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/SemaLambda.h"
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTLambda.h"
15 #include "clang/AST/CXXInheritance.h"
16 #include "clang/AST/ExprCXX.h"
17 #include "clang/AST/MangleNumberingContext.h"
18 #include "clang/Basic/TargetInfo.h"
19 #include "clang/Sema/DeclSpec.h"
20 #include "clang/Sema/Initialization.h"
21 #include "clang/Sema/Lookup.h"
22 #include "clang/Sema/Scope.h"
23 #include "clang/Sema/ScopeInfo.h"
24 #include "clang/Sema/SemaCUDA.h"
25 #include "clang/Sema/SemaInternal.h"
26 #include "clang/Sema/SemaOpenMP.h"
27 #include "clang/Sema/Template.h"
28 #include "llvm/ADT/STLExtras.h"
30 using namespace clang
;
33 /// Examines the FunctionScopeInfo stack to determine the nearest
34 /// enclosing lambda (to the current lambda) that is 'capture-ready' for
35 /// the variable referenced in the current lambda (i.e. \p VarToCapture).
36 /// If successful, returns the index into Sema's FunctionScopeInfo stack
37 /// of the capture-ready lambda's LambdaScopeInfo.
39 /// Climbs down the stack of lambdas (deepest nested lambda - i.e. current
40 /// lambda - is on top) to determine the index of the nearest enclosing/outer
41 /// lambda that is ready to capture the \p VarToCapture being referenced in
42 /// the current lambda.
43 /// As we climb down the stack, we want the index of the first such lambda -
44 /// that is the lambda with the highest index that is 'capture-ready'.
46 /// A lambda 'L' is capture-ready for 'V' (var or this) if:
47 /// - its enclosing context is non-dependent
48 /// - and if the chain of lambdas between L and the lambda in which
49 /// V is potentially used (i.e. the lambda at the top of the scope info
50 /// stack), can all capture or have already captured V.
51 /// If \p VarToCapture is 'null' then we are trying to capture 'this'.
53 /// Note that a lambda that is deemed 'capture-ready' still needs to be checked
54 /// for whether it is 'capture-capable' (see
55 /// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly
58 /// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
59 /// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
60 /// is at the top of the stack and has the highest index.
61 /// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
63 /// \returns An std::optional<unsigned> Index that if evaluates to 'true'
64 /// contains the index (into Sema's FunctionScopeInfo stack) of the innermost
65 /// lambda which is capture-ready. If the return value evaluates to 'false'
66 /// then no lambda is capture-ready for \p VarToCapture.
68 static inline std::optional
<unsigned>
69 getStackIndexOfNearestEnclosingCaptureReadyLambda(
70 ArrayRef
<const clang::sema::FunctionScopeInfo
*> FunctionScopes
,
71 ValueDecl
*VarToCapture
) {
72 // Label failure to capture.
73 const std::optional
<unsigned> NoLambdaIsCaptureReady
;
75 // Ignore all inner captured regions.
76 unsigned CurScopeIndex
= FunctionScopes
.size() - 1;
77 while (CurScopeIndex
> 0 && isa
<clang::sema::CapturedRegionScopeInfo
>(
78 FunctionScopes
[CurScopeIndex
]))
81 isa
<clang::sema::LambdaScopeInfo
>(FunctionScopes
[CurScopeIndex
]) &&
82 "The function on the top of sema's function-info stack must be a lambda");
84 // If VarToCapture is null, we are attempting to capture 'this'.
85 const bool IsCapturingThis
= !VarToCapture
;
86 const bool IsCapturingVariable
= !IsCapturingThis
;
88 // Start with the current lambda at the top of the stack (highest index).
89 DeclContext
*EnclosingDC
=
90 cast
<sema::LambdaScopeInfo
>(FunctionScopes
[CurScopeIndex
])->CallOperator
;
93 const clang::sema::LambdaScopeInfo
*LSI
=
94 cast
<sema::LambdaScopeInfo
>(FunctionScopes
[CurScopeIndex
]);
95 // IF we have climbed down to an intervening enclosing lambda that contains
96 // the variable declaration - it obviously can/must not capture the
98 // Since its enclosing DC is dependent, all the lambdas between it and the
99 // innermost nested lambda are dependent (otherwise we wouldn't have
100 // arrived here) - so we don't yet have a lambda that can capture the
102 if (IsCapturingVariable
&&
103 VarToCapture
->getDeclContext()->Equals(EnclosingDC
))
104 return NoLambdaIsCaptureReady
;
106 // For an enclosing lambda to be capture ready for an entity, all
107 // intervening lambda's have to be able to capture that entity. If even
108 // one of the intervening lambda's is not capable of capturing the entity
109 // then no enclosing lambda can ever capture that entity.
113 // [](auto b) { #2 <-- an intervening lambda that can never capture 'x'
115 // f(x, c); <-- can not lead to x's speculative capture by #1 or #2
117 // If they do not have a default implicit capture, check to see
118 // if the entity has already been explicitly captured.
119 // If even a single dependent enclosing lambda lacks the capability
120 // to ever capture this variable, there is no further enclosing
121 // non-dependent lambda that can capture this variable.
122 if (LSI
->ImpCaptureStyle
== sema::LambdaScopeInfo::ImpCap_None
) {
123 if (IsCapturingVariable
&& !LSI
->isCaptured(VarToCapture
))
124 return NoLambdaIsCaptureReady
;
125 if (IsCapturingThis
&& !LSI
->isCXXThisCaptured())
126 return NoLambdaIsCaptureReady
;
128 EnclosingDC
= getLambdaAwareParentOfDeclContext(EnclosingDC
);
130 assert(CurScopeIndex
);
132 } while (!EnclosingDC
->isTranslationUnit() &&
133 EnclosingDC
->isDependentContext() &&
134 isLambdaCallOperator(EnclosingDC
));
136 assert(CurScopeIndex
< (FunctionScopes
.size() - 1));
137 // If the enclosingDC is not dependent, then the immediately nested lambda
138 // (one index above) is capture-ready.
139 if (!EnclosingDC
->isDependentContext())
140 return CurScopeIndex
+ 1;
141 return NoLambdaIsCaptureReady
;
144 /// Examines the FunctionScopeInfo stack to determine the nearest
145 /// enclosing lambda (to the current lambda) that is 'capture-capable' for
146 /// the variable referenced in the current lambda (i.e. \p VarToCapture).
147 /// If successful, returns the index into Sema's FunctionScopeInfo stack
148 /// of the capture-capable lambda's LambdaScopeInfo.
150 /// Given the current stack of lambdas being processed by Sema and
151 /// the variable of interest, to identify the nearest enclosing lambda (to the
152 /// current lambda at the top of the stack) that can truly capture
153 /// a variable, it has to have the following two properties:
154 /// a) 'capture-ready' - be the innermost lambda that is 'capture-ready':
155 /// - climb down the stack (i.e. starting from the innermost and examining
156 /// each outer lambda step by step) checking if each enclosing
157 /// lambda can either implicitly or explicitly capture the variable.
158 /// Record the first such lambda that is enclosed in a non-dependent
159 /// context. If no such lambda currently exists return failure.
160 /// b) 'capture-capable' - make sure the 'capture-ready' lambda can truly
161 /// capture the variable by checking all its enclosing lambdas:
162 /// - check if all outer lambdas enclosing the 'capture-ready' lambda
163 /// identified above in 'a' can also capture the variable (this is done
164 /// via tryCaptureVariable for variables and CheckCXXThisCapture for
165 /// 'this' by passing in the index of the Lambda identified in step 'a')
167 /// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
168 /// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
169 /// is at the top of the stack.
171 /// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
174 /// \returns An std::optional<unsigned> Index that if evaluates to 'true'
175 /// contains the index (into Sema's FunctionScopeInfo stack) of the innermost
176 /// lambda which is capture-capable. If the return value evaluates to 'false'
177 /// then no lambda is capture-capable for \p VarToCapture.
179 std::optional
<unsigned>
180 clang::getStackIndexOfNearestEnclosingCaptureCapableLambda(
181 ArrayRef
<const sema::FunctionScopeInfo
*> FunctionScopes
,
182 ValueDecl
*VarToCapture
, Sema
&S
) {
184 const std::optional
<unsigned> NoLambdaIsCaptureCapable
;
186 const std::optional
<unsigned> OptionalStackIndex
=
187 getStackIndexOfNearestEnclosingCaptureReadyLambda(FunctionScopes
,
189 if (!OptionalStackIndex
)
190 return NoLambdaIsCaptureCapable
;
192 const unsigned IndexOfCaptureReadyLambda
= *OptionalStackIndex
;
193 assert(((IndexOfCaptureReadyLambda
!= (FunctionScopes
.size() - 1)) ||
194 S
.getCurGenericLambda()) &&
195 "The capture ready lambda for a potential capture can only be the "
196 "current lambda if it is a generic lambda");
198 const sema::LambdaScopeInfo
*const CaptureReadyLambdaLSI
=
199 cast
<sema::LambdaScopeInfo
>(FunctionScopes
[IndexOfCaptureReadyLambda
]);
201 // If VarToCapture is null, we are attempting to capture 'this'
202 const bool IsCapturingThis
= !VarToCapture
;
203 const bool IsCapturingVariable
= !IsCapturingThis
;
205 if (IsCapturingVariable
) {
206 // Check if the capture-ready lambda can truly capture the variable, by
207 // checking whether all enclosing lambdas of the capture-ready lambda allow
208 // the capture - i.e. make sure it is capture-capable.
209 QualType CaptureType
, DeclRefType
;
210 const bool CanCaptureVariable
=
211 !S
.tryCaptureVariable(VarToCapture
,
212 /*ExprVarIsUsedInLoc*/ SourceLocation(),
213 clang::Sema::TryCapture_Implicit
,
214 /*EllipsisLoc*/ SourceLocation(),
215 /*BuildAndDiagnose*/ false, CaptureType
,
216 DeclRefType
, &IndexOfCaptureReadyLambda
);
217 if (!CanCaptureVariable
)
218 return NoLambdaIsCaptureCapable
;
220 // Check if the capture-ready lambda can truly capture 'this' by checking
221 // whether all enclosing lambdas of the capture-ready lambda can capture
223 const bool CanCaptureThis
=
224 !S
.CheckCXXThisCapture(
225 CaptureReadyLambdaLSI
->PotentialThisCaptureLocation
,
226 /*Explicit*/ false, /*BuildAndDiagnose*/ false,
227 &IndexOfCaptureReadyLambda
);
229 return NoLambdaIsCaptureCapable
;
231 return IndexOfCaptureReadyLambda
;
234 static inline TemplateParameterList
*
235 getGenericLambdaTemplateParameterList(LambdaScopeInfo
*LSI
, Sema
&SemaRef
) {
236 if (!LSI
->GLTemplateParameterList
&& !LSI
->TemplateParams
.empty()) {
237 LSI
->GLTemplateParameterList
= TemplateParameterList::Create(
239 /*Template kw loc*/ SourceLocation(),
240 /*L angle loc*/ LSI
->ExplicitTemplateParamsRange
.getBegin(),
242 /*R angle loc*/LSI
->ExplicitTemplateParamsRange
.getEnd(),
243 LSI
->RequiresClause
.get());
245 return LSI
->GLTemplateParameterList
;
249 Sema::createLambdaClosureType(SourceRange IntroducerRange
, TypeSourceInfo
*Info
,
250 unsigned LambdaDependencyKind
,
251 LambdaCaptureDefault CaptureDefault
) {
252 DeclContext
*DC
= CurContext
;
253 while (!(DC
->isFunctionOrMethod() || DC
->isRecord() || DC
->isFileContext()))
254 DC
= DC
->getParent();
256 bool IsGenericLambda
=
257 Info
&& getGenericLambdaTemplateParameterList(getCurLambda(), *this);
258 // Start constructing the lambda class.
259 CXXRecordDecl
*Class
= CXXRecordDecl::CreateLambda(
260 Context
, DC
, Info
, IntroducerRange
.getBegin(), LambdaDependencyKind
,
261 IsGenericLambda
, CaptureDefault
);
267 /// Determine whether the given context is or is enclosed in an inline
269 static bool isInInlineFunction(const DeclContext
*DC
) {
270 while (!DC
->isFileContext()) {
271 if (const FunctionDecl
*FD
= dyn_cast
<FunctionDecl
>(DC
))
275 DC
= DC
->getLexicalParent();
281 std::tuple
<MangleNumberingContext
*, Decl
*>
282 Sema::getCurrentMangleNumberContext(const DeclContext
*DC
) {
283 // Compute the context for allocating mangling numbers in the current
284 // expression, if the ABI requires them.
285 Decl
*ManglingContextDecl
= ExprEvalContexts
.back().ManglingContextDecl
;
296 bool IsInNonspecializedTemplate
=
297 inTemplateInstantiation() || CurContext
->isDependentContext();
299 // Default arguments of member function parameters that appear in a class
300 // definition, as well as the initializers of data members, receive special
301 // treatment. Identify them.
302 if (ManglingContextDecl
) {
303 if (ParmVarDecl
*Param
= dyn_cast
<ParmVarDecl
>(ManglingContextDecl
)) {
304 if (const DeclContext
*LexicalDC
305 = Param
->getDeclContext()->getLexicalParent())
306 if (LexicalDC
->isRecord())
307 Kind
= DefaultArgument
;
308 } else if (VarDecl
*Var
= dyn_cast
<VarDecl
>(ManglingContextDecl
)) {
309 if (Var
->getMostRecentDecl()->isInline())
310 Kind
= InlineVariable
;
311 else if (Var
->getDeclContext()->isRecord() && IsInNonspecializedTemplate
)
312 Kind
= TemplatedVariable
;
313 else if (Var
->getDescribedVarTemplate())
314 Kind
= TemplatedVariable
;
315 else if (auto *VTS
= dyn_cast
<VarTemplateSpecializationDecl
>(Var
)) {
316 if (!VTS
->isExplicitSpecialization())
317 Kind
= TemplatedVariable
;
319 } else if (isa
<FieldDecl
>(ManglingContextDecl
)) {
321 } else if (isa
<ImplicitConceptSpecializationDecl
>(ManglingContextDecl
)) {
326 // Itanium ABI [5.1.7]:
327 // In the following contexts [...] the one-definition rule requires closure
328 // types in different translation units to "correspond":
331 // -- the bodies of inline or templated functions
332 if ((IsInNonspecializedTemplate
&&
333 !(ManglingContextDecl
&& isa
<ParmVarDecl
>(ManglingContextDecl
))) ||
334 isInInlineFunction(CurContext
)) {
335 while (auto *CD
= dyn_cast
<CapturedDecl
>(DC
))
336 DC
= CD
->getParent();
337 return std::make_tuple(&Context
.getManglingNumberContext(DC
), nullptr);
340 return std::make_tuple(nullptr, nullptr);
344 // Concept definitions aren't code generated and thus aren't mangled,
345 // however the ManglingContextDecl is important for the purposes of
346 // re-forming the template argument list of the lambda for constraint
349 // -- default member initializers
350 case DefaultArgument
:
351 // -- default arguments appearing in class definitions
353 case TemplatedVariable
:
354 // -- the initializers of inline or templated variables
355 return std::make_tuple(
356 &Context
.getManglingNumberContext(ASTContext::NeedExtraManglingDecl
,
357 ManglingContextDecl
),
358 ManglingContextDecl
);
361 llvm_unreachable("unexpected context");
365 buildTypeForLambdaCallOperator(Sema
&S
, clang::CXXRecordDecl
*Class
,
366 TemplateParameterList
*TemplateParams
,
367 TypeSourceInfo
*MethodTypeInfo
) {
368 assert(MethodTypeInfo
&& "expected a non null type");
370 QualType MethodType
= MethodTypeInfo
->getType();
371 // If a lambda appears in a dependent context or is a generic lambda (has
372 // template parameters) and has an 'auto' return type, deduce it to a
374 if (Class
->isDependentContext() || TemplateParams
) {
375 const FunctionProtoType
*FPT
= MethodType
->castAs
<FunctionProtoType
>();
376 QualType Result
= FPT
->getReturnType();
377 if (Result
->isUndeducedType()) {
378 Result
= S
.SubstAutoTypeDependent(Result
);
379 MethodType
= S
.Context
.getFunctionType(Result
, FPT
->getParamTypes(),
380 FPT
->getExtProtoInfo());
386 // [C++2b] [expr.prim.lambda.closure] p4
387 // Given a lambda with a lambda-capture, the type of the explicit object
388 // parameter, if any, of the lambda's function call operator (possibly
389 // instantiated from a function call operator template) shall be either:
390 // - the closure type,
391 // - class type publicly and unambiguously derived from the closure type, or
392 // - a reference to a possibly cv-qualified such type.
393 bool Sema::DiagnoseInvalidExplicitObjectParameterInLambda(
394 CXXMethodDecl
*Method
, SourceLocation CallLoc
) {
395 if (!isLambdaCallWithExplicitObjectParameter(Method
))
397 CXXRecordDecl
*RD
= Method
->getParent();
398 if (Method
->getType()->isDependentType())
400 if (RD
->isCapturelessLambda())
403 ParmVarDecl
*Param
= Method
->getParamDecl(0);
404 QualType ExplicitObjectParameterType
= Param
->getType()
405 .getNonReferenceType()
406 .getUnqualifiedType()
407 .getDesugaredType(getASTContext());
408 QualType LambdaType
= getASTContext().getRecordType(RD
);
409 if (LambdaType
== ExplicitObjectParameterType
)
412 // Don't check the same instantiation twice.
414 // If this call operator is ill-formed, there is no point in issuing
415 // a diagnostic every time it is called because the problem is in the
416 // definition of the derived type, not at the call site.
418 // FIXME: Move this check to where we instantiate the method? This should
419 // be possible, but the naive approach of just marking the method as invalid
420 // leads to us emitting more diagnostics than we should have to for this case
421 // (1 error here *and* 1 error about there being no matching overload at the
422 // call site). It might be possible to avoid that by also checking if there
423 // is an empty cast path for the method stored in the context (signalling that
424 // we've already diagnosed it) and then just not building the call, but that
425 // doesn't really seem any simpler than diagnosing it at the call site...
426 auto [It
, Inserted
] = Context
.LambdaCastPaths
.try_emplace(Method
);
428 return It
->second
.empty();
430 CXXCastPath
&Path
= It
->second
;
431 CXXBasePaths
Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
432 /*DetectVirtual=*/false);
433 if (!IsDerivedFrom(RD
->getLocation(), ExplicitObjectParameterType
, LambdaType
,
435 Diag(Param
->getLocation(), diag::err_invalid_explicit_object_type_in_lambda
)
436 << ExplicitObjectParameterType
;
440 if (Paths
.isAmbiguous(LambdaType
->getCanonicalTypeUnqualified())) {
441 std::string PathsDisplay
= getAmbiguousPathsDisplayString(Paths
);
442 Diag(CallLoc
, diag::err_explicit_object_lambda_ambiguous_base
)
443 << LambdaType
<< PathsDisplay
;
447 if (CheckBaseClassAccess(CallLoc
, LambdaType
, ExplicitObjectParameterType
,
449 diag::err_explicit_object_lambda_inaccessible_base
))
452 BuildBasePathArray(Paths
, Path
);
456 void Sema::handleLambdaNumbering(
457 CXXRecordDecl
*Class
, CXXMethodDecl
*Method
,
458 std::optional
<CXXRecordDecl::LambdaNumbering
> NumberingOverride
) {
459 if (NumberingOverride
) {
460 Class
->setLambdaNumbering(*NumberingOverride
);
464 ContextRAII
ManglingContext(*this, Class
->getDeclContext());
466 auto getMangleNumberingContext
=
467 [this](CXXRecordDecl
*Class
,
468 Decl
*ManglingContextDecl
) -> MangleNumberingContext
* {
469 // Get mangle numbering context if there's any extra decl context.
470 if (ManglingContextDecl
)
471 return &Context
.getManglingNumberContext(
472 ASTContext::NeedExtraManglingDecl
, ManglingContextDecl
);
473 // Otherwise, from that lambda's decl context.
474 auto DC
= Class
->getDeclContext();
475 while (auto *CD
= dyn_cast
<CapturedDecl
>(DC
))
476 DC
= CD
->getParent();
477 return &Context
.getManglingNumberContext(DC
);
480 CXXRecordDecl::LambdaNumbering Numbering
;
481 MangleNumberingContext
*MCtx
;
482 std::tie(MCtx
, Numbering
.ContextDecl
) =
483 getCurrentMangleNumberContext(Class
->getDeclContext());
484 if (!MCtx
&& (getLangOpts().CUDA
|| getLangOpts().SYCLIsDevice
||
485 getLangOpts().SYCLIsHost
)) {
486 // Force lambda numbering in CUDA/HIP as we need to name lambdas following
487 // ODR. Both device- and host-compilation need to have a consistent naming
488 // on kernel functions. As lambdas are potential part of these `__global__`
489 // function names, they needs numbering following ODR.
490 // Also force for SYCL, since we need this for the
491 // __builtin_sycl_unique_stable_name implementation, which depends on lambda
493 MCtx
= getMangleNumberingContext(Class
, Numbering
.ContextDecl
);
494 assert(MCtx
&& "Retrieving mangle numbering context failed!");
495 Numbering
.HasKnownInternalLinkage
= true;
498 Numbering
.IndexInContext
= MCtx
->getNextLambdaIndex();
499 Numbering
.ManglingNumber
= MCtx
->getManglingNumber(Method
);
500 Numbering
.DeviceManglingNumber
= MCtx
->getDeviceManglingNumber(Method
);
501 Class
->setLambdaNumbering(Numbering
);
504 dyn_cast_or_null
<ExternalSemaSource
>(Context
.getExternalSource()))
505 Source
->AssignedLambdaNumbering(Class
);
509 static void buildLambdaScopeReturnType(Sema
&S
, LambdaScopeInfo
*LSI
,
510 CXXMethodDecl
*CallOperator
,
511 bool ExplicitResultType
) {
512 if (ExplicitResultType
) {
513 LSI
->HasImplicitReturnType
= false;
514 LSI
->ReturnType
= CallOperator
->getReturnType();
515 if (!LSI
->ReturnType
->isDependentType() && !LSI
->ReturnType
->isVoidType())
516 S
.RequireCompleteType(CallOperator
->getBeginLoc(), LSI
->ReturnType
,
517 diag::err_lambda_incomplete_result
);
519 LSI
->HasImplicitReturnType
= true;
523 void Sema::buildLambdaScope(LambdaScopeInfo
*LSI
, CXXMethodDecl
*CallOperator
,
524 SourceRange IntroducerRange
,
525 LambdaCaptureDefault CaptureDefault
,
526 SourceLocation CaptureDefaultLoc
,
527 bool ExplicitParams
, bool Mutable
) {
528 LSI
->CallOperator
= CallOperator
;
529 CXXRecordDecl
*LambdaClass
= CallOperator
->getParent();
530 LSI
->Lambda
= LambdaClass
;
531 if (CaptureDefault
== LCD_ByCopy
)
532 LSI
->ImpCaptureStyle
= LambdaScopeInfo::ImpCap_LambdaByval
;
533 else if (CaptureDefault
== LCD_ByRef
)
534 LSI
->ImpCaptureStyle
= LambdaScopeInfo::ImpCap_LambdaByref
;
535 LSI
->CaptureDefaultLoc
= CaptureDefaultLoc
;
536 LSI
->IntroducerRange
= IntroducerRange
;
537 LSI
->ExplicitParams
= ExplicitParams
;
538 LSI
->Mutable
= Mutable
;
541 void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo
*LSI
) {
542 LSI
->finishedExplicitCaptures();
545 void Sema::ActOnLambdaExplicitTemplateParameterList(
546 LambdaIntroducer
&Intro
, SourceLocation LAngleLoc
,
547 ArrayRef
<NamedDecl
*> TParams
, SourceLocation RAngleLoc
,
548 ExprResult RequiresClause
) {
549 LambdaScopeInfo
*LSI
= getCurLambda();
550 assert(LSI
&& "Expected a lambda scope");
551 assert(LSI
->NumExplicitTemplateParams
== 0 &&
552 "Already acted on explicit template parameters");
553 assert(LSI
->TemplateParams
.empty() &&
554 "Explicit template parameters should come "
555 "before invented (auto) ones");
556 assert(!TParams
.empty() &&
557 "No template parameters to act on");
558 LSI
->TemplateParams
.append(TParams
.begin(), TParams
.end());
559 LSI
->NumExplicitTemplateParams
= TParams
.size();
560 LSI
->ExplicitTemplateParamsRange
= {LAngleLoc
, RAngleLoc
};
561 LSI
->RequiresClause
= RequiresClause
;
564 /// If this expression is an enumerator-like expression of some type
565 /// T, return the type T; otherwise, return null.
567 /// Pointer comparisons on the result here should always work because
568 /// it's derived from either the parent of an EnumConstantDecl
569 /// (i.e. the definition) or the declaration returned by
570 /// EnumType::getDecl() (i.e. the definition).
571 static EnumDecl
*findEnumForBlockReturn(Expr
*E
) {
572 // An expression is an enumerator-like expression of type T if,
573 // ignoring parens and parens-like expressions:
574 E
= E
->IgnoreParens();
576 // - it is an enumerator whose enum type is T or
577 if (DeclRefExpr
*DRE
= dyn_cast
<DeclRefExpr
>(E
)) {
578 if (EnumConstantDecl
*D
579 = dyn_cast
<EnumConstantDecl
>(DRE
->getDecl())) {
580 return cast
<EnumDecl
>(D
->getDeclContext());
585 // - it is a comma expression whose RHS is an enumerator-like
586 // expression of type T or
587 if (BinaryOperator
*BO
= dyn_cast
<BinaryOperator
>(E
)) {
588 if (BO
->getOpcode() == BO_Comma
)
589 return findEnumForBlockReturn(BO
->getRHS());
593 // - it is a statement-expression whose value expression is an
594 // enumerator-like expression of type T or
595 if (StmtExpr
*SE
= dyn_cast
<StmtExpr
>(E
)) {
596 if (Expr
*last
= dyn_cast_or_null
<Expr
>(SE
->getSubStmt()->body_back()))
597 return findEnumForBlockReturn(last
);
601 // - it is a ternary conditional operator (not the GNU ?:
602 // extension) whose second and third operands are
603 // enumerator-like expressions of type T or
604 if (ConditionalOperator
*CO
= dyn_cast
<ConditionalOperator
>(E
)) {
605 if (EnumDecl
*ED
= findEnumForBlockReturn(CO
->getTrueExpr()))
606 if (ED
== findEnumForBlockReturn(CO
->getFalseExpr()))
612 // - it is an implicit integral conversion applied to an
613 // enumerator-like expression of type T or
614 if (ImplicitCastExpr
*ICE
= dyn_cast
<ImplicitCastExpr
>(E
)) {
615 // We can sometimes see integral conversions in valid
616 // enumerator-like expressions.
617 if (ICE
->getCastKind() == CK_IntegralCast
)
618 return findEnumForBlockReturn(ICE
->getSubExpr());
620 // Otherwise, just rely on the type.
623 // - it is an expression of that formal enum type.
624 if (const EnumType
*ET
= E
->getType()->getAs
<EnumType
>()) {
625 return ET
->getDecl();
632 /// Attempt to find a type T for which the returned expression of the
633 /// given statement is an enumerator-like expression of that type.
634 static EnumDecl
*findEnumForBlockReturn(ReturnStmt
*ret
) {
635 if (Expr
*retValue
= ret
->getRetValue())
636 return findEnumForBlockReturn(retValue
);
640 /// Attempt to find a common type T for which all of the returned
641 /// expressions in a block are enumerator-like expressions of that
643 static EnumDecl
*findCommonEnumForBlockReturns(ArrayRef
<ReturnStmt
*> returns
) {
644 ArrayRef
<ReturnStmt
*>::iterator i
= returns
.begin(), e
= returns
.end();
646 // Try to find one for the first return.
647 EnumDecl
*ED
= findEnumForBlockReturn(*i
);
648 if (!ED
) return nullptr;
650 // Check that the rest of the returns have the same enum.
651 for (++i
; i
!= e
; ++i
) {
652 if (findEnumForBlockReturn(*i
) != ED
)
656 // Never infer an anonymous enum type.
657 if (!ED
->hasNameForLinkage()) return nullptr;
662 /// Adjust the given return statements so that they formally return
663 /// the given type. It should require, at most, an IntegralCast.
664 static void adjustBlockReturnsToEnum(Sema
&S
, ArrayRef
<ReturnStmt
*> returns
,
665 QualType returnType
) {
666 for (ArrayRef
<ReturnStmt
*>::iterator
667 i
= returns
.begin(), e
= returns
.end(); i
!= e
; ++i
) {
668 ReturnStmt
*ret
= *i
;
669 Expr
*retValue
= ret
->getRetValue();
670 if (S
.Context
.hasSameType(retValue
->getType(), returnType
))
673 // Right now we only support integral fixup casts.
674 assert(returnType
->isIntegralOrUnscopedEnumerationType());
675 assert(retValue
->getType()->isIntegralOrUnscopedEnumerationType());
677 ExprWithCleanups
*cleanups
= dyn_cast
<ExprWithCleanups
>(retValue
);
679 Expr
*E
= (cleanups
? cleanups
->getSubExpr() : retValue
);
680 E
= ImplicitCastExpr::Create(S
.Context
, returnType
, CK_IntegralCast
, E
,
681 /*base path*/ nullptr, VK_PRValue
,
682 FPOptionsOverride());
684 cleanups
->setSubExpr(E
);
691 void Sema::deduceClosureReturnType(CapturingScopeInfo
&CSI
) {
692 assert(CSI
.HasImplicitReturnType
);
693 // If it was ever a placeholder, it had to been deduced to DependentTy.
694 assert(CSI
.ReturnType
.isNull() || !CSI
.ReturnType
->isUndeducedType());
695 assert((!isa
<LambdaScopeInfo
>(CSI
) || !getLangOpts().CPlusPlus14
) &&
696 "lambda expressions use auto deduction in C++14 onwards");
698 // C++ core issue 975:
699 // If a lambda-expression does not include a trailing-return-type,
700 // it is as if the trailing-return-type denotes the following type:
701 // - if there are no return statements in the compound-statement,
702 // or all return statements return either an expression of type
703 // void or no expression or braced-init-list, the type void;
704 // - otherwise, if all return statements return an expression
705 // and the types of the returned expressions after
706 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
707 // array-to-pointer conversion (4.2 [conv.array]), and
708 // function-to-pointer conversion (4.3 [conv.func]) are the
709 // same, that common type;
710 // - otherwise, the program is ill-formed.
712 // C++ core issue 1048 additionally removes top-level cv-qualifiers
713 // from the types of returned expressions to match the C++14 auto
716 // In addition, in blocks in non-C++ modes, if all of the return
717 // statements are enumerator-like expressions of some type T, where
718 // T has a name for linkage, then we infer the return type of the
719 // block to be that type.
721 // First case: no return statements, implicit void return type.
722 ASTContext
&Ctx
= getASTContext();
723 if (CSI
.Returns
.empty()) {
724 // It's possible there were simply no /valid/ return statements.
725 // In this case, the first one we found may have at least given us a type.
726 if (CSI
.ReturnType
.isNull())
727 CSI
.ReturnType
= Ctx
.VoidTy
;
731 // Second case: at least one return statement has dependent type.
732 // Delay type checking until instantiation.
733 assert(!CSI
.ReturnType
.isNull() && "We should have a tentative return type.");
734 if (CSI
.ReturnType
->isDependentType())
737 // Try to apply the enum-fuzz rule.
738 if (!getLangOpts().CPlusPlus
) {
739 assert(isa
<BlockScopeInfo
>(CSI
));
740 const EnumDecl
*ED
= findCommonEnumForBlockReturns(CSI
.Returns
);
742 CSI
.ReturnType
= Context
.getTypeDeclType(ED
);
743 adjustBlockReturnsToEnum(*this, CSI
.Returns
, CSI
.ReturnType
);
748 // Third case: only one return statement. Don't bother doing extra work!
749 if (CSI
.Returns
.size() == 1)
752 // General case: many return statements.
753 // Check that they all have compatible return types.
755 // We require the return types to strictly match here.
756 // Note that we've already done the required promotions as part of
757 // processing the return statement.
758 for (const ReturnStmt
*RS
: CSI
.Returns
) {
759 const Expr
*RetE
= RS
->getRetValue();
761 QualType ReturnType
=
762 (RetE
? RetE
->getType() : Context
.VoidTy
).getUnqualifiedType();
763 if (Context
.getCanonicalFunctionResultType(ReturnType
) ==
764 Context
.getCanonicalFunctionResultType(CSI
.ReturnType
)) {
765 // Use the return type with the strictest possible nullability annotation.
766 auto RetTyNullability
= ReturnType
->getNullability();
767 auto BlockNullability
= CSI
.ReturnType
->getNullability();
768 if (BlockNullability
&&
769 (!RetTyNullability
||
770 hasWeakerNullability(*RetTyNullability
, *BlockNullability
)))
771 CSI
.ReturnType
= ReturnType
;
775 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
776 // TODO: It's possible that the *first* return is the divergent one.
777 Diag(RS
->getBeginLoc(),
778 diag::err_typecheck_missing_return_type_incompatible
)
779 << ReturnType
<< CSI
.ReturnType
<< isa
<LambdaScopeInfo
>(CSI
);
780 // Continue iterating so that we keep emitting diagnostics.
784 QualType
Sema::buildLambdaInitCaptureInitialization(
785 SourceLocation Loc
, bool ByRef
, SourceLocation EllipsisLoc
,
786 std::optional
<unsigned> NumExpansions
, IdentifierInfo
*Id
,
787 bool IsDirectInit
, Expr
*&Init
) {
788 // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to
790 QualType DeductType
= Context
.getAutoDeductType();
792 AutoTypeLoc TL
= TLB
.push
<AutoTypeLoc
>(DeductType
);
795 DeductType
= BuildReferenceType(DeductType
, true, Loc
, Id
);
796 assert(!DeductType
.isNull() && "can't build reference to auto");
797 TLB
.push
<ReferenceTypeLoc
>(DeductType
).setSigilLoc(Loc
);
799 if (EllipsisLoc
.isValid()) {
800 if (Init
->containsUnexpandedParameterPack()) {
801 Diag(EllipsisLoc
, getLangOpts().CPlusPlus20
802 ? diag::warn_cxx17_compat_init_capture_pack
803 : diag::ext_init_capture_pack
);
804 DeductType
= Context
.getPackExpansionType(DeductType
, NumExpansions
,
805 /*ExpectPackInType=*/false);
806 TLB
.push
<PackExpansionTypeLoc
>(DeductType
).setEllipsisLoc(EllipsisLoc
);
808 // Just ignore the ellipsis for now and form a non-pack variable. We'll
809 // diagnose this later when we try to capture it.
812 TypeSourceInfo
*TSI
= TLB
.getTypeSourceInfo(Context
, DeductType
);
814 // Deduce the type of the init capture.
815 QualType DeducedType
= deduceVarTypeFromInitializer(
816 /*VarDecl*/nullptr, DeclarationName(Id
), DeductType
, TSI
,
817 SourceRange(Loc
, Loc
), IsDirectInit
, Init
);
818 if (DeducedType
.isNull())
821 // Are we a non-list direct initialization?
822 ParenListExpr
*CXXDirectInit
= dyn_cast
<ParenListExpr
>(Init
);
824 // Perform initialization analysis and ensure any implicit conversions
825 // (such as lvalue-to-rvalue) are enforced.
826 InitializedEntity Entity
=
827 InitializedEntity::InitializeLambdaCapture(Id
, DeducedType
, Loc
);
828 InitializationKind Kind
=
830 ? (CXXDirectInit
? InitializationKind::CreateDirect(
831 Loc
, Init
->getBeginLoc(), Init
->getEndLoc())
832 : InitializationKind::CreateDirectList(Loc
))
833 : InitializationKind::CreateCopy(Loc
, Init
->getBeginLoc());
835 MultiExprArg Args
= Init
;
838 MultiExprArg(CXXDirectInit
->getExprs(), CXXDirectInit
->getNumExprs());
840 InitializationSequence
InitSeq(*this, Entity
, Kind
, Args
);
841 ExprResult Result
= InitSeq
.Perform(*this, Entity
, Kind
, Args
, &DclT
);
843 if (Result
.isInvalid())
846 Init
= Result
.getAs
<Expr
>();
850 VarDecl
*Sema::createLambdaInitCaptureVarDecl(
851 SourceLocation Loc
, QualType InitCaptureType
, SourceLocation EllipsisLoc
,
852 IdentifierInfo
*Id
, unsigned InitStyle
, Expr
*Init
, DeclContext
*DeclCtx
) {
853 // FIXME: Retain the TypeSourceInfo from buildLambdaInitCaptureInitialization
854 // rather than reconstructing it here.
855 TypeSourceInfo
*TSI
= Context
.getTrivialTypeSourceInfo(InitCaptureType
, Loc
);
856 if (auto PETL
= TSI
->getTypeLoc().getAs
<PackExpansionTypeLoc
>())
857 PETL
.setEllipsisLoc(EllipsisLoc
);
859 // Create a dummy variable representing the init-capture. This is not actually
860 // used as a variable, and only exists as a way to name and refer to the
862 // FIXME: Pass in separate source locations for '&' and identifier.
863 VarDecl
*NewVD
= VarDecl::Create(Context
, DeclCtx
, Loc
, Loc
, Id
,
864 InitCaptureType
, TSI
, SC_Auto
);
865 NewVD
->setInitCapture(true);
866 NewVD
->setReferenced(true);
867 // FIXME: Pass in a VarDecl::InitializationStyle.
868 NewVD
->setInitStyle(static_cast<VarDecl::InitializationStyle
>(InitStyle
));
869 NewVD
->markUsed(Context
);
870 NewVD
->setInit(Init
);
871 if (NewVD
->isParameterPack())
872 getCurLambda()->LocalPacks
.push_back(NewVD
);
876 void Sema::addInitCapture(LambdaScopeInfo
*LSI
, VarDecl
*Var
, bool ByRef
) {
877 assert(Var
->isInitCapture() && "init capture flag should be set");
878 LSI
->addCapture(Var
, /*isBlock=*/false, ByRef
,
879 /*isNested=*/false, Var
->getLocation(), SourceLocation(),
880 Var
->getType(), /*Invalid=*/false);
883 // Unlike getCurLambda, getCurrentLambdaScopeUnsafe doesn't
884 // check that the current lambda is in a consistent or fully constructed state.
885 static LambdaScopeInfo
*getCurrentLambdaScopeUnsafe(Sema
&S
) {
886 assert(!S
.FunctionScopes
.empty());
887 return cast
<LambdaScopeInfo
>(S
.FunctionScopes
[S
.FunctionScopes
.size() - 1]);
890 static TypeSourceInfo
*
891 getDummyLambdaType(Sema
&S
, SourceLocation Loc
= SourceLocation()) {
892 // C++11 [expr.prim.lambda]p4:
893 // If a lambda-expression does not include a lambda-declarator, it is as
894 // if the lambda-declarator were ().
895 FunctionProtoType::ExtProtoInfo
EPI(S
.Context
.getDefaultCallingConvention(
896 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
897 EPI
.HasTrailingReturn
= true;
898 EPI
.TypeQuals
.addConst();
899 LangAS AS
= S
.getDefaultCXXMethodAddrSpace();
900 if (AS
!= LangAS::Default
)
901 EPI
.TypeQuals
.addAddressSpace(AS
);
903 // C++1y [expr.prim.lambda]:
904 // The lambda return type is 'auto', which is replaced by the
905 // trailing-return type if provided and/or deduced from 'return'
907 // We don't do this before C++1y, because we don't support deduced return
909 QualType DefaultTypeForNoTrailingReturn
= S
.getLangOpts().CPlusPlus14
910 ? S
.Context
.getAutoDeductType()
911 : S
.Context
.DependentTy
;
913 S
.Context
.getFunctionType(DefaultTypeForNoTrailingReturn
, {}, EPI
);
914 return S
.Context
.getTrivialTypeSourceInfo(MethodTy
, Loc
);
917 static TypeSourceInfo
*getLambdaType(Sema
&S
, LambdaIntroducer
&Intro
,
918 Declarator
&ParamInfo
, Scope
*CurScope
,
920 bool &ExplicitResultType
) {
922 ExplicitResultType
= false;
925 (ParamInfo
.getDeclSpec().getStorageClassSpec() ==
926 DeclSpec::SCS_unspecified
||
927 ParamInfo
.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static
) &&
928 "Unexpected storage specifier");
929 bool IsLambdaStatic
=
930 ParamInfo
.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static
;
932 TypeSourceInfo
*MethodTyInfo
;
934 if (ParamInfo
.getNumTypeObjects() == 0) {
935 MethodTyInfo
= getDummyLambdaType(S
, Loc
);
937 // Check explicit parameters
938 S
.CheckExplicitObjectLambda(ParamInfo
);
940 DeclaratorChunk::FunctionTypeInfo
&FTI
= ParamInfo
.getFunctionTypeInfo();
942 bool HasExplicitObjectParameter
=
943 ParamInfo
.isExplicitObjectMemberFunction();
945 ExplicitResultType
= FTI
.hasTrailingReturnType();
946 if (!FTI
.hasMutableQualifier() && !IsLambdaStatic
&&
947 !HasExplicitObjectParameter
)
948 FTI
.getOrCreateMethodQualifiers().SetTypeQual(DeclSpec::TQ_const
, Loc
);
950 if (ExplicitResultType
&& S
.getLangOpts().HLSL
) {
951 QualType RetTy
= FTI
.getTrailingReturnType().get();
952 if (!RetTy
.isNull()) {
953 // HLSL does not support specifying an address space on a lambda return
955 LangAS AddressSpace
= RetTy
.getAddressSpace();
956 if (AddressSpace
!= LangAS::Default
)
957 S
.Diag(FTI
.getTrailingReturnTypeLoc(),
958 diag::err_return_value_with_address_space
);
962 MethodTyInfo
= S
.GetTypeForDeclarator(ParamInfo
);
963 assert(MethodTyInfo
&& "no type from lambda-declarator");
965 // Check for unexpanded parameter packs in the method type.
966 if (MethodTyInfo
->getType()->containsUnexpandedParameterPack())
967 S
.DiagnoseUnexpandedParameterPack(Intro
.Range
.getBegin(), MethodTyInfo
,
968 S
.UPPC_DeclarationType
);
973 CXXMethodDecl
*Sema::CreateLambdaCallOperator(SourceRange IntroducerRange
,
974 CXXRecordDecl
*Class
) {
976 // C++20 [expr.prim.lambda.closure]p3:
977 // The closure type for a lambda-expression has a public inline function
978 // call operator (for a non-generic lambda) or function call operator
979 // template (for a generic lambda) whose parameters and return type are
980 // described by the lambda-expression's parameter-declaration-clause
981 // and trailing-return-type respectively.
982 DeclarationName MethodName
=
983 Context
.DeclarationNames
.getCXXOperatorName(OO_Call
);
984 DeclarationNameLoc MethodNameLoc
=
985 DeclarationNameLoc::makeCXXOperatorNameLoc(IntroducerRange
.getBegin());
986 CXXMethodDecl
*Method
= CXXMethodDecl::Create(
987 Context
, Class
, SourceLocation(),
988 DeclarationNameInfo(MethodName
, IntroducerRange
.getBegin(),
990 QualType(), /*Tinfo=*/nullptr, SC_None
,
991 getCurFPFeatures().isFPConstrained(),
992 /*isInline=*/true, ConstexprSpecKind::Unspecified
, SourceLocation(),
993 /*TrailingRequiresClause=*/nullptr);
994 Method
->setAccess(AS_public
);
998 void Sema::AddTemplateParametersToLambdaCallOperator(
999 CXXMethodDecl
*CallOperator
, CXXRecordDecl
*Class
,
1000 TemplateParameterList
*TemplateParams
) {
1001 assert(TemplateParams
&& "no template parameters");
1002 FunctionTemplateDecl
*TemplateMethod
= FunctionTemplateDecl::Create(
1003 Context
, Class
, CallOperator
->getLocation(), CallOperator
->getDeclName(),
1004 TemplateParams
, CallOperator
);
1005 TemplateMethod
->setAccess(AS_public
);
1006 CallOperator
->setDescribedFunctionTemplate(TemplateMethod
);
1009 void Sema::CompleteLambdaCallOperator(
1010 CXXMethodDecl
*Method
, SourceLocation LambdaLoc
,
1011 SourceLocation CallOperatorLoc
, Expr
*TrailingRequiresClause
,
1012 TypeSourceInfo
*MethodTyInfo
, ConstexprSpecKind ConstexprKind
,
1013 StorageClass SC
, ArrayRef
<ParmVarDecl
*> Params
,
1014 bool HasExplicitResultType
) {
1016 LambdaScopeInfo
*LSI
= getCurrentLambdaScopeUnsafe(*this);
1018 if (TrailingRequiresClause
)
1019 Method
->setTrailingRequiresClause(TrailingRequiresClause
);
1021 TemplateParameterList
*TemplateParams
=
1022 getGenericLambdaTemplateParameterList(LSI
, *this);
1024 DeclContext
*DC
= Method
->getLexicalDeclContext();
1025 // DeclContext::addDecl() assumes that the DeclContext we're adding to is the
1026 // lexical context of the Method. Do so.
1027 Method
->setLexicalDeclContext(LSI
->Lambda
);
1028 if (TemplateParams
) {
1029 FunctionTemplateDecl
*TemplateMethod
=
1030 Method
->getDescribedFunctionTemplate();
1031 assert(TemplateMethod
&&
1032 "AddTemplateParametersToLambdaCallOperator should have been called");
1034 LSI
->Lambda
->addDecl(TemplateMethod
);
1035 TemplateMethod
->setLexicalDeclContext(DC
);
1037 LSI
->Lambda
->addDecl(Method
);
1039 LSI
->Lambda
->setLambdaIsGeneric(TemplateParams
);
1040 LSI
->Lambda
->setLambdaTypeInfo(MethodTyInfo
);
1042 Method
->setLexicalDeclContext(DC
);
1043 Method
->setLocation(LambdaLoc
);
1044 Method
->setInnerLocStart(CallOperatorLoc
);
1045 Method
->setTypeSourceInfo(MethodTyInfo
);
1046 Method
->setType(buildTypeForLambdaCallOperator(*this, LSI
->Lambda
,
1047 TemplateParams
, MethodTyInfo
));
1048 Method
->setConstexprKind(ConstexprKind
);
1049 Method
->setStorageClass(SC
);
1050 if (!Params
.empty()) {
1051 CheckParmsForFunctionDef(Params
, /*CheckParameterNames=*/false);
1052 Method
->setParams(Params
);
1053 for (auto P
: Method
->parameters()) {
1054 assert(P
&& "null in a parameter list");
1055 P
->setOwningFunction(Method
);
1059 buildLambdaScopeReturnType(*this, LSI
, Method
, HasExplicitResultType
);
1062 void Sema::ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer
&Intro
,
1063 Scope
*CurrentScope
) {
1065 LambdaScopeInfo
*LSI
= getCurLambda();
1066 assert(LSI
&& "LambdaScopeInfo should be on stack!");
1068 if (Intro
.Default
== LCD_ByCopy
)
1069 LSI
->ImpCaptureStyle
= LambdaScopeInfo::ImpCap_LambdaByval
;
1070 else if (Intro
.Default
== LCD_ByRef
)
1071 LSI
->ImpCaptureStyle
= LambdaScopeInfo::ImpCap_LambdaByref
;
1072 LSI
->CaptureDefaultLoc
= Intro
.DefaultLoc
;
1073 LSI
->IntroducerRange
= Intro
.Range
;
1074 LSI
->AfterParameterList
= false;
1076 assert(LSI
->NumExplicitTemplateParams
== 0);
1078 // Determine if we're within a context where we know that the lambda will
1079 // be dependent, because there are template parameters in scope.
1080 CXXRecordDecl::LambdaDependencyKind LambdaDependencyKind
=
1081 CXXRecordDecl::LDK_Unknown
;
1082 if (CurScope
->getTemplateParamParent() != nullptr) {
1083 LambdaDependencyKind
= CXXRecordDecl::LDK_AlwaysDependent
;
1084 } else if (Scope
*P
= CurScope
->getParent()) {
1085 // Given a lambda defined inside a requires expression,
1088 // S(auto var) requires requires { [&] -> decltype(var) { }; }
1092 // The parameter var is not injected into the function Decl at the point of
1093 // parsing lambda. In such scenarios, perceiving it as dependent could
1094 // result in the constraint being evaluated, which matches what GCC does.
1095 while (P
->getEntity() && P
->getEntity()->isRequiresExprBody())
1097 if (P
->isFunctionDeclarationScope() &&
1098 llvm::any_of(P
->decls(), [](Decl
*D
) {
1099 return isa
<ParmVarDecl
>(D
) &&
1100 cast
<ParmVarDecl
>(D
)->getType()->isTemplateTypeParmType();
1102 LambdaDependencyKind
= CXXRecordDecl::LDK_AlwaysDependent
;
1105 CXXRecordDecl
*Class
= createLambdaClosureType(
1106 Intro
.Range
, /*Info=*/nullptr, LambdaDependencyKind
, Intro
.Default
);
1107 LSI
->Lambda
= Class
;
1109 CXXMethodDecl
*Method
= CreateLambdaCallOperator(Intro
.Range
, Class
);
1110 LSI
->CallOperator
= Method
;
1111 // Temporarily set the lexical declaration context to the current
1112 // context, so that the Scope stack matches the lexical nesting.
1113 Method
->setLexicalDeclContext(CurContext
);
1115 PushDeclContext(CurScope
, Method
);
1117 bool ContainsUnexpandedParameterPack
= false;
1119 // Distinct capture names, for diagnostics.
1120 llvm::DenseMap
<IdentifierInfo
*, ValueDecl
*> CaptureNames
;
1122 // Handle explicit captures.
1123 SourceLocation PrevCaptureLoc
=
1124 Intro
.Default
== LCD_None
? Intro
.Range
.getBegin() : Intro
.DefaultLoc
;
1125 for (auto C
= Intro
.Captures
.begin(), E
= Intro
.Captures
.end(); C
!= E
;
1126 PrevCaptureLoc
= C
->Loc
, ++C
) {
1127 if (C
->Kind
== LCK_This
|| C
->Kind
== LCK_StarThis
) {
1128 if (C
->Kind
== LCK_StarThis
)
1129 Diag(C
->Loc
, !getLangOpts().CPlusPlus17
1130 ? diag::ext_star_this_lambda_capture_cxx17
1131 : diag::warn_cxx14_compat_star_this_lambda_capture
);
1133 // C++11 [expr.prim.lambda]p8:
1134 // An identifier or this shall not appear more than once in a
1136 if (LSI
->isCXXThisCaptured()) {
1137 Diag(C
->Loc
, diag::err_capture_more_than_once
)
1138 << "'this'" << SourceRange(LSI
->getCXXThisCapture().getLocation())
1139 << FixItHint::CreateRemoval(
1140 SourceRange(getLocForEndOfToken(PrevCaptureLoc
), C
->Loc
));
1144 // C++20 [expr.prim.lambda]p8:
1145 // If a lambda-capture includes a capture-default that is =,
1146 // each simple-capture of that lambda-capture shall be of the form
1147 // "&identifier", "this", or "* this". [ Note: The form [&,this] is
1148 // redundant but accepted for compatibility with ISO C++14. --end note ]
1149 if (Intro
.Default
== LCD_ByCopy
&& C
->Kind
!= LCK_StarThis
)
1150 Diag(C
->Loc
, !getLangOpts().CPlusPlus20
1151 ? diag::ext_equals_this_lambda_capture_cxx20
1152 : diag::warn_cxx17_compat_equals_this_lambda_capture
);
1154 // C++11 [expr.prim.lambda]p12:
1155 // If this is captured by a local lambda expression, its nearest
1156 // enclosing function shall be a non-static member function.
1157 QualType ThisCaptureType
= getCurrentThisType();
1158 if (ThisCaptureType
.isNull()) {
1159 Diag(C
->Loc
, diag::err_this_capture
) << true;
1163 CheckCXXThisCapture(C
->Loc
, /*Explicit=*/true, /*BuildAndDiagnose*/ true,
1164 /*FunctionScopeIndexToStopAtPtr*/ nullptr,
1165 C
->Kind
== LCK_StarThis
);
1166 if (!LSI
->Captures
.empty())
1167 LSI
->ExplicitCaptureRanges
[LSI
->Captures
.size() - 1] = C
->ExplicitRange
;
1171 assert(C
->Id
&& "missing identifier for capture");
1173 if (C
->Init
.isInvalid())
1176 ValueDecl
*Var
= nullptr;
1177 if (C
->Init
.isUsable()) {
1178 Diag(C
->Loc
, getLangOpts().CPlusPlus14
1179 ? diag::warn_cxx11_compat_init_capture
1180 : diag::ext_init_capture
);
1182 // If the initializer expression is usable, but the InitCaptureType
1183 // is not, then an error has occurred - so ignore the capture for now.
1184 // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
1185 // FIXME: we should create the init capture variable and mark it invalid
1187 if (C
->InitCaptureType
.get().isNull())
1190 if (C
->Init
.get()->containsUnexpandedParameterPack() &&
1191 !C
->InitCaptureType
.get()->getAs
<PackExpansionType
>())
1192 DiagnoseUnexpandedParameterPack(C
->Init
.get(), UPPC_Initializer
);
1195 switch (C
->InitKind
) {
1196 case LambdaCaptureInitKind::NoInit
:
1197 llvm_unreachable("not an init-capture?");
1198 case LambdaCaptureInitKind::CopyInit
:
1199 InitStyle
= VarDecl::CInit
;
1201 case LambdaCaptureInitKind::DirectInit
:
1202 InitStyle
= VarDecl::CallInit
;
1204 case LambdaCaptureInitKind::ListInit
:
1205 InitStyle
= VarDecl::ListInit
;
1208 Var
= createLambdaInitCaptureVarDecl(C
->Loc
, C
->InitCaptureType
.get(),
1209 C
->EllipsisLoc
, C
->Id
, InitStyle
,
1210 C
->Init
.get(), Method
);
1211 assert(Var
&& "createLambdaInitCaptureVarDecl returned a null VarDecl?");
1212 if (auto *V
= dyn_cast
<VarDecl
>(Var
))
1213 CheckShadow(CurrentScope
, V
);
1214 PushOnScopeChains(Var
, CurrentScope
, false);
1216 assert(C
->InitKind
== LambdaCaptureInitKind::NoInit
&&
1217 "init capture has valid but null init?");
1219 // C++11 [expr.prim.lambda]p8:
1220 // If a lambda-capture includes a capture-default that is &, the
1221 // identifiers in the lambda-capture shall not be preceded by &.
1222 // If a lambda-capture includes a capture-default that is =, [...]
1223 // each identifier it contains shall be preceded by &.
1224 if (C
->Kind
== LCK_ByRef
&& Intro
.Default
== LCD_ByRef
) {
1225 Diag(C
->Loc
, diag::err_reference_capture_with_reference_default
)
1226 << FixItHint::CreateRemoval(
1227 SourceRange(getLocForEndOfToken(PrevCaptureLoc
), C
->Loc
));
1229 } else if (C
->Kind
== LCK_ByCopy
&& Intro
.Default
== LCD_ByCopy
) {
1230 Diag(C
->Loc
, diag::err_copy_capture_with_copy_default
)
1231 << FixItHint::CreateRemoval(
1232 SourceRange(getLocForEndOfToken(PrevCaptureLoc
), C
->Loc
));
1236 // C++11 [expr.prim.lambda]p10:
1237 // The identifiers in a capture-list are looked up using the usual
1238 // rules for unqualified name lookup (3.4.1)
1239 DeclarationNameInfo
Name(C
->Id
, C
->Loc
);
1240 LookupResult
R(*this, Name
, LookupOrdinaryName
);
1241 LookupName(R
, CurScope
);
1242 if (R
.isAmbiguous())
1245 // FIXME: Disable corrections that would add qualification?
1246 CXXScopeSpec ScopeSpec
;
1247 DeclFilterCCC
<VarDecl
> Validator
{};
1248 if (DiagnoseEmptyLookup(CurScope
, ScopeSpec
, R
, Validator
))
1252 if (auto *BD
= R
.getAsSingle
<BindingDecl
>())
1254 else if (R
.getAsSingle
<FieldDecl
>()) {
1255 Diag(C
->Loc
, diag::err_capture_class_member_does_not_name_variable
)
1259 Var
= R
.getAsSingle
<VarDecl
>();
1260 if (Var
&& DiagnoseUseOfDecl(Var
, C
->Loc
))
1264 // C++11 [expr.prim.lambda]p10:
1265 // [...] each such lookup shall find a variable with automatic storage
1266 // duration declared in the reaching scope of the local lambda expression.
1267 // Note that the 'reaching scope' check happens in tryCaptureVariable().
1269 Diag(C
->Loc
, diag::err_capture_does_not_name_variable
) << C
->Id
;
1273 // C++11 [expr.prim.lambda]p8:
1274 // An identifier or this shall not appear more than once in a
1276 if (auto [It
, Inserted
] = CaptureNames
.insert(std::pair
{C
->Id
, Var
});
1278 if (C
->InitKind
== LambdaCaptureInitKind::NoInit
&&
1279 !Var
->isInitCapture()) {
1280 Diag(C
->Loc
, diag::err_capture_more_than_once
)
1281 << C
->Id
<< It
->second
->getBeginLoc()
1282 << FixItHint::CreateRemoval(
1283 SourceRange(getLocForEndOfToken(PrevCaptureLoc
), C
->Loc
));
1284 Var
->setInvalidDecl();
1285 } else if (Var
&& Var
->isPlaceholderVar(getLangOpts())) {
1286 DiagPlaceholderVariableDefinition(C
->Loc
);
1288 // Previous capture captured something different (one or both was
1289 // an init-capture): no fixit.
1290 Diag(C
->Loc
, diag::err_capture_more_than_once
) << C
->Id
;
1295 // Ignore invalid decls; they'll just confuse the code later.
1296 if (Var
->isInvalidDecl())
1299 VarDecl
*Underlying
= Var
->getPotentiallyDecomposedVarDecl();
1301 if (!Underlying
->hasLocalStorage()) {
1302 Diag(C
->Loc
, diag::err_capture_non_automatic_variable
) << C
->Id
;
1303 Diag(Var
->getLocation(), diag::note_previous_decl
) << C
->Id
;
1307 // C++11 [expr.prim.lambda]p23:
1308 // A capture followed by an ellipsis is a pack expansion (14.5.3).
1309 SourceLocation EllipsisLoc
;
1310 if (C
->EllipsisLoc
.isValid()) {
1311 if (Var
->isParameterPack()) {
1312 EllipsisLoc
= C
->EllipsisLoc
;
1314 Diag(C
->EllipsisLoc
, diag::err_pack_expansion_without_parameter_packs
)
1315 << (C
->Init
.isUsable() ? C
->Init
.get()->getSourceRange()
1316 : SourceRange(C
->Loc
));
1318 // Just ignore the ellipsis.
1320 } else if (Var
->isParameterPack()) {
1321 ContainsUnexpandedParameterPack
= true;
1324 if (C
->Init
.isUsable()) {
1325 addInitCapture(LSI
, cast
<VarDecl
>(Var
), C
->Kind
== LCK_ByRef
);
1327 TryCaptureKind Kind
= C
->Kind
== LCK_ByRef
? TryCapture_ExplicitByRef
1328 : TryCapture_ExplicitByVal
;
1329 tryCaptureVariable(Var
, C
->Loc
, Kind
, EllipsisLoc
);
1331 if (!LSI
->Captures
.empty())
1332 LSI
->ExplicitCaptureRanges
[LSI
->Captures
.size() - 1] = C
->ExplicitRange
;
1334 finishLambdaExplicitCaptures(LSI
);
1335 LSI
->ContainsUnexpandedParameterPack
|= ContainsUnexpandedParameterPack
;
1339 void Sema::ActOnLambdaClosureQualifiers(LambdaIntroducer
&Intro
,
1340 SourceLocation MutableLoc
) {
1342 LambdaScopeInfo
*LSI
= getCurrentLambdaScopeUnsafe(*this);
1343 LSI
->Mutable
= MutableLoc
.isValid();
1344 ContextRAII
Context(*this, LSI
->CallOperator
, /*NewThisContext*/ false);
1346 // C++11 [expr.prim.lambda]p9:
1347 // A lambda-expression whose smallest enclosing scope is a block scope is a
1348 // local lambda expression; any other lambda expression shall not have a
1349 // capture-default or simple-capture in its lambda-introducer.
1351 // For simple-captures, this is covered by the check below that any named
1352 // entity is a variable that can be captured.
1354 // For DR1632, we also allow a capture-default in any context where we can
1355 // odr-use 'this' (in particular, in a default initializer for a non-static
1357 if (Intro
.Default
!= LCD_None
&&
1358 !LSI
->Lambda
->getParent()->isFunctionOrMethod() &&
1359 (getCurrentThisType().isNull() ||
1360 CheckCXXThisCapture(SourceLocation(), /*Explicit=*/true,
1361 /*BuildAndDiagnose=*/false)))
1362 Diag(Intro
.DefaultLoc
, diag::err_capture_default_non_local
);
1365 void Sema::ActOnLambdaClosureParameters(
1366 Scope
*LambdaScope
, MutableArrayRef
<DeclaratorChunk::ParamInfo
> Params
) {
1367 LambdaScopeInfo
*LSI
= getCurrentLambdaScopeUnsafe(*this);
1368 PushDeclContext(LambdaScope
, LSI
->CallOperator
);
1370 for (const DeclaratorChunk::ParamInfo
&P
: Params
) {
1371 auto *Param
= cast
<ParmVarDecl
>(P
.Param
);
1372 Param
->setOwningFunction(LSI
->CallOperator
);
1373 if (Param
->getIdentifier())
1374 PushOnScopeChains(Param
, LambdaScope
, false);
1377 // After the parameter list, we may parse a noexcept/requires/trailing return
1378 // type which need to know whether the call operator constiture a dependent
1379 // context, so we need to setup the FunctionTemplateDecl of generic lambdas
1381 TemplateParameterList
*TemplateParams
=
1382 getGenericLambdaTemplateParameterList(LSI
, *this);
1383 if (TemplateParams
) {
1384 AddTemplateParametersToLambdaCallOperator(LSI
->CallOperator
, LSI
->Lambda
,
1386 LSI
->Lambda
->setLambdaIsGeneric(true);
1387 LSI
->ContainsUnexpandedParameterPack
|=
1388 TemplateParams
->containsUnexpandedParameterPack();
1390 LSI
->AfterParameterList
= true;
1393 void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer
&Intro
,
1394 Declarator
&ParamInfo
,
1395 const DeclSpec
&DS
) {
1397 LambdaScopeInfo
*LSI
= getCurrentLambdaScopeUnsafe(*this);
1398 LSI
->CallOperator
->setConstexprKind(DS
.getConstexprSpecifier());
1400 SmallVector
<ParmVarDecl
*, 8> Params
;
1401 bool ExplicitResultType
;
1403 SourceLocation TypeLoc
, CallOperatorLoc
;
1404 if (ParamInfo
.getNumTypeObjects() == 0) {
1405 CallOperatorLoc
= TypeLoc
= Intro
.Range
.getEnd();
1408 ParamInfo
.isFunctionDeclarator(Index
);
1409 const auto &Object
= ParamInfo
.getTypeObject(Index
);
1411 Object
.Loc
.isValid() ? Object
.Loc
: ParamInfo
.getSourceRange().getEnd();
1412 CallOperatorLoc
= ParamInfo
.getSourceRange().getEnd();
1415 CXXRecordDecl
*Class
= LSI
->Lambda
;
1416 CXXMethodDecl
*Method
= LSI
->CallOperator
;
1418 TypeSourceInfo
*MethodTyInfo
= getLambdaType(
1419 *this, Intro
, ParamInfo
, getCurScope(), TypeLoc
, ExplicitResultType
);
1421 LSI
->ExplicitParams
= ParamInfo
.getNumTypeObjects() != 0;
1423 if (ParamInfo
.isFunctionDeclarator() != 0 &&
1424 !FTIHasSingleVoidParameter(ParamInfo
.getFunctionTypeInfo())) {
1425 const auto &FTI
= ParamInfo
.getFunctionTypeInfo();
1426 Params
.reserve(Params
.size());
1427 for (unsigned I
= 0; I
< FTI
.NumParams
; ++I
) {
1428 auto *Param
= cast
<ParmVarDecl
>(FTI
.Params
[I
].Param
);
1429 Param
->setScopeInfo(0, Params
.size());
1430 Params
.push_back(Param
);
1434 bool IsLambdaStatic
=
1435 ParamInfo
.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static
;
1437 CompleteLambdaCallOperator(
1438 Method
, Intro
.Range
.getBegin(), CallOperatorLoc
,
1439 ParamInfo
.getTrailingRequiresClause(), MethodTyInfo
,
1440 ParamInfo
.getDeclSpec().getConstexprSpecifier(),
1441 IsLambdaStatic
? SC_Static
: SC_None
, Params
, ExplicitResultType
);
1443 CheckCXXDefaultArguments(Method
);
1445 // This represents the function body for the lambda function, check if we
1446 // have to apply optnone due to a pragma.
1447 AddRangeBasedOptnone(Method
);
1449 // code_seg attribute on lambda apply to the method.
1450 if (Attr
*A
= getImplicitCodeSegOrSectionAttrForFunction(
1451 Method
, /*IsDefinition=*/true))
1454 // Attributes on the lambda apply to the method.
1455 ProcessDeclAttributes(CurScope
, Method
, ParamInfo
);
1457 // CUDA lambdas get implicit host and device attributes.
1458 if (getLangOpts().CUDA
)
1459 CUDA().SetLambdaAttrs(Method
);
1461 // OpenMP lambdas might get assumumption attributes.
1462 if (LangOpts
.OpenMP
)
1463 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Method
);
1465 handleLambdaNumbering(Class
, Method
);
1467 for (auto &&C
: LSI
->Captures
) {
1468 if (!C
.isVariableCapture())
1470 ValueDecl
*Var
= C
.getVariable();
1471 if (Var
&& Var
->isInitCapture()) {
1472 PushOnScopeChains(Var
, CurScope
, false);
1476 auto CheckRedefinition
= [&](ParmVarDecl
*Param
) {
1477 for (const auto &Capture
: Intro
.Captures
) {
1478 if (Capture
.Id
== Param
->getIdentifier()) {
1479 Diag(Param
->getLocation(), diag::err_parameter_shadow_capture
);
1480 Diag(Capture
.Loc
, diag::note_var_explicitly_captured_here
)
1481 << Capture
.Id
<< true;
1488 for (ParmVarDecl
*P
: Params
) {
1489 if (!P
->getIdentifier())
1491 if (CheckRedefinition(P
))
1492 CheckShadow(CurScope
, P
);
1493 PushOnScopeChains(P
, CurScope
);
1496 // C++23 [expr.prim.lambda.capture]p5:
1497 // If an identifier in a capture appears as the declarator-id of a parameter
1498 // of the lambda-declarator's parameter-declaration-clause or as the name of a
1499 // template parameter of the lambda-expression's template-parameter-list, the
1500 // program is ill-formed.
1501 TemplateParameterList
*TemplateParams
=
1502 getGenericLambdaTemplateParameterList(LSI
, *this);
1503 if (TemplateParams
) {
1504 for (const auto *TP
: TemplateParams
->asArray()) {
1505 if (!TP
->getIdentifier())
1507 for (const auto &Capture
: Intro
.Captures
) {
1508 if (Capture
.Id
== TP
->getIdentifier()) {
1509 Diag(Capture
.Loc
, diag::err_template_param_shadow
) << Capture
.Id
;
1510 NoteTemplateParameterLocation(*TP
);
1516 // C++20: dcl.decl.general p4:
1517 // The optional requires-clause ([temp.pre]) in an init-declarator or
1518 // member-declarator shall be present only if the declarator declares a
1519 // templated function ([dcl.fct]).
1520 if (Expr
*TRC
= Method
->getTrailingRequiresClause()) {
1522 // An entity is templated if it is
1524 // - an entity defined ([basic.def]) or created ([class.temporary]) in a
1525 // templated entity,
1526 // - a member of a templated entity,
1527 // - an enumerator for an enumeration that is a templated entity, or
1528 // - the closure type of a lambda-expression ([expr.prim.lambda.closure])
1529 // appearing in the declaration of a templated entity. [Note 6: A local
1530 // class, a local or block variable, or a friend function defined in a
1531 // templated entity is a templated entity. — end note]
1533 // A templated function is a function template or a function that is
1534 // templated. A templated class is a class template or a class that is
1535 // templated. A templated variable is a variable template or a variable
1536 // that is templated.
1538 // Note: we only have to check if this is defined in a template entity, OR
1539 // if we are a template, since the rest don't apply. The requires clause
1540 // applies to the call operator, which we already know is a member function,
1542 if (!Method
->getDescribedFunctionTemplate() && !Method
->isTemplated()) {
1543 Diag(TRC
->getBeginLoc(), diag::err_constrained_non_templated_function
);
1547 // Enter a new evaluation context to insulate the lambda from any
1548 // cleanups from the enclosing full-expression.
1549 PushExpressionEvaluationContext(
1550 LSI
->CallOperator
->isConsteval()
1551 ? ExpressionEvaluationContext::ImmediateFunctionContext
1552 : ExpressionEvaluationContext::PotentiallyEvaluated
);
1553 ExprEvalContexts
.back().InImmediateFunctionContext
=
1554 LSI
->CallOperator
->isConsteval();
1555 ExprEvalContexts
.back().InImmediateEscalatingFunctionContext
=
1556 getLangOpts().CPlusPlus20
&& LSI
->CallOperator
->isImmediateEscalating();
1559 void Sema::ActOnLambdaError(SourceLocation StartLoc
, Scope
*CurScope
,
1560 bool IsInstantiation
) {
1561 LambdaScopeInfo
*LSI
= cast
<LambdaScopeInfo
>(FunctionScopes
.back());
1563 // Leave the expression-evaluation context.
1564 DiscardCleanupsInEvaluationContext();
1565 PopExpressionEvaluationContext();
1567 // Leave the context of the lambda.
1568 if (!IsInstantiation
)
1571 // Finalize the lambda.
1572 CXXRecordDecl
*Class
= LSI
->Lambda
;
1573 Class
->setInvalidDecl();
1574 SmallVector
<Decl
*, 4> Fields(Class
->fields());
1575 ActOnFields(nullptr, Class
->getLocation(), Class
, Fields
, SourceLocation(),
1576 SourceLocation(), ParsedAttributesView());
1577 CheckCompletedCXXClass(nullptr, Class
);
1579 PopFunctionScopeInfo();
1582 template <typename Func
>
1583 static void repeatForLambdaConversionFunctionCallingConvs(
1584 Sema
&S
, const FunctionProtoType
&CallOpProto
, Func F
) {
1585 CallingConv DefaultFree
= S
.Context
.getDefaultCallingConvention(
1586 CallOpProto
.isVariadic(), /*IsCXXMethod=*/false);
1587 CallingConv DefaultMember
= S
.Context
.getDefaultCallingConvention(
1588 CallOpProto
.isVariadic(), /*IsCXXMethod=*/true);
1589 CallingConv CallOpCC
= CallOpProto
.getCallConv();
1591 /// Implement emitting a version of the operator for many of the calling
1592 /// conventions for MSVC, as described here:
1593 /// https://devblogs.microsoft.com/oldnewthing/20150220-00/?p=44623.
1594 /// Experimentally, we determined that cdecl, stdcall, fastcall, and
1595 /// vectorcall are generated by MSVC when it is supported by the target.
1596 /// Additionally, we are ensuring that the default-free/default-member and
1597 /// call-operator calling convention are generated as well.
1598 /// NOTE: We intentionally generate a 'thiscall' on Win32 implicitly from the
1599 /// 'member default', despite MSVC not doing so. We do this in order to ensure
1600 /// that someone who intentionally places 'thiscall' on the lambda call
1601 /// operator will still get that overload, since we don't have the a way of
1602 /// detecting the attribute by the time we get here.
1603 if (S
.getLangOpts().MSVCCompat
) {
1604 CallingConv Convs
[] = {
1605 CC_C
, CC_X86StdCall
, CC_X86FastCall
, CC_X86VectorCall
,
1606 DefaultFree
, DefaultMember
, CallOpCC
};
1608 llvm::iterator_range
<CallingConv
*> Range(
1609 std::begin(Convs
), std::unique(std::begin(Convs
), std::end(Convs
)));
1610 const TargetInfo
&TI
= S
.getASTContext().getTargetInfo();
1612 for (CallingConv C
: Range
) {
1613 if (TI
.checkCallingConvention(C
) == TargetInfo::CCCR_OK
)
1619 if (CallOpCC
== DefaultMember
&& DefaultMember
!= DefaultFree
) {
1627 // Returns the 'standard' calling convention to be used for the lambda
1628 // conversion function, that is, the 'free' function calling convention unless
1629 // it is overridden by a non-default calling convention attribute.
1631 getLambdaConversionFunctionCallConv(Sema
&S
,
1632 const FunctionProtoType
*CallOpProto
) {
1633 CallingConv DefaultFree
= S
.Context
.getDefaultCallingConvention(
1634 CallOpProto
->isVariadic(), /*IsCXXMethod=*/false);
1635 CallingConv DefaultMember
= S
.Context
.getDefaultCallingConvention(
1636 CallOpProto
->isVariadic(), /*IsCXXMethod=*/true);
1637 CallingConv CallOpCC
= CallOpProto
->getCallConv();
1639 // If the call-operator hasn't been changed, return both the 'free' and
1640 // 'member' function calling convention.
1641 if (CallOpCC
== DefaultMember
&& DefaultMember
!= DefaultFree
)
1646 QualType
Sema::getLambdaConversionFunctionResultType(
1647 const FunctionProtoType
*CallOpProto
, CallingConv CC
) {
1648 const FunctionProtoType::ExtProtoInfo CallOpExtInfo
=
1649 CallOpProto
->getExtProtoInfo();
1650 FunctionProtoType::ExtProtoInfo InvokerExtInfo
= CallOpExtInfo
;
1651 InvokerExtInfo
.ExtInfo
= InvokerExtInfo
.ExtInfo
.withCallingConv(CC
);
1652 InvokerExtInfo
.TypeQuals
= Qualifiers();
1653 assert(InvokerExtInfo
.RefQualifier
== RQ_None
&&
1654 "Lambda's call operator should not have a reference qualifier");
1655 return Context
.getFunctionType(CallOpProto
->getReturnType(),
1656 CallOpProto
->getParamTypes(), InvokerExtInfo
);
1659 /// Add a lambda's conversion to function pointer, as described in
1660 /// C++11 [expr.prim.lambda]p6.
1661 static void addFunctionPointerConversion(Sema
&S
, SourceRange IntroducerRange
,
1662 CXXRecordDecl
*Class
,
1663 CXXMethodDecl
*CallOperator
,
1664 QualType InvokerFunctionTy
) {
1665 // This conversion is explicitly disabled if the lambda's function has
1666 // pass_object_size attributes on any of its parameters.
1667 auto HasPassObjectSizeAttr
= [](const ParmVarDecl
*P
) {
1668 return P
->hasAttr
<PassObjectSizeAttr
>();
1670 if (llvm::any_of(CallOperator
->parameters(), HasPassObjectSizeAttr
))
1673 // Add the conversion to function pointer.
1674 QualType PtrToFunctionTy
= S
.Context
.getPointerType(InvokerFunctionTy
);
1676 // Create the type of the conversion function.
1677 FunctionProtoType::ExtProtoInfo
ConvExtInfo(
1678 S
.Context
.getDefaultCallingConvention(
1679 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1680 // The conversion function is always const and noexcept.
1681 ConvExtInfo
.TypeQuals
= Qualifiers();
1682 ConvExtInfo
.TypeQuals
.addConst();
1683 ConvExtInfo
.ExceptionSpec
.Type
= EST_BasicNoexcept
;
1684 QualType ConvTy
= S
.Context
.getFunctionType(PtrToFunctionTy
, {}, ConvExtInfo
);
1686 SourceLocation Loc
= IntroducerRange
.getBegin();
1687 DeclarationName ConversionName
1688 = S
.Context
.DeclarationNames
.getCXXConversionFunctionName(
1689 S
.Context
.getCanonicalType(PtrToFunctionTy
));
1690 // Construct a TypeSourceInfo for the conversion function, and wire
1691 // all the parameters appropriately for the FunctionProtoTypeLoc
1692 // so that everything works during transformation/instantiation of
1694 // The main reason for wiring up the parameters of the conversion
1695 // function with that of the call operator is so that constructs
1696 // like the following work:
1697 // auto L = [](auto b) { <-- 1
1698 // return [](auto a) -> decltype(a) { <-- 2
1702 // int (*fp)(int) = L(5);
1703 // Because the trailing return type can contain DeclRefExprs that refer
1704 // to the original call operator's variables, we hijack the call
1705 // operators ParmVarDecls below.
1706 TypeSourceInfo
*ConvNamePtrToFunctionTSI
=
1707 S
.Context
.getTrivialTypeSourceInfo(PtrToFunctionTy
, Loc
);
1708 DeclarationNameLoc ConvNameLoc
=
1709 DeclarationNameLoc::makeNamedTypeLoc(ConvNamePtrToFunctionTSI
);
1711 // The conversion function is a conversion to a pointer-to-function.
1712 TypeSourceInfo
*ConvTSI
= S
.Context
.getTrivialTypeSourceInfo(ConvTy
, Loc
);
1713 FunctionProtoTypeLoc ConvTL
=
1714 ConvTSI
->getTypeLoc().getAs
<FunctionProtoTypeLoc
>();
1715 // Get the result of the conversion function which is a pointer-to-function.
1716 PointerTypeLoc PtrToFunctionTL
=
1717 ConvTL
.getReturnLoc().getAs
<PointerTypeLoc
>();
1718 // Do the same for the TypeSourceInfo that is used to name the conversion
1720 PointerTypeLoc ConvNamePtrToFunctionTL
=
1721 ConvNamePtrToFunctionTSI
->getTypeLoc().getAs
<PointerTypeLoc
>();
1723 // Get the underlying function types that the conversion function will
1724 // be converting to (should match the type of the call operator).
1725 FunctionProtoTypeLoc CallOpConvTL
=
1726 PtrToFunctionTL
.getPointeeLoc().getAs
<FunctionProtoTypeLoc
>();
1727 FunctionProtoTypeLoc CallOpConvNameTL
=
1728 ConvNamePtrToFunctionTL
.getPointeeLoc().getAs
<FunctionProtoTypeLoc
>();
1730 // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
1731 // These parameter's are essentially used to transform the name and
1732 // the type of the conversion operator. By using the same parameters
1733 // as the call operator's we don't have to fix any back references that
1734 // the trailing return type of the call operator's uses (such as
1735 // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
1736 // - we can simply use the return type of the call operator, and
1737 // everything should work.
1738 SmallVector
<ParmVarDecl
*, 4> InvokerParams
;
1739 for (unsigned I
= 0, N
= CallOperator
->getNumParams(); I
!= N
; ++I
) {
1740 ParmVarDecl
*From
= CallOperator
->getParamDecl(I
);
1742 InvokerParams
.push_back(ParmVarDecl::Create(
1744 // Temporarily add to the TU. This is set to the invoker below.
1745 S
.Context
.getTranslationUnitDecl(), From
->getBeginLoc(),
1746 From
->getLocation(), From
->getIdentifier(), From
->getType(),
1747 From
->getTypeSourceInfo(), From
->getStorageClass(),
1748 /*DefArg=*/nullptr));
1749 CallOpConvTL
.setParam(I
, From
);
1750 CallOpConvNameTL
.setParam(I
, From
);
1753 CXXConversionDecl
*Conversion
= CXXConversionDecl::Create(
1754 S
.Context
, Class
, Loc
,
1755 DeclarationNameInfo(ConversionName
, Loc
, ConvNameLoc
), ConvTy
, ConvTSI
,
1756 S
.getCurFPFeatures().isFPConstrained(),
1757 /*isInline=*/true, ExplicitSpecifier(),
1758 S
.getLangOpts().CPlusPlus17
? ConstexprSpecKind::Constexpr
1759 : ConstexprSpecKind::Unspecified
,
1760 CallOperator
->getBody()->getEndLoc());
1761 Conversion
->setAccess(AS_public
);
1762 Conversion
->setImplicit(true);
1764 // A non-generic lambda may still be a templated entity. We need to preserve
1765 // constraints when converting the lambda to a function pointer. See GH63181.
1766 if (Expr
*Requires
= CallOperator
->getTrailingRequiresClause())
1767 Conversion
->setTrailingRequiresClause(Requires
);
1769 if (Class
->isGenericLambda()) {
1770 // Create a template version of the conversion operator, using the template
1771 // parameter list of the function call operator.
1772 FunctionTemplateDecl
*TemplateCallOperator
=
1773 CallOperator
->getDescribedFunctionTemplate();
1774 FunctionTemplateDecl
*ConversionTemplate
=
1775 FunctionTemplateDecl::Create(S
.Context
, Class
,
1776 Loc
, ConversionName
,
1777 TemplateCallOperator
->getTemplateParameters(),
1779 ConversionTemplate
->setAccess(AS_public
);
1780 ConversionTemplate
->setImplicit(true);
1781 Conversion
->setDescribedFunctionTemplate(ConversionTemplate
);
1782 Class
->addDecl(ConversionTemplate
);
1784 Class
->addDecl(Conversion
);
1786 // If the lambda is not static, we need to add a static member
1787 // function that will be the result of the conversion with a
1788 // certain unique ID.
1789 // When it is static we just return the static call operator instead.
1790 if (CallOperator
->isImplicitObjectMemberFunction()) {
1791 DeclarationName InvokerName
=
1792 &S
.Context
.Idents
.get(getLambdaStaticInvokerName());
1793 // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
1794 // we should get a prebuilt TrivialTypeSourceInfo from Context
1795 // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
1796 // then rewire the parameters accordingly, by hoisting up the InvokeParams
1797 // loop below and then use its Params to set Invoke->setParams(...) below.
1798 // This would avoid the 'const' qualifier of the calloperator from
1799 // contaminating the type of the invoker, which is currently adjusted
1800 // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the
1801 // trailing return type of the invoker would require a visitor to rebuild
1802 // the trailing return type and adjusting all back DeclRefExpr's to refer
1803 // to the new static invoker parameters - not the call operator's.
1804 CXXMethodDecl
*Invoke
= CXXMethodDecl::Create(
1805 S
.Context
, Class
, Loc
, DeclarationNameInfo(InvokerName
, Loc
),
1806 InvokerFunctionTy
, CallOperator
->getTypeSourceInfo(), SC_Static
,
1807 S
.getCurFPFeatures().isFPConstrained(),
1808 /*isInline=*/true, CallOperator
->getConstexprKind(),
1809 CallOperator
->getBody()->getEndLoc());
1810 for (unsigned I
= 0, N
= CallOperator
->getNumParams(); I
!= N
; ++I
)
1811 InvokerParams
[I
]->setOwningFunction(Invoke
);
1812 Invoke
->setParams(InvokerParams
);
1813 Invoke
->setAccess(AS_private
);
1814 Invoke
->setImplicit(true);
1815 if (Class
->isGenericLambda()) {
1816 FunctionTemplateDecl
*TemplateCallOperator
=
1817 CallOperator
->getDescribedFunctionTemplate();
1818 FunctionTemplateDecl
*StaticInvokerTemplate
=
1819 FunctionTemplateDecl::Create(
1820 S
.Context
, Class
, Loc
, InvokerName
,
1821 TemplateCallOperator
->getTemplateParameters(), Invoke
);
1822 StaticInvokerTemplate
->setAccess(AS_private
);
1823 StaticInvokerTemplate
->setImplicit(true);
1824 Invoke
->setDescribedFunctionTemplate(StaticInvokerTemplate
);
1825 Class
->addDecl(StaticInvokerTemplate
);
1827 Class
->addDecl(Invoke
);
1831 /// Add a lambda's conversion to function pointers, as described in
1832 /// C++11 [expr.prim.lambda]p6. Note that in most cases, this should emit only a
1833 /// single pointer conversion. In the event that the default calling convention
1834 /// for free and member functions is different, it will emit both conventions.
1835 static void addFunctionPointerConversions(Sema
&S
, SourceRange IntroducerRange
,
1836 CXXRecordDecl
*Class
,
1837 CXXMethodDecl
*CallOperator
) {
1838 const FunctionProtoType
*CallOpProto
=
1839 CallOperator
->getType()->castAs
<FunctionProtoType
>();
1841 repeatForLambdaConversionFunctionCallingConvs(
1842 S
, *CallOpProto
, [&](CallingConv CC
) {
1843 QualType InvokerFunctionTy
=
1844 S
.getLambdaConversionFunctionResultType(CallOpProto
, CC
);
1845 addFunctionPointerConversion(S
, IntroducerRange
, Class
, CallOperator
,
1850 /// Add a lambda's conversion to block pointer.
1851 static void addBlockPointerConversion(Sema
&S
,
1852 SourceRange IntroducerRange
,
1853 CXXRecordDecl
*Class
,
1854 CXXMethodDecl
*CallOperator
) {
1855 const FunctionProtoType
*CallOpProto
=
1856 CallOperator
->getType()->castAs
<FunctionProtoType
>();
1857 QualType FunctionTy
= S
.getLambdaConversionFunctionResultType(
1858 CallOpProto
, getLambdaConversionFunctionCallConv(S
, CallOpProto
));
1859 QualType BlockPtrTy
= S
.Context
.getBlockPointerType(FunctionTy
);
1861 FunctionProtoType::ExtProtoInfo
ConversionEPI(
1862 S
.Context
.getDefaultCallingConvention(
1863 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1864 ConversionEPI
.TypeQuals
= Qualifiers();
1865 ConversionEPI
.TypeQuals
.addConst();
1866 QualType ConvTy
= S
.Context
.getFunctionType(BlockPtrTy
, {}, ConversionEPI
);
1868 SourceLocation Loc
= IntroducerRange
.getBegin();
1869 DeclarationName Name
1870 = S
.Context
.DeclarationNames
.getCXXConversionFunctionName(
1871 S
.Context
.getCanonicalType(BlockPtrTy
));
1872 DeclarationNameLoc NameLoc
= DeclarationNameLoc::makeNamedTypeLoc(
1873 S
.Context
.getTrivialTypeSourceInfo(BlockPtrTy
, Loc
));
1874 CXXConversionDecl
*Conversion
= CXXConversionDecl::Create(
1875 S
.Context
, Class
, Loc
, DeclarationNameInfo(Name
, Loc
, NameLoc
), ConvTy
,
1876 S
.Context
.getTrivialTypeSourceInfo(ConvTy
, Loc
),
1877 S
.getCurFPFeatures().isFPConstrained(),
1878 /*isInline=*/true, ExplicitSpecifier(), ConstexprSpecKind::Unspecified
,
1879 CallOperator
->getBody()->getEndLoc());
1880 Conversion
->setAccess(AS_public
);
1881 Conversion
->setImplicit(true);
1882 Class
->addDecl(Conversion
);
1885 ExprResult
Sema::BuildCaptureInit(const Capture
&Cap
,
1886 SourceLocation ImplicitCaptureLoc
,
1887 bool IsOpenMPMapping
) {
1888 // VLA captures don't have a stored initialization expression.
1889 if (Cap
.isVLATypeCapture())
1890 return ExprResult();
1892 // An init-capture is initialized directly from its stored initializer.
1893 if (Cap
.isInitCapture())
1894 return cast
<VarDecl
>(Cap
.getVariable())->getInit();
1896 // For anything else, build an initialization expression. For an implicit
1897 // capture, the capture notionally happens at the capture-default, so use
1898 // that location here.
1899 SourceLocation Loc
=
1900 ImplicitCaptureLoc
.isValid() ? ImplicitCaptureLoc
: Cap
.getLocation();
1902 // C++11 [expr.prim.lambda]p21:
1903 // When the lambda-expression is evaluated, the entities that
1904 // are captured by copy are used to direct-initialize each
1905 // corresponding non-static data member of the resulting closure
1906 // object. (For array members, the array elements are
1907 // direct-initialized in increasing subscript order.) These
1908 // initializations are performed in the (unspecified) order in
1909 // which the non-static data members are declared.
1911 // C++ [expr.prim.lambda]p12:
1912 // An entity captured by a lambda-expression is odr-used (3.2) in
1913 // the scope containing the lambda-expression.
1915 IdentifierInfo
*Name
= nullptr;
1916 if (Cap
.isThisCapture()) {
1917 QualType ThisTy
= getCurrentThisType();
1918 Expr
*This
= BuildCXXThisExpr(Loc
, ThisTy
, ImplicitCaptureLoc
.isValid());
1919 if (Cap
.isCopyCapture())
1920 Init
= CreateBuiltinUnaryOp(Loc
, UO_Deref
, This
);
1924 assert(Cap
.isVariableCapture() && "unknown kind of capture");
1925 ValueDecl
*Var
= Cap
.getVariable();
1926 Name
= Var
->getIdentifier();
1927 Init
= BuildDeclarationNameExpr(
1928 CXXScopeSpec(), DeclarationNameInfo(Var
->getDeclName(), Loc
), Var
);
1931 // In OpenMP, the capture kind doesn't actually describe how to capture:
1932 // variables are "mapped" onto the device in a process that does not formally
1933 // make a copy, even for a "copy capture".
1934 if (IsOpenMPMapping
)
1937 if (Init
.isInvalid())
1940 Expr
*InitExpr
= Init
.get();
1941 InitializedEntity Entity
= InitializedEntity::InitializeLambdaCapture(
1942 Name
, Cap
.getCaptureType(), Loc
);
1943 InitializationKind InitKind
=
1944 InitializationKind::CreateDirect(Loc
, Loc
, Loc
);
1945 InitializationSequence
InitSeq(*this, Entity
, InitKind
, InitExpr
);
1946 return InitSeq
.Perform(*this, Entity
, InitKind
, InitExpr
);
1949 ExprResult
Sema::ActOnLambdaExpr(SourceLocation StartLoc
, Stmt
*Body
) {
1950 LambdaScopeInfo LSI
= *cast
<LambdaScopeInfo
>(FunctionScopes
.back());
1951 ActOnFinishFunctionBody(LSI
.CallOperator
, Body
);
1953 return BuildLambdaExpr(StartLoc
, Body
->getEndLoc(), &LSI
);
1956 static LambdaCaptureDefault
1957 mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS
) {
1959 case CapturingScopeInfo::ImpCap_None
:
1961 case CapturingScopeInfo::ImpCap_LambdaByval
:
1963 case CapturingScopeInfo::ImpCap_CapturedRegion
:
1964 case CapturingScopeInfo::ImpCap_LambdaByref
:
1966 case CapturingScopeInfo::ImpCap_Block
:
1967 llvm_unreachable("block capture in lambda");
1969 llvm_unreachable("Unknown implicit capture style");
1972 bool Sema::CaptureHasSideEffects(const Capture
&From
) {
1973 if (From
.isInitCapture()) {
1974 Expr
*Init
= cast
<VarDecl
>(From
.getVariable())->getInit();
1975 if (Init
&& Init
->HasSideEffects(Context
))
1979 if (!From
.isCopyCapture())
1982 const QualType T
= From
.isThisCapture()
1983 ? getCurrentThisType()->getPointeeType()
1984 : From
.getCaptureType();
1986 if (T
.isVolatileQualified())
1989 const Type
*BaseT
= T
->getBaseElementTypeUnsafe();
1990 if (const CXXRecordDecl
*RD
= BaseT
->getAsCXXRecordDecl())
1991 return !RD
->isCompleteDefinition() || !RD
->hasTrivialCopyConstructor() ||
1992 !RD
->hasTrivialDestructor();
1997 bool Sema::DiagnoseUnusedLambdaCapture(SourceRange CaptureRange
,
1998 const Capture
&From
) {
1999 if (CaptureHasSideEffects(From
))
2002 if (From
.isVLATypeCapture())
2005 // FIXME: maybe we should warn on these if we can find a sensible diagnostic
2007 if (From
.isInitCapture() &&
2008 From
.getVariable()->isPlaceholderVar(getLangOpts()))
2011 auto diag
= Diag(From
.getLocation(), diag::warn_unused_lambda_capture
);
2012 if (From
.isThisCapture())
2015 diag
<< From
.getVariable();
2016 diag
<< From
.isNonODRUsed();
2017 diag
<< FixItHint::CreateRemoval(CaptureRange
);
2021 /// Create a field within the lambda class or captured statement record for the
2023 FieldDecl
*Sema::BuildCaptureField(RecordDecl
*RD
,
2024 const sema::Capture
&Capture
) {
2025 SourceLocation Loc
= Capture
.getLocation();
2026 QualType FieldType
= Capture
.getCaptureType();
2028 TypeSourceInfo
*TSI
= nullptr;
2029 if (Capture
.isVariableCapture()) {
2030 const auto *Var
= dyn_cast_or_null
<VarDecl
>(Capture
.getVariable());
2031 if (Var
&& Var
->isInitCapture())
2032 TSI
= Var
->getTypeSourceInfo();
2035 // FIXME: Should we really be doing this? A null TypeSourceInfo seems more
2036 // appropriate, at least for an implicit capture.
2038 TSI
= Context
.getTrivialTypeSourceInfo(FieldType
, Loc
);
2040 // Build the non-static data member.
2042 FieldDecl::Create(Context
, RD
, /*StartLoc=*/Loc
, /*IdLoc=*/Loc
,
2043 /*Id=*/nullptr, FieldType
, TSI
, /*BW=*/nullptr,
2044 /*Mutable=*/false, ICIS_NoInit
);
2045 // If the variable being captured has an invalid type, mark the class as
2047 if (!FieldType
->isDependentType()) {
2048 if (RequireCompleteSizedType(Loc
, FieldType
,
2049 diag::err_field_incomplete_or_sizeless
)) {
2050 RD
->setInvalidDecl();
2051 Field
->setInvalidDecl();
2054 FieldType
->isIncompleteType(&Def
);
2055 if (Def
&& Def
->isInvalidDecl()) {
2056 RD
->setInvalidDecl();
2057 Field
->setInvalidDecl();
2061 Field
->setImplicit(true);
2062 Field
->setAccess(AS_private
);
2065 if (Capture
.isVLATypeCapture())
2066 Field
->setCapturedVLAType(Capture
.getCapturedVLAType());
2071 ExprResult
Sema::BuildLambdaExpr(SourceLocation StartLoc
, SourceLocation EndLoc
,
2072 LambdaScopeInfo
*LSI
) {
2073 // Collect information from the lambda scope.
2074 SmallVector
<LambdaCapture
, 4> Captures
;
2075 SmallVector
<Expr
*, 4> CaptureInits
;
2076 SourceLocation CaptureDefaultLoc
= LSI
->CaptureDefaultLoc
;
2077 LambdaCaptureDefault CaptureDefault
=
2078 mapImplicitCaptureStyle(LSI
->ImpCaptureStyle
);
2079 CXXRecordDecl
*Class
;
2080 CXXMethodDecl
*CallOperator
;
2081 SourceRange IntroducerRange
;
2082 bool ExplicitParams
;
2083 bool ExplicitResultType
;
2084 CleanupInfo LambdaCleanup
;
2085 bool ContainsUnexpandedParameterPack
;
2086 bool IsGenericLambda
;
2088 CallOperator
= LSI
->CallOperator
;
2089 Class
= LSI
->Lambda
;
2090 IntroducerRange
= LSI
->IntroducerRange
;
2091 ExplicitParams
= LSI
->ExplicitParams
;
2092 ExplicitResultType
= !LSI
->HasImplicitReturnType
;
2093 LambdaCleanup
= LSI
->Cleanup
;
2094 ContainsUnexpandedParameterPack
= LSI
->ContainsUnexpandedParameterPack
;
2095 IsGenericLambda
= Class
->isGenericLambda();
2097 CallOperator
->setLexicalDeclContext(Class
);
2098 Decl
*TemplateOrNonTemplateCallOperatorDecl
=
2099 CallOperator
->getDescribedFunctionTemplate()
2100 ? CallOperator
->getDescribedFunctionTemplate()
2101 : cast
<Decl
>(CallOperator
);
2103 // FIXME: Is this really the best choice? Keeping the lexical decl context
2104 // set as CurContext seems more faithful to the source.
2105 TemplateOrNonTemplateCallOperatorDecl
->setLexicalDeclContext(Class
);
2107 PopExpressionEvaluationContext();
2109 // True if the current capture has a used capture or default before it.
2110 bool CurHasPreviousCapture
= CaptureDefault
!= LCD_None
;
2111 SourceLocation PrevCaptureLoc
= CurHasPreviousCapture
?
2112 CaptureDefaultLoc
: IntroducerRange
.getBegin();
2114 for (unsigned I
= 0, N
= LSI
->Captures
.size(); I
!= N
; ++I
) {
2115 const Capture
&From
= LSI
->Captures
[I
];
2117 if (From
.isInvalid())
2120 assert(!From
.isBlockCapture() && "Cannot capture __block variables");
2121 bool IsImplicit
= I
>= LSI
->NumExplicitCaptures
;
2122 SourceLocation ImplicitCaptureLoc
=
2123 IsImplicit
? CaptureDefaultLoc
: SourceLocation();
2125 // Use source ranges of explicit captures for fixits where available.
2126 SourceRange CaptureRange
= LSI
->ExplicitCaptureRanges
[I
];
2128 // Warn about unused explicit captures.
2129 bool IsCaptureUsed
= true;
2130 if (!CurContext
->isDependentContext() && !IsImplicit
&&
2131 !From
.isODRUsed()) {
2132 // Initialized captures that are non-ODR used may not be eliminated.
2133 // FIXME: Where did the IsGenericLambda here come from?
2134 bool NonODRUsedInitCapture
=
2135 IsGenericLambda
&& From
.isNonODRUsed() && From
.isInitCapture();
2136 if (!NonODRUsedInitCapture
) {
2137 bool IsLast
= (I
+ 1) == LSI
->NumExplicitCaptures
;
2138 SourceRange FixItRange
;
2139 if (CaptureRange
.isValid()) {
2140 if (!CurHasPreviousCapture
&& !IsLast
) {
2141 // If there are no captures preceding this capture, remove the
2143 FixItRange
= SourceRange(CaptureRange
.getBegin(),
2144 getLocForEndOfToken(CaptureRange
.getEnd()));
2146 // Otherwise, remove the comma since the last used capture.
2147 FixItRange
= SourceRange(getLocForEndOfToken(PrevCaptureLoc
),
2148 CaptureRange
.getEnd());
2152 IsCaptureUsed
= !DiagnoseUnusedLambdaCapture(FixItRange
, From
);
2156 if (CaptureRange
.isValid()) {
2157 CurHasPreviousCapture
|= IsCaptureUsed
;
2158 PrevCaptureLoc
= CaptureRange
.getEnd();
2161 // Map the capture to our AST representation.
2162 LambdaCapture Capture
= [&] {
2163 if (From
.isThisCapture()) {
2164 // Capturing 'this' implicitly with a default of '[=]' is deprecated,
2165 // because it results in a reference capture. Don't warn prior to
2166 // C++2a; there's nothing that can be done about it before then.
2167 if (getLangOpts().CPlusPlus20
&& IsImplicit
&&
2168 CaptureDefault
== LCD_ByCopy
) {
2169 Diag(From
.getLocation(), diag::warn_deprecated_this_capture
);
2170 Diag(CaptureDefaultLoc
, diag::note_deprecated_this_capture
)
2171 << FixItHint::CreateInsertion(
2172 getLocForEndOfToken(CaptureDefaultLoc
), ", this");
2174 return LambdaCapture(From
.getLocation(), IsImplicit
,
2175 From
.isCopyCapture() ? LCK_StarThis
: LCK_This
);
2176 } else if (From
.isVLATypeCapture()) {
2177 return LambdaCapture(From
.getLocation(), IsImplicit
, LCK_VLAType
);
2179 assert(From
.isVariableCapture() && "unknown kind of capture");
2180 ValueDecl
*Var
= From
.getVariable();
2181 LambdaCaptureKind Kind
=
2182 From
.isCopyCapture() ? LCK_ByCopy
: LCK_ByRef
;
2183 return LambdaCapture(From
.getLocation(), IsImplicit
, Kind
, Var
,
2184 From
.getEllipsisLoc());
2188 // Form the initializer for the capture field.
2189 ExprResult Init
= BuildCaptureInit(From
, ImplicitCaptureLoc
);
2191 // FIXME: Skip this capture if the capture is not used, the initializer
2192 // has no side-effects, the type of the capture is trivial, and the
2193 // lambda is not externally visible.
2195 // Add a FieldDecl for the capture and form its initializer.
2196 BuildCaptureField(Class
, From
);
2197 Captures
.push_back(Capture
);
2198 CaptureInits
.push_back(Init
.get());
2201 CUDA().CheckLambdaCapture(CallOperator
, From
);
2204 Class
->setCaptures(Context
, Captures
);
2206 // C++11 [expr.prim.lambda]p6:
2207 // The closure type for a lambda-expression with no lambda-capture
2208 // has a public non-virtual non-explicit const conversion function
2209 // to pointer to function having the same parameter and return
2210 // types as the closure type's function call operator.
2211 if (Captures
.empty() && CaptureDefault
== LCD_None
)
2212 addFunctionPointerConversions(*this, IntroducerRange
, Class
,
2216 // The closure type for a lambda-expression has a public non-virtual
2217 // non-explicit const conversion function to a block pointer having the
2218 // same parameter and return types as the closure type's function call
2220 // FIXME: Fix generic lambda to block conversions.
2221 if (getLangOpts().Blocks
&& getLangOpts().ObjC
&& !IsGenericLambda
)
2222 addBlockPointerConversion(*this, IntroducerRange
, Class
, CallOperator
);
2224 // Finalize the lambda class.
2225 SmallVector
<Decl
*, 4> Fields(Class
->fields());
2226 ActOnFields(nullptr, Class
->getLocation(), Class
, Fields
, SourceLocation(),
2227 SourceLocation(), ParsedAttributesView());
2228 CheckCompletedCXXClass(nullptr, Class
);
2231 Cleanup
.mergeFrom(LambdaCleanup
);
2233 LambdaExpr
*Lambda
= LambdaExpr::Create(Context
, Class
, IntroducerRange
,
2234 CaptureDefault
, CaptureDefaultLoc
,
2235 ExplicitParams
, ExplicitResultType
,
2236 CaptureInits
, EndLoc
,
2237 ContainsUnexpandedParameterPack
);
2238 // If the lambda expression's call operator is not explicitly marked constexpr
2239 // and we are not in a dependent context, analyze the call operator to infer
2240 // its constexpr-ness, suppressing diagnostics while doing so.
2241 if (getLangOpts().CPlusPlus17
&& !CallOperator
->isInvalidDecl() &&
2242 !CallOperator
->isConstexpr() &&
2243 !isa
<CoroutineBodyStmt
>(CallOperator
->getBody()) &&
2244 !Class
->getDeclContext()->isDependentContext()) {
2245 CallOperator
->setConstexprKind(
2246 CheckConstexprFunctionDefinition(CallOperator
,
2247 CheckConstexprKind::CheckValid
)
2248 ? ConstexprSpecKind::Constexpr
2249 : ConstexprSpecKind::Unspecified
);
2252 // Emit delayed shadowing warnings now that the full capture list is known.
2253 DiagnoseShadowingLambdaDecls(LSI
);
2255 if (!CurContext
->isDependentContext()) {
2256 switch (ExprEvalContexts
.back().Context
) {
2257 // C++11 [expr.prim.lambda]p2:
2258 // A lambda-expression shall not appear in an unevaluated operand
2260 case ExpressionEvaluationContext::Unevaluated
:
2261 case ExpressionEvaluationContext::UnevaluatedList
:
2262 case ExpressionEvaluationContext::UnevaluatedAbstract
:
2263 // C++1y [expr.const]p2:
2264 // A conditional-expression e is a core constant expression unless the
2265 // evaluation of e, following the rules of the abstract machine, would
2266 // evaluate [...] a lambda-expression.
2268 // This is technically incorrect, there are some constant evaluated contexts
2269 // where this should be allowed. We should probably fix this when DR1607 is
2270 // ratified, it lays out the exact set of conditions where we shouldn't
2271 // allow a lambda-expression.
2272 case ExpressionEvaluationContext::ConstantEvaluated
:
2273 case ExpressionEvaluationContext::ImmediateFunctionContext
:
2274 // We don't actually diagnose this case immediately, because we
2275 // could be within a context where we might find out later that
2276 // the expression is potentially evaluated (e.g., for typeid).
2277 ExprEvalContexts
.back().Lambdas
.push_back(Lambda
);
2280 case ExpressionEvaluationContext::DiscardedStatement
:
2281 case ExpressionEvaluationContext::PotentiallyEvaluated
:
2282 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed
:
2285 maybeAddDeclWithEffects(LSI
->CallOperator
);
2288 return MaybeBindToTemporary(Lambda
);
2291 ExprResult
Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation
,
2292 SourceLocation ConvLocation
,
2293 CXXConversionDecl
*Conv
,
2295 // Make sure that the lambda call operator is marked used.
2296 CXXRecordDecl
*Lambda
= Conv
->getParent();
2297 CXXMethodDecl
*CallOperator
2298 = cast
<CXXMethodDecl
>(
2300 Context
.DeclarationNames
.getCXXOperatorName(OO_Call
)).front());
2301 CallOperator
->setReferenced();
2302 CallOperator
->markUsed(Context
);
2304 ExprResult Init
= PerformCopyInitialization(
2305 InitializedEntity::InitializeLambdaToBlock(ConvLocation
, Src
->getType()),
2306 CurrentLocation
, Src
);
2307 if (!Init
.isInvalid())
2308 Init
= ActOnFinishFullExpr(Init
.get(), /*DiscardedValue*/ false);
2310 if (Init
.isInvalid())
2313 // Create the new block to be returned.
2314 BlockDecl
*Block
= BlockDecl::Create(Context
, CurContext
, ConvLocation
);
2316 // Set the type information.
2317 Block
->setSignatureAsWritten(CallOperator
->getTypeSourceInfo());
2318 Block
->setIsVariadic(CallOperator
->isVariadic());
2319 Block
->setBlockMissingReturnType(false);
2322 SmallVector
<ParmVarDecl
*, 4> BlockParams
;
2323 for (unsigned I
= 0, N
= CallOperator
->getNumParams(); I
!= N
; ++I
) {
2324 ParmVarDecl
*From
= CallOperator
->getParamDecl(I
);
2325 BlockParams
.push_back(ParmVarDecl::Create(
2326 Context
, Block
, From
->getBeginLoc(), From
->getLocation(),
2327 From
->getIdentifier(), From
->getType(), From
->getTypeSourceInfo(),
2328 From
->getStorageClass(),
2329 /*DefArg=*/nullptr));
2331 Block
->setParams(BlockParams
);
2333 Block
->setIsConversionFromLambda(true);
2335 // Add capture. The capture uses a fake variable, which doesn't correspond
2336 // to any actual memory location. However, the initializer copy-initializes
2337 // the lambda object.
2338 TypeSourceInfo
*CapVarTSI
=
2339 Context
.getTrivialTypeSourceInfo(Src
->getType());
2340 VarDecl
*CapVar
= VarDecl::Create(Context
, Block
, ConvLocation
,
2341 ConvLocation
, nullptr,
2342 Src
->getType(), CapVarTSI
,
2344 BlockDecl::Capture
Capture(/*variable=*/CapVar
, /*byRef=*/false,
2345 /*nested=*/false, /*copy=*/Init
.get());
2346 Block
->setCaptures(Context
, Capture
, /*CapturesCXXThis=*/false);
2348 // Add a fake function body to the block. IR generation is responsible
2349 // for filling in the actual body, which cannot be expressed as an AST.
2350 Block
->setBody(new (Context
) CompoundStmt(ConvLocation
));
2352 // Create the block literal expression.
2353 // TODO: Do we ever get here if we have unexpanded packs in the lambda???
2355 new (Context
) BlockExpr(Block
, Conv
->getConversionType(),
2356 /*ContainsUnexpandedParameterPack=*/false);
2357 ExprCleanupObjects
.push_back(Block
);
2358 Cleanup
.setExprNeedsCleanups(true);
2363 static FunctionDecl
*getPatternFunctionDecl(FunctionDecl
*FD
) {
2364 if (FD
->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization
) {
2365 while (FD
->getInstantiatedFromMemberFunction())
2366 FD
= FD
->getInstantiatedFromMemberFunction();
2370 if (FD
->getTemplatedKind() == FunctionDecl::TK_DependentNonTemplate
)
2371 return FD
->getInstantiatedFromDecl();
2373 FunctionTemplateDecl
*FTD
= FD
->getPrimaryTemplate();
2377 while (FTD
->getInstantiatedFromMemberTemplate())
2378 FTD
= FTD
->getInstantiatedFromMemberTemplate();
2380 return FTD
->getTemplatedDecl();
2383 Sema::LambdaScopeForCallOperatorInstantiationRAII::
2384 LambdaScopeForCallOperatorInstantiationRAII(
2385 Sema
&SemaRef
, FunctionDecl
*FD
, MultiLevelTemplateArgumentList MLTAL
,
2386 LocalInstantiationScope
&Scope
, bool ShouldAddDeclsFromParentScope
)
2387 : FunctionScopeRAII(SemaRef
) {
2388 if (!isLambdaCallOperator(FD
)) {
2389 FunctionScopeRAII::disable();
2393 SemaRef
.RebuildLambdaScopeInfo(cast
<CXXMethodDecl
>(FD
));
2395 FunctionDecl
*FDPattern
= getPatternFunctionDecl(FD
);
2399 if (!ShouldAddDeclsFromParentScope
)
2402 FunctionDecl
*InnermostFD
= FD
, *InnermostFDPattern
= FDPattern
;
2403 llvm::SmallVector
<std::pair
<FunctionDecl
*, FunctionDecl
*>, 4>
2404 ParentInstantiations
;
2407 dyn_cast
<FunctionDecl
>(getLambdaAwareParentOfDeclContext(FDPattern
));
2408 FD
= dyn_cast
<FunctionDecl
>(getLambdaAwareParentOfDeclContext(FD
));
2410 if (!FDPattern
|| !FD
)
2413 ParentInstantiations
.emplace_back(FDPattern
, FD
);
2416 // Add instantiated parameters and local vars to scopes, starting from the
2417 // outermost lambda to the innermost lambda. This ordering ensures that
2418 // parameters in inner lambdas can correctly depend on those defined
2419 // in outer lambdas, e.g. auto L = [](auto... x) {
2420 // return [](decltype(x)... y) { }; // `y` depends on `x`
2423 for (const auto &[FDPattern
, FD
] : llvm::reverse(ParentInstantiations
)) {
2424 SemaRef
.addInstantiatedParametersToScope(FD
, FDPattern
, Scope
, MLTAL
);
2425 SemaRef
.addInstantiatedLocalVarsToScope(FD
, FDPattern
, Scope
);
2427 if (isLambdaCallOperator(FD
))
2428 SemaRef
.addInstantiatedCapturesToScope(FD
, FDPattern
, Scope
, MLTAL
);
2431 SemaRef
.addInstantiatedCapturesToScope(InnermostFD
, InnermostFDPattern
, Scope
,