1//===--- SemaLambda.cpp - Semantic Analysis for C++11 Lambdas -------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for C++ lambda expressions.
10//
11//===----------------------------------------------------------------------===//
12#include "clang/Sema/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/SemaARM.h"
25#include "clang/Sema/SemaCUDA.h"
26#include "clang/Sema/SemaInternal.h"
27#include "clang/Sema/SemaOpenMP.h"
28#include "clang/Sema/SemaSYCL.h"
29#include "clang/Sema/Template.h"
30#include "llvm/ADT/STLExtras.h"
31#include <optional>
32using namespace clang;
33using namespace sema;
34
35/// Examines the FunctionScopeInfo stack to determine the nearest
36/// enclosing lambda (to the current lambda) that is 'capture-ready' for
37/// the variable referenced in the current lambda (i.e. \p VarToCapture).
38/// If successful, returns the index into Sema's FunctionScopeInfo stack
39/// of the capture-ready lambda's LambdaScopeInfo.
40///
41/// Climbs down the stack of lambdas (deepest nested lambda - i.e. current
42/// lambda - is on top) to determine the index of the nearest enclosing/outer
43/// lambda that is ready to capture the \p VarToCapture being referenced in
44/// the current lambda.
45/// As we climb down the stack, we want the index of the first such lambda -
46/// that is the lambda with the highest index that is 'capture-ready'.
47///
48/// A lambda 'L' is capture-ready for 'V' (var or this) if:
49/// - its enclosing context is non-dependent
50/// - and if the chain of lambdas between L and the lambda in which
51/// V is potentially used (i.e. the lambda at the top of the scope info
52/// stack), can all capture or have already captured V.
53/// If \p VarToCapture is 'null' then we are trying to capture 'this'.
54///
55/// Note that a lambda that is deemed 'capture-ready' still needs to be checked
56/// for whether it is 'capture-capable' (see
57/// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly
58/// capture.
59///
60/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
61/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
62/// is at the top of the stack and has the highest index.
63/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
64///
65/// \returns An UnsignedOrNone Index that if evaluates to 'true'
66/// contains the index (into Sema's FunctionScopeInfo stack) of the innermost
67/// lambda which is capture-ready. If the return value evaluates to 'false'
68/// then no lambda is capture-ready for \p VarToCapture.
69
70static inline UnsignedOrNone getStackIndexOfNearestEnclosingCaptureReadyLambda(
71 ArrayRef<const clang::sema::FunctionScopeInfo *> FunctionScopes,
72 ValueDecl *VarToCapture) {
73 // Label failure to capture.
74 const UnsignedOrNone NoLambdaIsCaptureReady = std::nullopt;
75
76 // Ignore all inner captured regions.
77 unsigned CurScopeIndex = FunctionScopes.size() - 1;
78 while (CurScopeIndex > 0 && isa<clang::sema::CapturedRegionScopeInfo>(
79 Val: FunctionScopes[CurScopeIndex]))
80 --CurScopeIndex;
81 assert(
82 isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) &&
83 "The function on the top of sema's function-info stack must be a lambda");
84
85 // If VarToCapture is null, we are attempting to capture 'this'.
86 const bool IsCapturingThis = !VarToCapture;
87 const bool IsCapturingVariable = !IsCapturingThis;
88
89 // Start with the current lambda at the top of the stack (highest index).
90 DeclContext *EnclosingDC =
91 cast<sema::LambdaScopeInfo>(Val: FunctionScopes[CurScopeIndex])->CallOperator;
92
93 do {
94 const clang::sema::LambdaScopeInfo *LSI =
95 cast<sema::LambdaScopeInfo>(Val: FunctionScopes[CurScopeIndex]);
96 // IF we have climbed down to an intervening enclosing lambda that contains
97 // the variable declaration - it obviously can/must not capture the
98 // variable.
99 // Since its enclosing DC is dependent, all the lambdas between it and the
100 // innermost nested lambda are dependent (otherwise we wouldn't have
101 // arrived here) - so we don't yet have a lambda that can capture the
102 // variable.
103 if (IsCapturingVariable && VarToCapture->getDeclContext()
104 ->getEnclosingNonExpansionStatementContext()
105 ->Equals(DC: EnclosingDC))
106 return NoLambdaIsCaptureReady;
107
108 // For an enclosing lambda to be capture ready for an entity, all
109 // intervening lambda's have to be able to capture that entity. If even
110 // one of the intervening lambda's is not capable of capturing the entity
111 // then no enclosing lambda can ever capture that entity.
112 // For e.g.
113 // const int x = 10;
114 // [=](auto a) { #1
115 // [](auto b) { #2 <-- an intervening lambda that can never capture 'x'
116 // [=](auto c) { #3
117 // f(x, c); <-- can not lead to x's speculative capture by #1 or #2
118 // }; }; };
119 // If they do not have a default implicit capture, check to see
120 // if the entity has already been explicitly captured.
121 // If even a single dependent enclosing lambda lacks the capability
122 // to ever capture this variable, there is no further enclosing
123 // non-dependent lambda that can capture this variable.
124 if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) {
125 if (IsCapturingVariable && !LSI->isCaptured(Var: VarToCapture))
126 return NoLambdaIsCaptureReady;
127 if (IsCapturingThis && !LSI->isCXXThisCaptured())
128 return NoLambdaIsCaptureReady;
129 }
130 EnclosingDC = getLambdaAwareParentOfDeclContext(DC: EnclosingDC)
131 ->getEnclosingNonExpansionStatementContext();
132
133 assert(CurScopeIndex);
134 --CurScopeIndex;
135 } while (!EnclosingDC->isTranslationUnit() &&
136 EnclosingDC->isDependentContext() &&
137 isLambdaCallOperator(DC: EnclosingDC));
138
139 assert(CurScopeIndex < (FunctionScopes.size() - 1));
140 // If the enclosingDC is not dependent, then the immediately nested lambda
141 // (one index above) is capture-ready.
142 if (!EnclosingDC->isDependentContext())
143 return CurScopeIndex + 1;
144 return NoLambdaIsCaptureReady;
145}
146
147/// Examines the FunctionScopeInfo stack to determine the nearest
148/// enclosing lambda (to the current lambda) that is 'capture-capable' for
149/// the variable referenced in the current lambda (i.e. \p VarToCapture).
150/// If successful, returns the index into Sema's FunctionScopeInfo stack
151/// of the capture-capable lambda's LambdaScopeInfo.
152///
153/// Given the current stack of lambdas being processed by Sema and
154/// the variable of interest, to identify the nearest enclosing lambda (to the
155/// current lambda at the top of the stack) that can truly capture
156/// a variable, it has to have the following two properties:
157/// a) 'capture-ready' - be the innermost lambda that is 'capture-ready':
158/// - climb down the stack (i.e. starting from the innermost and examining
159/// each outer lambda step by step) checking if each enclosing
160/// lambda can either implicitly or explicitly capture the variable.
161/// Record the first such lambda that is enclosed in a non-dependent
162/// context. If no such lambda currently exists return failure.
163/// b) 'capture-capable' - make sure the 'capture-ready' lambda can truly
164/// capture the variable by checking all its enclosing lambdas:
165/// - check if all outer lambdas enclosing the 'capture-ready' lambda
166/// identified above in 'a' can also capture the variable (this is done
167/// via tryCaptureVariable for variables and CheckCXXThisCapture for
168/// 'this' by passing in the index of the Lambda identified in step 'a')
169///
170/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
171/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
172/// is at the top of the stack.
173///
174/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
175///
176///
177/// \returns An UnsignedOrNone Index that if evaluates to 'true'
178/// contains the index (into Sema's FunctionScopeInfo stack) of the innermost
179/// lambda which is capture-capable. If the return value evaluates to 'false'
180/// then no lambda is capture-capable for \p VarToCapture.
181
182UnsignedOrNone clang::getStackIndexOfNearestEnclosingCaptureCapableLambda(
183 ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes,
184 ValueDecl *VarToCapture, Sema &S) {
185
186 const UnsignedOrNone NoLambdaIsCaptureCapable = std::nullopt;
187
188 const UnsignedOrNone OptionalStackIndex =
189 getStackIndexOfNearestEnclosingCaptureReadyLambda(FunctionScopes,
190 VarToCapture);
191 if (!OptionalStackIndex)
192 return NoLambdaIsCaptureCapable;
193
194 const unsigned IndexOfCaptureReadyLambda = *OptionalStackIndex;
195 const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI =
196 cast<sema::LambdaScopeInfo>(Val: FunctionScopes[IndexOfCaptureReadyLambda]);
197
198 // If VarToCapture is null, we are attempting to capture 'this'
199 const bool IsCapturingThis = !VarToCapture;
200 const bool IsCapturingVariable = !IsCapturingThis;
201
202 if (IsCapturingVariable) {
203 // Check if the capture-ready lambda can truly capture the variable, by
204 // checking whether all enclosing lambdas of the capture-ready lambda allow
205 // the capture - i.e. make sure it is capture-capable.
206 QualType CaptureType, DeclRefType;
207 const bool CanCaptureVariable = !S.tryCaptureVariable(
208 Var: VarToCapture,
209 /*ExprVarIsUsedInLoc*/ Loc: SourceLocation(), Kind: TryCaptureKind::Implicit,
210 /*EllipsisLoc*/ SourceLocation(),
211 /*BuildAndDiagnose*/ false, CaptureType, DeclRefType,
212 FunctionScopeIndexToStopAt: &IndexOfCaptureReadyLambda);
213 if (!CanCaptureVariable)
214 return NoLambdaIsCaptureCapable;
215 } else {
216 // Check if the capture-ready lambda can truly capture 'this' by checking
217 // whether all enclosing lambdas of the capture-ready lambda can capture
218 // 'this'.
219 const bool CanCaptureThis =
220 !S.CheckCXXThisCapture(
221 Loc: CaptureReadyLambdaLSI->PotentialThisCaptureLocation,
222 /*Explicit*/ false, /*BuildAndDiagnose*/ false,
223 FunctionScopeIndexToStopAt: &IndexOfCaptureReadyLambda);
224 if (!CanCaptureThis)
225 return NoLambdaIsCaptureCapable;
226 }
227 return IndexOfCaptureReadyLambda;
228}
229
230static inline TemplateParameterList *
231getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) {
232 if (!LSI->GLTemplateParameterList && !LSI->TemplateParams.empty()) {
233 LSI->GLTemplateParameterList = TemplateParameterList::Create(
234 C: SemaRef.Context,
235 /*Begin loc of the lambda expression*/ TemplateLoc: LSI->IntroducerRange.getBegin(),
236 /*L angle loc*/ LAngleLoc: LSI->ExplicitTemplateParamsRange.getBegin(),
237 Params: LSI->TemplateParams,
238 /*R angle loc*/ RAngleLoc: LSI->ExplicitTemplateParamsRange.getEnd(),
239 RequiresClause: LSI->RequiresClause.get());
240 }
241 return LSI->GLTemplateParameterList;
242}
243
244CXXRecordDecl *
245Sema::createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info,
246 unsigned LambdaDependencyKind,
247 LambdaCaptureDefault CaptureDefault) {
248 DeclContext *DC = CurContext->getEnclosingNonExpansionStatementContext();
249
250 bool IsGenericLambda =
251 Info && getGenericLambdaTemplateParameterList(LSI: getCurLambda(), SemaRef&: *this);
252 // Start constructing the lambda class.
253 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(
254 C: Context, DC, Info, Loc: IntroducerRange.getBegin(), DependencyKind: LambdaDependencyKind,
255 IsGeneric: IsGenericLambda, CaptureDefault);
256 DC->addDecl(D: Class);
257
258 return Class;
259}
260
261std::tuple<MangleNumberingContext *, Decl *>
262Sema::getCurrentMangleNumberContext(const DeclContext *DC) {
263 // Compute the context for allocating mangling numbers in the current
264 // expression, if the ABI requires them.
265 Decl *ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
266
267 enum ContextKind {
268 Normal,
269 DefaultArgument,
270 DataMember,
271 InlineVariable,
272 TemplatedVariable,
273 ExternallyVisibleVariableInModulePurview,
274 Concept,
275 } Kind = Normal;
276
277 bool IsInNonspecializedTemplate =
278 inTemplateInstantiation() || CurContext->isDependentContext();
279
280 // Checks if a VarDecl or FunctionDecl is from a module purview and externally
281 // visible. These Decls should be treated as "inline" for the purpose of
282 // mangling in the code below.
283 //
284 // See discussion in https://github.com/itanium-cxx-abi/cxx-abi/issues/186
285 //
286 // zygoloid:
287 // Yeah, I think the only cases left where lambdas don't need a
288 // mangling are when they have (effectively) internal linkage or
289 // appear in a non-inline function in a non-module translation unit.
290 static constexpr auto IsExternallyVisibleInModulePurview =
291 [](const NamedDecl *ND) -> bool {
292 return (ND->isInNamedModule() || ND->isFromGlobalModule()) &&
293 ND->isExternallyVisible();
294 };
295
296 // Default arguments of member function parameters that appear in a class
297 // definition, as well as the initializers of data members, receive special
298 // treatment. Identify them.
299 Kind = [&]() {
300 if (!ManglingContextDecl)
301 return Normal;
302
303 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(Val: ManglingContextDecl)) {
304 if (const DeclContext *LexicalDC
305 = Param->getDeclContext()->getLexicalParent())
306 if (LexicalDC->isRecord())
307 return DefaultArgument;
308 } else if (VarDecl *Var = dyn_cast<VarDecl>(Val: ManglingContextDecl)) {
309 if (Var->getMostRecentDecl()->isInline())
310 return InlineVariable;
311
312 if (IsExternallyVisibleInModulePurview(Var))
313 return ExternallyVisibleVariableInModulePurview;
314
315 if (Var->getDeclContext()->isRecord() && IsInNonspecializedTemplate)
316 return TemplatedVariable;
317
318 if (Var->getDescribedVarTemplate())
319 return TemplatedVariable;
320
321 if (auto *VTS = dyn_cast<VarTemplateSpecializationDecl>(Val: Var)) {
322 if (!VTS->isExplicitSpecialization())
323 return TemplatedVariable;
324 }
325 } else if (isa<FieldDecl>(Val: ManglingContextDecl)) {
326 return DataMember;
327 } else if (isa<ImplicitConceptSpecializationDecl, ConceptDecl>(
328 Val: ManglingContextDecl)) {
329 return Concept;
330 }
331
332 return Normal;
333 }();
334
335 // Determine whether the given context is or is enclosed in a function that
336 // requires Decl's inside to be mangled, so either:
337 // - an inline function
338 // - or a function in a module purview that is externally visible
339 static constexpr auto IsInFunctionThatRequiresMangling =
340 [](const DeclContext *DC) -> bool {
341 while (!DC->isFileContext()) {
342 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: DC))
343 if (FD->isInlined() || IsExternallyVisibleInModulePurview(FD))
344 return true;
345
346 DC = DC->getLexicalParent();
347 }
348
349 return false;
350 };
351
352 // Itanium ABI [5.1.8]:
353 // In the following contexts [...] the one-definition rule requires closure
354 // types in different translation units to "correspond":
355 switch (Kind) {
356 case Normal: {
357 // -- the bodies of inline or templated functions
358 // -- the bodies of externally visible functions in a module purview
359 // (note: this is not yet part of the Itanium ABI, see the linked Github
360 // discussion above)
361 if ((IsInNonspecializedTemplate &&
362 !(ManglingContextDecl && isa<ParmVarDecl>(Val: ManglingContextDecl))) ||
363 IsInFunctionThatRequiresMangling(CurContext)) {
364 while (auto *CD = dyn_cast<CapturedDecl>(Val: DC))
365 DC = CD->getParent();
366 return std::make_tuple(args: &Context.getManglingNumberContext(DC), args: nullptr);
367 }
368
369 return std::make_tuple(args: nullptr, args: nullptr);
370 }
371
372 case Concept:
373 // Concept definitions aren't code generated and thus aren't mangled,
374 // however the ManglingContextDecl is important for the purposes of
375 // re-forming the template argument list of the lambda for constraint
376 // evaluation.
377 case DataMember:
378 // -- default member initializers
379 case DefaultArgument:
380 // -- default arguments appearing in class definitions
381 case InlineVariable:
382 case ExternallyVisibleVariableInModulePurview:
383 case TemplatedVariable:
384 // -- the initializers of inline or templated variables
385 // -- the initializers of externally visible variables in a module purview
386 // (note: this is not yet part of the Itanium ABI, see the linked Github
387 // discussion above)
388 return std::make_tuple(
389 args: &Context.getManglingNumberContext(ASTContext::NeedExtraManglingDecl,
390 D: ManglingContextDecl),
391 args&: ManglingContextDecl);
392 }
393
394 llvm_unreachable("unexpected context");
395}
396
397static QualType
398buildTypeForLambdaCallOperator(Sema &S, clang::CXXRecordDecl *Class,
399 TemplateParameterList *TemplateParams,
400 TypeSourceInfo *MethodTypeInfo) {
401 assert(MethodTypeInfo && "expected a non null type");
402
403 QualType MethodType = MethodTypeInfo->getType();
404 // If a lambda appears in a dependent context or is a generic lambda (has
405 // template parameters) and has an 'auto' return type, deduce it to a
406 // dependent type.
407 if (Class->isDependentContext() || TemplateParams) {
408 const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
409 QualType Result = FPT->getReturnType();
410 if (Result->isUndeducedType()) {
411 Result = S.SubstAutoTypeDependent(TypeWithAuto: Result);
412 MethodType = S.Context.getFunctionType(ResultTy: Result, Args: FPT->getParamTypes(),
413 EPI: FPT->getExtProtoInfo());
414 }
415 }
416 return MethodType;
417}
418
419// [C++2b] [expr.prim.lambda.closure] p4
420// Given a lambda with a lambda-capture, the type of the explicit object
421// parameter, if any, of the lambda's function call operator (possibly
422// instantiated from a function call operator template) shall be either:
423// - the closure type,
424// - class type publicly and unambiguously derived from the closure type, or
425// - a reference to a possibly cv-qualified such type.
426bool Sema::DiagnoseInvalidExplicitObjectParameterInLambda(
427 CXXMethodDecl *Method, SourceLocation CallLoc) {
428 if (!isLambdaCallWithExplicitObjectParameter(DC: Method))
429 return false;
430 CXXRecordDecl *RD = Method->getParent();
431 if (Method->getType()->isDependentType())
432 return false;
433 if (RD->isCapturelessLambda())
434 return false;
435
436 ParmVarDecl *Param = Method->getParamDecl(i: 0);
437 QualType ExplicitObjectParameterType = Param->getType()
438 .getNonReferenceType()
439 .getUnqualifiedType()
440 .getDesugaredType(Context: getASTContext());
441 CanQualType LambdaType = getASTContext().getCanonicalTagType(TD: RD);
442 if (LambdaType == ExplicitObjectParameterType)
443 return false;
444
445 // Don't check the same instantiation twice.
446 //
447 // If this call operator is ill-formed, there is no point in issuing
448 // a diagnostic every time it is called because the problem is in the
449 // definition of the derived type, not at the call site.
450 //
451 // FIXME: Move this check to where we instantiate the method? This should
452 // be possible, but the naive approach of just marking the method as invalid
453 // leads to us emitting more diagnostics than we should have to for this case
454 // (1 error here *and* 1 error about there being no matching overload at the
455 // call site). It might be possible to avoid that by also checking if there
456 // is an empty cast path for the method stored in the context (signalling that
457 // we've already diagnosed it) and then just not building the call, but that
458 // doesn't really seem any simpler than diagnosing it at the call site...
459 auto [It, Inserted] = Context.LambdaCastPaths.try_emplace(Key: Method);
460 if (!Inserted)
461 return It->second.empty();
462
463 CXXCastPath &Path = It->second;
464 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
465 /*DetectVirtual=*/false);
466 if (!IsDerivedFrom(Loc: RD->getLocation(), Derived: ExplicitObjectParameterType, Base: LambdaType,
467 Paths)) {
468 Diag(Loc: Param->getLocation(), DiagID: diag::err_invalid_explicit_object_type_in_lambda)
469 << ExplicitObjectParameterType;
470 return true;
471 }
472
473 if (Paths.isAmbiguous(BaseType: LambdaType)) {
474 std::string PathsDisplay = getAmbiguousPathsDisplayString(Paths);
475 Diag(Loc: CallLoc, DiagID: diag::err_explicit_object_lambda_ambiguous_base)
476 << LambdaType << PathsDisplay;
477 return true;
478 }
479
480 if (CheckBaseClassAccess(AccessLoc: CallLoc, Base: LambdaType, Derived: ExplicitObjectParameterType,
481 Path: Paths.front(),
482 DiagID: diag::err_explicit_object_lambda_inaccessible_base))
483 return true;
484
485 BuildBasePathArray(Paths, BasePath&: Path);
486 return false;
487}
488
489void Sema::handleLambdaNumbering(
490 CXXRecordDecl *Class, CXXMethodDecl *Method,
491 std::optional<CXXRecordDecl::LambdaNumbering> NumberingOverride) {
492 ContextRAII ManglingContext(*this, Class->getDeclContext());
493
494 auto getMangleNumberingContext =
495 [this](CXXRecordDecl *Class,
496 Decl *ManglingContextDecl) -> MangleNumberingContext * {
497 // Get mangle numbering context if there's any extra decl context.
498 if (ManglingContextDecl)
499 return &Context.getManglingNumberContext(
500 ASTContext::NeedExtraManglingDecl, D: ManglingContextDecl);
501 // Otherwise, from that lambda's decl context.
502 auto DC = Class->getDeclContext();
503 while (auto *CD = dyn_cast<CapturedDecl>(Val: DC))
504 DC = CD->getParent();
505 return &Context.getManglingNumberContext(DC);
506 };
507
508 MangleNumberingContext *MCtx;
509 Decl *ContextDecl;
510 std::tie(args&: MCtx, args&: ContextDecl) =
511 getCurrentMangleNumberContext(DC: Class->getDeclContext());
512 // getManglingNumber(Method) below may trigger mangling of dependent types
513 // that reference init-captures. Publish the lambda context declaration early
514 // so such mangling can resolve the surrounding context without recursing
515 // through the lambda call operator. This avoids publishing provisional
516 // numbering state before final numbering is assigned below.
517 if (ContextDecl)
518 Class->setLambdaContextDecl(ContextDecl);
519 if (NumberingOverride) {
520 Class->setLambdaNumbering(*NumberingOverride);
521 return;
522 }
523
524 CXXRecordDecl::LambdaNumbering Numbering;
525 if (!MCtx && (getLangOpts().CUDA || getLangOpts().SYCLIsDevice ||
526 getLangOpts().SYCLIsHost)) {
527 // Force lambda numbering in CUDA/HIP as we need to name lambdas following
528 // ODR. Both device- and host-compilation need to have a consistent naming
529 // on kernel functions. As lambdas are potential part of these `__global__`
530 // function names, they needs numbering following ODR.
531 // Also force for SYCL, since we need this for the
532 // __builtin_sycl_unique_stable_name implementation, which depends on lambda
533 // mangling.
534 MCtx = getMangleNumberingContext(Class, ContextDecl);
535 assert(MCtx && "Retrieving mangle numbering context failed!");
536 Numbering.HasKnownInternalLinkage = true;
537 }
538 if (MCtx) {
539 Numbering.IndexInContext = MCtx->getNextLambdaIndex();
540 Numbering.ManglingNumber = MCtx->getManglingNumber(CallOperator: Method);
541 Numbering.DeviceManglingNumber = MCtx->getDeviceManglingNumber(Method);
542 Class->setLambdaNumbering(Numbering);
543
544 if (auto *Source =
545 dyn_cast_or_null<ExternalSemaSource>(Val: Context.getExternalSource()))
546 Source->AssignedLambdaNumbering(Lambda: Class);
547 }
548}
549
550static void buildLambdaScopeReturnType(Sema &S, LambdaScopeInfo *LSI,
551 CXXMethodDecl *CallOperator,
552 bool ExplicitResultType) {
553 if (ExplicitResultType) {
554 LSI->HasImplicitReturnType = false;
555 LSI->ReturnType = CallOperator->getReturnType();
556 if (!LSI->ReturnType->isDependentType() && !LSI->ReturnType->isVoidType())
557 S.RequireCompleteType(Loc: CallOperator->getBeginLoc(), T: LSI->ReturnType,
558 DiagID: diag::err_lambda_incomplete_result);
559 } else {
560 LSI->HasImplicitReturnType = true;
561 }
562}
563
564void Sema::buildLambdaScope(LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator,
565 SourceRange IntroducerRange,
566 LambdaCaptureDefault CaptureDefault,
567 SourceLocation CaptureDefaultLoc,
568 bool ExplicitParams, bool Mutable) {
569 LSI->CallOperator = CallOperator;
570 CXXRecordDecl *LambdaClass = CallOperator->getParent();
571 LSI->Lambda = LambdaClass;
572 if (CaptureDefault == LCD_ByCopy)
573 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
574 else if (CaptureDefault == LCD_ByRef)
575 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
576 LSI->CaptureDefaultLoc = CaptureDefaultLoc;
577 LSI->IntroducerRange = IntroducerRange;
578 LSI->ExplicitParams = ExplicitParams;
579 LSI->Mutable = Mutable;
580}
581
582void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
583 LSI->finishedExplicitCaptures();
584}
585
586void Sema::ActOnLambdaExplicitTemplateParameterList(
587 LambdaIntroducer &Intro, SourceLocation LAngleLoc,
588 ArrayRef<NamedDecl *> TParams, SourceLocation RAngleLoc,
589 ExprResult RequiresClause) {
590 LambdaScopeInfo *LSI = getCurLambda();
591 assert(LSI && "Expected a lambda scope");
592 assert(LSI->NumExplicitTemplateParams == 0 &&
593 "Already acted on explicit template parameters");
594 assert(LSI->TemplateParams.empty() &&
595 "Explicit template parameters should come "
596 "before invented (auto) ones");
597 assert(!TParams.empty() &&
598 "No template parameters to act on");
599 LSI->TemplateParams.append(in_start: TParams.begin(), in_end: TParams.end());
600 LSI->NumExplicitTemplateParams = TParams.size();
601 LSI->ExplicitTemplateParamsRange = {LAngleLoc, RAngleLoc};
602 LSI->RequiresClause = RequiresClause;
603}
604
605/// If this expression is an enumerator-like expression of some type
606/// T, return the type T; otherwise, return null.
607///
608/// Pointer comparisons on the result here should always work because
609/// it's derived from either the parent of an EnumConstantDecl
610/// (i.e. the definition) or the declaration returned by
611/// EnumType::getDecl() (i.e. the definition).
612static EnumDecl *findEnumForBlockReturn(Expr *E) {
613 // An expression is an enumerator-like expression of type T if,
614 // ignoring parens and parens-like expressions:
615 E = E->IgnoreParens();
616
617 // - it is an enumerator whose enum type is T or
618 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
619 if (EnumConstantDecl *D
620 = dyn_cast<EnumConstantDecl>(Val: DRE->getDecl())) {
621 return cast<EnumDecl>(Val: D->getDeclContext());
622 }
623 return nullptr;
624 }
625
626 // - it is a comma expression whose RHS is an enumerator-like
627 // expression of type T or
628 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
629 if (BO->getOpcode() == BO_Comma)
630 return findEnumForBlockReturn(E: BO->getRHS());
631 return nullptr;
632 }
633
634 // - it is a statement-expression whose value expression is an
635 // enumerator-like expression of type T or
636 if (StmtExpr *SE = dyn_cast<StmtExpr>(Val: E)) {
637 if (Expr *last = dyn_cast_or_null<Expr>(Val: SE->getSubStmt()->body_back()))
638 return findEnumForBlockReturn(E: last);
639 return nullptr;
640 }
641
642 // - it is a ternary conditional operator (not the GNU ?:
643 // extension) whose second and third operands are
644 // enumerator-like expressions of type T or
645 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
646 if (EnumDecl *ED = findEnumForBlockReturn(E: CO->getTrueExpr()))
647 if (ED == findEnumForBlockReturn(E: CO->getFalseExpr()))
648 return ED;
649 return nullptr;
650 }
651
652 // (implicitly:)
653 // - it is an implicit integral conversion applied to an
654 // enumerator-like expression of type T or
655 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: E)) {
656 // We can sometimes see integral conversions in valid
657 // enumerator-like expressions.
658 if (ICE->getCastKind() == CK_IntegralCast)
659 return findEnumForBlockReturn(E: ICE->getSubExpr());
660
661 // Otherwise, just rely on the type.
662 }
663
664 // - it is an expression of that formal enum type.
665 if (auto *ED = E->getType()->getAsEnumDecl())
666 return ED;
667
668 // Otherwise, nope.
669 return nullptr;
670}
671
672/// Attempt to find a type T for which the returned expression of the
673/// given statement is an enumerator-like expression of that type.
674static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
675 if (Expr *retValue = ret->getRetValue())
676 return findEnumForBlockReturn(E: retValue);
677 return nullptr;
678}
679
680/// Attempt to find a common type T for which all of the returned
681/// expressions in a block are enumerator-like expressions of that
682/// type.
683static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
684 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
685
686 // Try to find one for the first return.
687 EnumDecl *ED = findEnumForBlockReturn(ret: *i);
688 if (!ED) return nullptr;
689
690 // Check that the rest of the returns have the same enum.
691 for (++i; i != e; ++i) {
692 if (findEnumForBlockReturn(ret: *i) != ED)
693 return nullptr;
694 }
695
696 // Never infer an anonymous enum type.
697 if (!ED->hasNameForLinkage()) return nullptr;
698
699 return ED;
700}
701
702/// Adjust the given return statements so that they formally return
703/// the given type. It should require, at most, an IntegralCast.
704static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
705 QualType returnType) {
706 for (ArrayRef<ReturnStmt*>::iterator
707 i = returns.begin(), e = returns.end(); i != e; ++i) {
708 ReturnStmt *ret = *i;
709 Expr *retValue = ret->getRetValue();
710 if (S.Context.hasSameType(T1: retValue->getType(), T2: returnType))
711 continue;
712
713 // Right now we only support integral fixup casts.
714 assert(returnType->isIntegralOrUnscopedEnumerationType());
715 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
716
717 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(Val: retValue);
718
719 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
720 E = ImplicitCastExpr::Create(Context: S.Context, T: returnType, Kind: CK_IntegralCast, Operand: E,
721 /*base path*/ BasePath: nullptr, Cat: VK_PRValue,
722 FPO: FPOptionsOverride());
723 if (cleanups) {
724 cleanups->setSubExpr(E);
725 } else {
726 ret->setRetValue(E);
727 }
728 }
729}
730
731void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
732 assert(CSI.HasImplicitReturnType);
733 // If it was ever a placeholder, it had to been deduced to DependentTy.
734 assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
735 assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) &&
736 "lambda expressions use auto deduction in C++14 onwards");
737
738 // C++ core issue 975:
739 // If a lambda-expression does not include a trailing-return-type,
740 // it is as if the trailing-return-type denotes the following type:
741 // - if there are no return statements in the compound-statement,
742 // or all return statements return either an expression of type
743 // void or no expression or braced-init-list, the type void;
744 // - otherwise, if all return statements return an expression
745 // and the types of the returned expressions after
746 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
747 // array-to-pointer conversion (4.2 [conv.array]), and
748 // function-to-pointer conversion (4.3 [conv.func]) are the
749 // same, that common type;
750 // - otherwise, the program is ill-formed.
751 //
752 // C++ core issue 1048 additionally removes top-level cv-qualifiers
753 // from the types of returned expressions to match the C++14 auto
754 // deduction rules.
755 //
756 // In addition, in blocks in non-C++ modes, if all of the return
757 // statements are enumerator-like expressions of some type T, where
758 // T has a name for linkage, then we infer the return type of the
759 // block to be that type.
760
761 // First case: no return statements, implicit void return type.
762 ASTContext &Ctx = getASTContext();
763 if (CSI.Returns.empty()) {
764 // It's possible there were simply no /valid/ return statements.
765 // In this case, the first one we found may have at least given us a type.
766 if (CSI.ReturnType.isNull())
767 CSI.ReturnType = Ctx.VoidTy;
768 return;
769 }
770
771 // Second case: at least one return statement has dependent type.
772 // Delay type checking until instantiation.
773 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
774 if (CSI.ReturnType->isDependentType())
775 return;
776
777 // Try to apply the enum-fuzz rule.
778 if (!getLangOpts().CPlusPlus) {
779 assert(isa<BlockScopeInfo>(CSI));
780 const EnumDecl *ED = findCommonEnumForBlockReturns(returns: CSI.Returns);
781 if (ED) {
782 CSI.ReturnType = Context.getCanonicalTagType(TD: ED);
783 adjustBlockReturnsToEnum(S&: *this, returns: CSI.Returns, returnType: CSI.ReturnType);
784 return;
785 }
786 }
787
788 // Third case: only one return statement. Don't bother doing extra work!
789 if (CSI.Returns.size() == 1)
790 return;
791
792 // General case: many return statements.
793 // Check that they all have compatible return types.
794
795 // We require the return types to strictly match here.
796 // Note that we've already done the required promotions as part of
797 // processing the return statement.
798 for (const ReturnStmt *RS : CSI.Returns) {
799 const Expr *RetE = RS->getRetValue();
800
801 QualType ReturnType =
802 (RetE ? RetE->getType() : Context.VoidTy).getUnqualifiedType();
803 if (Context.getCanonicalFunctionResultType(ResultType: ReturnType) ==
804 Context.getCanonicalFunctionResultType(ResultType: CSI.ReturnType)) {
805 // Use the return type with the strictest possible nullability annotation.
806 auto RetTyNullability = ReturnType->getNullability();
807 auto BlockNullability = CSI.ReturnType->getNullability();
808 if (BlockNullability &&
809 (!RetTyNullability ||
810 hasWeakerNullability(L: *RetTyNullability, R: *BlockNullability)))
811 CSI.ReturnType = ReturnType;
812 continue;
813 }
814
815 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
816 // TODO: It's possible that the *first* return is the divergent one.
817 Diag(Loc: RS->getBeginLoc(),
818 DiagID: diag::err_typecheck_missing_return_type_incompatible)
819 << ReturnType << CSI.ReturnType << isa<LambdaScopeInfo>(Val: CSI);
820 // Continue iterating so that we keep emitting diagnostics.
821 }
822}
823
824QualType Sema::buildLambdaInitCaptureInitialization(
825 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
826 UnsignedOrNone NumExpansions, IdentifierInfo *Id, bool IsDirectInit,
827 Expr *&Init) {
828 // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to
829 // deduce against.
830 QualType DeductType = Context.getAutoDeductType();
831 TypeLocBuilder TLB;
832 AutoTypeLoc TL = TLB.push<AutoTypeLoc>(T: DeductType);
833 TL.setNameLoc(Loc);
834 if (ByRef) {
835 DeductType = BuildReferenceType(T: DeductType, LValueRef: true, Loc, Entity: Id);
836 assert(!DeductType.isNull() && "can't build reference to auto");
837 TLB.push<ReferenceTypeLoc>(T: DeductType).setSigilLoc(Loc);
838 }
839 if (EllipsisLoc.isValid()) {
840 if (Init->containsUnexpandedParameterPack()) {
841 Diag(Loc: EllipsisLoc, DiagID: getLangOpts().CPlusPlus20
842 ? diag::warn_cxx17_compat_init_capture_pack
843 : diag::ext_init_capture_pack);
844 DeductType = Context.getPackExpansionType(Pattern: DeductType, NumExpansions,
845 /*ExpectPackInType=*/false);
846 TLB.push<PackExpansionTypeLoc>(T: DeductType).setEllipsisLoc(EllipsisLoc);
847 } else {
848 // Just ignore the ellipsis for now and form a non-pack variable. We'll
849 // diagnose this later when we try to capture it.
850 }
851 }
852 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, T: DeductType);
853
854 // Deduce the type of the init capture.
855 QualType DeducedType = deduceVarTypeFromInitializer(
856 /*VarDecl*/VDecl: nullptr, Name: DeclarationName(Id), Type: DeductType, TSI,
857 Range: SourceRange(Loc, Loc), DirectInit: IsDirectInit, Init);
858 if (DeducedType.isNull())
859 return QualType();
860
861 // Are we a non-list direct initialization?
862 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Val: Init);
863
864 // Perform initialization analysis and ensure any implicit conversions
865 // (such as lvalue-to-rvalue) are enforced.
866 InitializedEntity Entity =
867 InitializedEntity::InitializeLambdaCapture(VarID: Id, FieldType: DeducedType, Loc);
868 InitializationKind Kind =
869 IsDirectInit
870 ? (CXXDirectInit ? InitializationKind::CreateDirect(
871 InitLoc: Loc, LParenLoc: Init->getBeginLoc(), RParenLoc: Init->getEndLoc())
872 : InitializationKind::CreateDirectList(InitLoc: Loc))
873 : InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: Init->getBeginLoc());
874
875 MultiExprArg Args = Init;
876 if (CXXDirectInit)
877 Args =
878 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
879 QualType DclT;
880 InitializationSequence InitSeq(*this, Entity, Kind, Args);
881 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args, ResultType: &DclT);
882
883 if (Result.isInvalid())
884 return QualType();
885
886 Init = Result.getAs<Expr>();
887 return DeducedType;
888}
889
890VarDecl *Sema::createLambdaInitCaptureVarDecl(
891 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
892 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx) {
893 // FIXME: Retain the TypeSourceInfo from buildLambdaInitCaptureInitialization
894 // rather than reconstructing it here.
895 TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(T: InitCaptureType, Loc);
896 if (auto PETL = TSI->getTypeLoc().getAs<PackExpansionTypeLoc>())
897 PETL.setEllipsisLoc(EllipsisLoc);
898
899 // Create a dummy variable representing the init-capture. This is not actually
900 // used as a variable, and only exists as a way to name and refer to the
901 // init-capture.
902 // FIXME: Pass in separate source locations for '&' and identifier.
903 VarDecl *NewVD = VarDecl::Create(C&: Context, DC: DeclCtx, StartLoc: Loc, IdLoc: Loc, Id,
904 T: InitCaptureType, TInfo: TSI, S: SC_Auto);
905 NewVD->setInitCapture(true);
906 NewVD->setReferenced(true);
907 // FIXME: Pass in a VarDecl::InitializationStyle.
908 NewVD->setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle));
909 NewVD->markUsed(C&: Context);
910 NewVD->setInit(Init);
911 if (NewVD->isParameterPack())
912 getCurLambda()->LocalPacks.push_back(Elt: NewVD);
913 return NewVD;
914}
915
916void Sema::addInitCapture(LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef) {
917 assert(Var->isInitCapture() && "init capture flag should be set");
918 LSI->addCapture(Var, /*isBlock=*/false, isByref: ByRef,
919 /*isNested=*/false, Loc: Var->getLocation(), EllipsisLoc: SourceLocation(),
920 CaptureType: Var->getType(), /*Invalid=*/false);
921}
922
923// Unlike getCurLambda, getCurrentLambdaScopeUnsafe doesn't
924// check that the current lambda is in a consistent or fully constructed state.
925static LambdaScopeInfo *getCurrentLambdaScopeUnsafe(Sema &S) {
926 assert(!S.FunctionScopes.empty());
927 return cast<LambdaScopeInfo>(Val: S.FunctionScopes[S.FunctionScopes.size() - 1]);
928}
929
930static TypeSourceInfo *
931getDummyLambdaType(Sema &S, SourceLocation Loc = SourceLocation()) {
932 // C++11 [expr.prim.lambda]p4:
933 // If a lambda-expression does not include a lambda-declarator, it is as
934 // if the lambda-declarator were ().
935 FunctionProtoType::ExtProtoInfo EPI(S.Context.getDefaultCallingConvention(
936 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
937 EPI.HasTrailingReturn = true;
938 EPI.TypeQuals.addConst();
939 LangAS AS = S.getDefaultCXXMethodAddrSpace();
940 if (AS != LangAS::Default)
941 EPI.TypeQuals.addAddressSpace(space: AS);
942
943 // C++1y [expr.prim.lambda]:
944 // The lambda return type is 'auto', which is replaced by the
945 // trailing-return type if provided and/or deduced from 'return'
946 // statements
947 // We don't do this before C++1y, because we don't support deduced return
948 // types there.
949 QualType DefaultTypeForNoTrailingReturn = S.getLangOpts().CPlusPlus14
950 ? S.Context.getAutoDeductType()
951 : S.Context.DependentTy;
952 QualType MethodTy =
953 S.Context.getFunctionType(ResultTy: DefaultTypeForNoTrailingReturn, Args: {}, EPI);
954 return S.Context.getTrivialTypeSourceInfo(T: MethodTy, Loc);
955}
956
957static TypeSourceInfo *getLambdaType(Sema &S, LambdaIntroducer &Intro,
958 Declarator &ParamInfo, Scope *CurScope,
959 SourceLocation Loc,
960 bool &ExplicitResultType) {
961
962 ExplicitResultType = false;
963
964 assert(
965 (ParamInfo.getDeclSpec().getStorageClassSpec() ==
966 DeclSpec::SCS_unspecified ||
967 ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static) &&
968 "Unexpected storage specifier");
969 bool IsLambdaStatic =
970 ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static;
971
972 TypeSourceInfo *MethodTyInfo;
973
974 if (ParamInfo.getNumTypeObjects() == 0) {
975 MethodTyInfo = getDummyLambdaType(S, Loc);
976 } else {
977 // Check explicit parameters
978 S.CheckExplicitObjectLambda(D&: ParamInfo);
979
980 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
981
982 bool HasExplicitObjectParameter =
983 ParamInfo.isExplicitObjectMemberFunction();
984
985 ExplicitResultType = FTI.hasTrailingReturnType();
986 if (!FTI.hasMutableQualifier() && !IsLambdaStatic &&
987 !HasExplicitObjectParameter)
988 FTI.getOrCreateMethodQualifiers().SetTypeQual(T: DeclSpec::TQ_const, Loc);
989
990 if (ExplicitResultType && S.getLangOpts().HLSL) {
991 QualType RetTy = FTI.getTrailingReturnType().get();
992 if (!RetTy.isNull()) {
993 // HLSL does not support specifying an address space on a lambda return
994 // type.
995 LangAS AddressSpace = RetTy.getAddressSpace();
996 if (AddressSpace != LangAS::Default)
997 S.Diag(Loc: FTI.getTrailingReturnTypeLoc(),
998 DiagID: diag::err_return_value_with_address_space);
999 }
1000 }
1001
1002 MethodTyInfo = S.GetTypeForDeclarator(D&: ParamInfo);
1003 assert(MethodTyInfo && "no type from lambda-declarator");
1004
1005 // Check for unexpanded parameter packs in the method type.
1006 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
1007 S.DiagnoseUnexpandedParameterPack(Loc: Intro.Range.getBegin(), T: MethodTyInfo,
1008 UPPC: S.UPPC_DeclarationType);
1009 }
1010 return MethodTyInfo;
1011}
1012
1013CXXMethodDecl *Sema::CreateLambdaCallOperator(SourceRange IntroducerRange,
1014 CXXRecordDecl *Class) {
1015
1016 // C++20 [expr.prim.lambda.closure]p3:
1017 // The closure type for a lambda-expression has a public inline function
1018 // call operator (for a non-generic lambda) or function call operator
1019 // template (for a generic lambda) whose parameters and return type are
1020 // described by the lambda-expression's parameter-declaration-clause
1021 // and trailing-return-type respectively.
1022 DeclarationName MethodName =
1023 Context.DeclarationNames.getCXXOperatorName(Op: OO_Call);
1024 DeclarationNameLoc MethodNameLoc =
1025 DeclarationNameLoc::makeCXXOperatorNameLoc(Range: IntroducerRange.getBegin());
1026 CXXMethodDecl *Method = CXXMethodDecl::Create(
1027 C&: Context, RD: Class, StartLoc: SourceLocation(),
1028 NameInfo: DeclarationNameInfo(MethodName, IntroducerRange.getBegin(),
1029 MethodNameLoc),
1030 T: QualType(), /*Tinfo=*/TInfo: nullptr, SC: SC_None,
1031 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
1032 /*isInline=*/true, ConstexprKind: ConstexprSpecKind::Unspecified, EndLocation: SourceLocation(),
1033 /*TrailingRequiresClause=*/{});
1034 Method->setAccess(AS_public);
1035 return Method;
1036}
1037
1038void Sema::AddTemplateParametersToLambdaCallOperator(
1039 CXXMethodDecl *CallOperator, CXXRecordDecl *Class,
1040 TemplateParameterList *TemplateParams) {
1041 assert(TemplateParams && "no template parameters");
1042 FunctionTemplateDecl *TemplateMethod = FunctionTemplateDecl::Create(
1043 C&: Context, DC: Class, L: CallOperator->getLocation(), Name: CallOperator->getDeclName(),
1044 Params: TemplateParams, Decl: CallOperator);
1045 TemplateMethod->setAccess(AS_public);
1046 CallOperator->setDescribedFunctionTemplate(TemplateMethod);
1047}
1048
1049void Sema::CompleteLambdaCallOperator(
1050 CXXMethodDecl *Method, SourceLocation LambdaLoc,
1051 SourceLocation CallOperatorLoc,
1052 const AssociatedConstraint &TrailingRequiresClause,
1053 TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind,
1054 StorageClass SC, ArrayRef<ParmVarDecl *> Params,
1055 bool HasExplicitResultType) {
1056
1057 LambdaScopeInfo *LSI = getCurrentLambdaScopeUnsafe(S&: *this);
1058
1059 if (TrailingRequiresClause)
1060 Method->setTrailingRequiresClause(TrailingRequiresClause);
1061
1062 TemplateParameterList *TemplateParams =
1063 getGenericLambdaTemplateParameterList(LSI, SemaRef&: *this);
1064
1065 DeclContext *DC = Method->getLexicalDeclContext();
1066 // DeclContext::addDecl() assumes that the DeclContext we're adding to is the
1067 // lexical context of the Method. Do so.
1068 Method->setLexicalDeclContext(LSI->Lambda);
1069 if (TemplateParams) {
1070 FunctionTemplateDecl *TemplateMethod =
1071 Method->getDescribedFunctionTemplate();
1072 assert(TemplateMethod &&
1073 "AddTemplateParametersToLambdaCallOperator should have been called");
1074
1075 LSI->Lambda->addDecl(D: TemplateMethod);
1076 TemplateMethod->setLexicalDeclContext(DC);
1077 } else {
1078 LSI->Lambda->addDecl(D: Method);
1079 }
1080 LSI->Lambda->setLambdaIsGeneric(TemplateParams);
1081 LSI->Lambda->setLambdaTypeInfo(MethodTyInfo);
1082
1083 Method->setLexicalDeclContext(DC);
1084 Method->setLocation(LambdaLoc);
1085 Method->setInnerLocStart(CallOperatorLoc);
1086 Method->setTypeSourceInfo(MethodTyInfo);
1087 Method->setType(buildTypeForLambdaCallOperator(S&: *this, Class: LSI->Lambda,
1088 TemplateParams, MethodTypeInfo: MethodTyInfo));
1089 Method->setConstexprKind(ConstexprKind);
1090 Method->setStorageClass(SC);
1091 if (!Params.empty()) {
1092 CheckParmsForFunctionDef(Parameters: Params, /*CheckParameterNames=*/false);
1093 Method->setParams(Params);
1094 for (auto P : Method->parameters()) {
1095 assert(P && "null in a parameter list");
1096 P->setOwningFunction(Method);
1097 }
1098 }
1099
1100 buildLambdaScopeReturnType(S&: *this, LSI, CallOperator: Method, ExplicitResultType: HasExplicitResultType);
1101}
1102
1103void Sema::ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro,
1104 Scope *CurrentScope) {
1105
1106 LambdaScopeInfo *LSI = getCurLambda();
1107 assert(LSI && "LambdaScopeInfo should be on stack!");
1108
1109 if (Intro.Default == LCD_ByCopy)
1110 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
1111 else if (Intro.Default == LCD_ByRef)
1112 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
1113 LSI->CaptureDefaultLoc = Intro.DefaultLoc;
1114 LSI->IntroducerRange = Intro.Range;
1115 LSI->AfterParameterList = false;
1116
1117 assert(LSI->NumExplicitTemplateParams == 0);
1118
1119 // Determine if we're within a context where we know that the lambda will
1120 // be dependent, because there are template parameters in scope.
1121 CXXRecordDecl::LambdaDependencyKind LambdaDependencyKind =
1122 CXXRecordDecl::LDK_Unknown;
1123 if (CurScope->getTemplateParamParent() != nullptr) {
1124 LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
1125 } else if (Scope *ParentScope = CurScope->getParent()) {
1126 // Given a lambda defined inside a requires expression,
1127 //
1128 // struct S {
1129 // S(auto var) requires requires { [&] -> decltype(var) { }; }
1130 // {}
1131 // };
1132 //
1133 // The parameter var is not injected into the function Decl at the point of
1134 // parsing lambda. In such scenarios, perceiving it as dependent could
1135 // result in the constraint being evaluated, which matches what GCC does.
1136 Scope *LookupScope = ParentScope;
1137 while (LookupScope->getEntity() &&
1138 LookupScope->getEntity()->isRequiresExprBody())
1139 LookupScope = LookupScope->getParent();
1140
1141 if (LookupScope != ParentScope &&
1142 LookupScope->isFunctionDeclarationScope() &&
1143 llvm::any_of(Range: LookupScope->decls(), P: [](Decl *D) {
1144 return isa<ParmVarDecl>(Val: D) &&
1145 cast<ParmVarDecl>(Val: D)->getType()->isTemplateTypeParmType();
1146 }))
1147 LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
1148 }
1149
1150 CXXRecordDecl *Class = createLambdaClosureType(
1151 IntroducerRange: Intro.Range, /*Info=*/nullptr, LambdaDependencyKind, CaptureDefault: Intro.Default);
1152 LSI->Lambda = Class;
1153
1154 CXXMethodDecl *Method = CreateLambdaCallOperator(IntroducerRange: Intro.Range, Class);
1155 LSI->CallOperator = Method;
1156 // Temporarily set the lexical declaration context to the current
1157 // context, so that the Scope stack matches the lexical nesting.
1158 Method->setLexicalDeclContext(CurContext);
1159
1160 PushDeclContext(S: CurScope, DC: Method);
1161
1162 bool ContainsUnexpandedParameterPack = false;
1163
1164 // Distinct capture names, for diagnostics.
1165 llvm::DenseMap<IdentifierInfo *, ValueDecl *> CaptureNames;
1166
1167 // Handle explicit captures.
1168 SourceLocation PrevCaptureLoc =
1169 Intro.Default == LCD_None ? Intro.Range.getBegin() : Intro.DefaultLoc;
1170 for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E;
1171 PrevCaptureLoc = C->Loc, ++C) {
1172 if (C->Kind == LCK_This || C->Kind == LCK_StarThis) {
1173 if (C->Kind == LCK_StarThis)
1174 Diag(Loc: C->Loc, DiagID: !getLangOpts().CPlusPlus17
1175 ? diag::ext_star_this_lambda_capture_cxx17
1176 : diag::warn_cxx14_compat_star_this_lambda_capture);
1177
1178 // C++11 [expr.prim.lambda]p8:
1179 // An identifier or this shall not appear more than once in a
1180 // lambda-capture.
1181 if (LSI->isCXXThisCaptured()) {
1182 Diag(Loc: C->Loc, DiagID: diag::err_capture_more_than_once)
1183 << "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation())
1184 << FixItHint::CreateRemoval(
1185 RemoveRange: SourceRange(getLocForEndOfToken(Loc: PrevCaptureLoc), C->Loc));
1186 continue;
1187 }
1188
1189 // C++20 [expr.prim.lambda]p8:
1190 // If a lambda-capture includes a capture-default that is =,
1191 // each simple-capture of that lambda-capture shall be of the form
1192 // "&identifier", "this", or "* this". [ Note: The form [&,this] is
1193 // redundant but accepted for compatibility with ISO C++14. --end note ]
1194 if (Intro.Default == LCD_ByCopy && C->Kind != LCK_StarThis)
1195 Diag(Loc: C->Loc, DiagID: !getLangOpts().CPlusPlus20
1196 ? diag::ext_equals_this_lambda_capture_cxx20
1197 : diag::warn_cxx17_compat_equals_this_lambda_capture);
1198
1199 // C++11 [expr.prim.lambda]p12:
1200 // If this is captured by a local lambda expression, its nearest
1201 // enclosing function shall be a non-static member function.
1202 QualType ThisCaptureType = getCurrentThisType();
1203 if (ThisCaptureType.isNull()) {
1204 Diag(Loc: C->Loc, DiagID: diag::err_this_capture) << true;
1205 continue;
1206 }
1207
1208 CheckCXXThisCapture(Loc: C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true,
1209 /*FunctionScopeIndexToStopAtPtr*/ FunctionScopeIndexToStopAt: nullptr,
1210 ByCopy: C->Kind == LCK_StarThis);
1211 if (!LSI->Captures.empty())
1212 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1213 continue;
1214 }
1215
1216 assert(C->Id && "missing identifier for capture");
1217
1218 if (C->Init.isInvalid())
1219 continue;
1220
1221 ValueDecl *Var = nullptr;
1222 if (C->Init.isUsable()) {
1223 Diag(Loc: C->Loc, DiagID: getLangOpts().CPlusPlus14
1224 ? diag::warn_cxx11_compat_init_capture
1225 : diag::ext_init_capture);
1226
1227 // If the initializer expression is usable, but the InitCaptureType
1228 // is not, then an error has occurred - so ignore the capture for now.
1229 // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
1230 // FIXME: we should create the init capture variable and mark it invalid
1231 // in this case.
1232 if (C->InitCaptureType.get().isNull())
1233 continue;
1234
1235 if (C->Init.get()->containsUnexpandedParameterPack() &&
1236 !C->InitCaptureType.get()->getAs<PackExpansionType>())
1237 DiagnoseUnexpandedParameterPack(E: C->Init.get(), UPPC: UPPC_Initializer);
1238
1239 unsigned InitStyle;
1240 switch (C->InitKind) {
1241 case LambdaCaptureInitKind::NoInit:
1242 llvm_unreachable("not an init-capture?");
1243 case LambdaCaptureInitKind::CopyInit:
1244 InitStyle = VarDecl::CInit;
1245 break;
1246 case LambdaCaptureInitKind::DirectInit:
1247 InitStyle = VarDecl::CallInit;
1248 break;
1249 case LambdaCaptureInitKind::ListInit:
1250 InitStyle = VarDecl::ListInit;
1251 break;
1252 }
1253 Var = createLambdaInitCaptureVarDecl(Loc: C->Loc, InitCaptureType: C->InitCaptureType.get(),
1254 EllipsisLoc: C->EllipsisLoc, Id: C->Id, InitStyle,
1255 Init: C->Init.get(), DeclCtx: Method);
1256 assert(Var && "createLambdaInitCaptureVarDecl returned a null VarDecl?");
1257 if (auto *V = dyn_cast<VarDecl>(Val: Var))
1258 CheckShadow(S: CurrentScope, D: V);
1259 PushOnScopeChains(D: Var, S: CurrentScope, AddToContext: false);
1260 } else {
1261 assert(C->InitKind == LambdaCaptureInitKind::NoInit &&
1262 "init capture has valid but null init?");
1263
1264 // C++11 [expr.prim.lambda]p8:
1265 // If a lambda-capture includes a capture-default that is &, the
1266 // identifiers in the lambda-capture shall not be preceded by &.
1267 // If a lambda-capture includes a capture-default that is =, [...]
1268 // each identifier it contains shall be preceded by &.
1269 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
1270 Diag(Loc: C->Loc, DiagID: diag::err_reference_capture_with_reference_default)
1271 << FixItHint::CreateRemoval(
1272 RemoveRange: SourceRange(getLocForEndOfToken(Loc: PrevCaptureLoc), C->Loc));
1273 continue;
1274 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
1275 Diag(Loc: C->Loc, DiagID: diag::err_copy_capture_with_copy_default)
1276 << FixItHint::CreateRemoval(
1277 RemoveRange: SourceRange(getLocForEndOfToken(Loc: PrevCaptureLoc), C->Loc));
1278 continue;
1279 }
1280
1281 // C++11 [expr.prim.lambda]p10:
1282 // The identifiers in a capture-list are looked up using the usual
1283 // rules for unqualified name lookup (3.4.1)
1284 DeclarationNameInfo Name(C->Id, C->Loc);
1285 LookupResult R(*this, Name, LookupOrdinaryName);
1286 LookupName(R, S: CurScope);
1287 if (R.isAmbiguous())
1288 continue;
1289 if (R.empty()) {
1290 // FIXME: Disable corrections that would add qualification?
1291 CXXScopeSpec ScopeSpec;
1292 DeclFilterCCC<VarDecl> Validator{};
1293 if (DiagnoseEmptyLookup(S: CurScope, SS&: ScopeSpec, R, CCC&: Validator))
1294 continue;
1295 }
1296
1297 if (auto *BD = R.getAsSingle<BindingDecl>())
1298 Var = BD;
1299 else if (R.getAsSingle<FieldDecl>()) {
1300 Diag(Loc: C->Loc, DiagID: diag::err_capture_class_member_does_not_name_variable)
1301 << C->Id;
1302 continue;
1303 } else
1304 Var = R.getAsSingle<VarDecl>();
1305 if (Var && DiagnoseUseOfDecl(D: Var, Locs: C->Loc))
1306 continue;
1307 }
1308
1309 // C++11 [expr.prim.lambda]p10:
1310 // [...] each such lookup shall find a variable with automatic storage
1311 // duration declared in the reaching scope of the local lambda expression.
1312 // Note that the 'reaching scope' check happens in tryCaptureVariable().
1313 if (!Var) {
1314 Diag(Loc: C->Loc, DiagID: diag::err_capture_does_not_name_variable) << C->Id;
1315 continue;
1316 }
1317
1318 // C++11 [expr.prim.lambda]p8:
1319 // An identifier or this shall not appear more than once in a
1320 // lambda-capture.
1321 if (auto [It, Inserted] = CaptureNames.insert(KV: std::pair{C->Id, Var});
1322 !Inserted) {
1323 if (C->InitKind == LambdaCaptureInitKind::NoInit &&
1324 !Var->isInitCapture()) {
1325 Diag(Loc: C->Loc, DiagID: diag::err_capture_more_than_once)
1326 << C->Id << It->second->getBeginLoc()
1327 << FixItHint::CreateRemoval(
1328 RemoveRange: SourceRange(getLocForEndOfToken(Loc: PrevCaptureLoc), C->Loc));
1329 Var->setInvalidDecl();
1330 } else if (Var && Var->isPlaceholderVar(LangOpts: getLangOpts())) {
1331 DiagPlaceholderVariableDefinition(Loc: C->Loc);
1332 } else {
1333 // Previous capture captured something different (one or both was
1334 // an init-capture): no fixit.
1335 Diag(Loc: C->Loc, DiagID: diag::err_capture_more_than_once) << C->Id;
1336 continue;
1337 }
1338 }
1339
1340 // Ignore invalid decls; they'll just confuse the code later.
1341 if (Var->isInvalidDecl())
1342 continue;
1343
1344 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
1345
1346 if (!Underlying->hasLocalStorage()) {
1347 Diag(Loc: C->Loc, DiagID: diag::err_capture_non_automatic_variable) << C->Id;
1348 Diag(Loc: Var->getLocation(), DiagID: diag::note_previous_decl) << C->Id;
1349 continue;
1350 }
1351
1352 // C++11 [expr.prim.lambda]p23:
1353 // A capture followed by an ellipsis is a pack expansion (14.5.3).
1354 SourceLocation EllipsisLoc;
1355 if (C->EllipsisLoc.isValid()) {
1356 if (Var->isParameterPack()) {
1357 EllipsisLoc = C->EllipsisLoc;
1358 } else {
1359 Diag(Loc: C->EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
1360 << (C->Init.isUsable() ? C->Init.get()->getSourceRange()
1361 : SourceRange(C->Loc));
1362
1363 // Just ignore the ellipsis.
1364 }
1365 } else if (Var->isParameterPack()) {
1366 ContainsUnexpandedParameterPack = true;
1367 }
1368
1369 if (C->Init.isUsable()) {
1370 addInitCapture(LSI, Var: cast<VarDecl>(Val: Var), ByRef: C->Kind == LCK_ByRef);
1371 } else {
1372 TryCaptureKind Kind = C->Kind == LCK_ByRef
1373 ? TryCaptureKind::ExplicitByRef
1374 : TryCaptureKind::ExplicitByVal;
1375 tryCaptureVariable(Var, Loc: C->Loc, Kind, EllipsisLoc);
1376 }
1377 if (!LSI->Captures.empty())
1378 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1379 }
1380 finishLambdaExplicitCaptures(LSI);
1381 LSI->ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
1382 PopDeclContext();
1383}
1384
1385void Sema::ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro,
1386 SourceLocation MutableLoc) {
1387
1388 LambdaScopeInfo *LSI = getCurrentLambdaScopeUnsafe(S&: *this);
1389 LSI->Mutable = MutableLoc.isValid();
1390 ContextRAII Context(*this, LSI->CallOperator, /*NewThisContext*/ false);
1391
1392 // C++11 [expr.prim.lambda]p9:
1393 // A lambda-expression whose smallest enclosing scope is a block scope is a
1394 // local lambda expression; any other lambda expression shall not have a
1395 // capture-default or simple-capture in its lambda-introducer.
1396 //
1397 // For simple-captures, this is covered by the check below that any named
1398 // entity is a variable that can be captured.
1399 //
1400 // For DR1632, we also allow a capture-default in any context where we can
1401 // odr-use 'this' (in particular, in a default initializer for a non-static
1402 // data member).
1403 if (Intro.Default != LCD_None &&
1404 !LSI->Lambda->getParent()
1405 ->getEnclosingNonExpansionStatementContext()
1406 ->isFunctionOrMethod() &&
1407 (getCurrentThisType().isNull() ||
1408 CheckCXXThisCapture(Loc: SourceLocation(), /*Explicit=*/true,
1409 /*BuildAndDiagnose=*/false)))
1410 Diag(Loc: Intro.DefaultLoc, DiagID: diag::err_capture_default_non_local);
1411}
1412
1413void Sema::ActOnLambdaClosureParameters(
1414 Scope *LambdaScope, MutableArrayRef<DeclaratorChunk::ParamInfo> Params) {
1415 LambdaScopeInfo *LSI = getCurrentLambdaScopeUnsafe(S&: *this);
1416 PushDeclContext(S: LambdaScope, DC: LSI->CallOperator);
1417
1418 for (const DeclaratorChunk::ParamInfo &P : Params) {
1419 auto *Param = cast<ParmVarDecl>(Val: P.Param);
1420 Param->setOwningFunction(LSI->CallOperator);
1421 if (Param->getIdentifier())
1422 PushOnScopeChains(D: Param, S: LambdaScope, AddToContext: false);
1423 }
1424
1425 // After the parameter list, we may parse a noexcept/requires/trailing return
1426 // type which need to know whether the call operator constiture a dependent
1427 // context, so we need to setup the FunctionTemplateDecl of generic lambdas
1428 // now.
1429 TemplateParameterList *TemplateParams =
1430 getGenericLambdaTemplateParameterList(LSI, SemaRef&: *this);
1431 if (TemplateParams) {
1432 AddTemplateParametersToLambdaCallOperator(CallOperator: LSI->CallOperator, Class: LSI->Lambda,
1433 TemplateParams);
1434 LSI->Lambda->setLambdaIsGeneric(true);
1435 LSI->ContainsUnexpandedParameterPack |=
1436 TemplateParams->containsUnexpandedParameterPack();
1437 }
1438 LSI->AfterParameterList = true;
1439}
1440
1441void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
1442 Declarator &ParamInfo,
1443 const DeclSpec &DS) {
1444
1445 LambdaScopeInfo *LSI = getCurrentLambdaScopeUnsafe(S&: *this);
1446 LSI->CallOperator->setConstexprKind(DS.getConstexprSpecifier());
1447
1448 SmallVector<ParmVarDecl *, 8> Params;
1449 bool ExplicitResultType;
1450
1451 SourceLocation TypeLoc, CallOperatorLoc;
1452 if (ParamInfo.getNumTypeObjects() == 0) {
1453 CallOperatorLoc = TypeLoc = Intro.Range.getEnd();
1454 } else {
1455 unsigned Index;
1456 ParamInfo.isFunctionDeclarator(idx&: Index);
1457 const auto &Object = ParamInfo.getTypeObject(i: Index);
1458 TypeLoc =
1459 Object.Loc.isValid() ? Object.Loc : ParamInfo.getSourceRange().getEnd();
1460 CallOperatorLoc = ParamInfo.getSourceRange().getEnd();
1461 }
1462
1463 CXXRecordDecl *Class = LSI->Lambda;
1464 CXXMethodDecl *Method = LSI->CallOperator;
1465
1466 TypeSourceInfo *MethodTyInfo = getLambdaType(
1467 S&: *this, Intro, ParamInfo, CurScope: getCurScope(), Loc: TypeLoc, ExplicitResultType);
1468
1469 if (ParamInfo.isFunctionDeclarator() != 0) {
1470 const auto &FTI = ParamInfo.getFunctionTypeInfo();
1471 LSI->ExplicitParams = FTI.getLParenLoc().isValid();
1472 if (!FTIHasSingleVoidParameter(FTI)) {
1473 Params.reserve(N: Params.size());
1474 for (unsigned I = 0; I < FTI.NumParams; ++I) {
1475 auto *Param = cast<ParmVarDecl>(Val: FTI.Params[I].Param);
1476 Param->setScopeInfo(scopeDepth: 0, parameterIndex: Params.size());
1477 Params.push_back(Elt: Param);
1478 }
1479 }
1480 }
1481
1482 bool IsLambdaStatic =
1483 ParamInfo.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static;
1484
1485 CompleteLambdaCallOperator(
1486 Method, LambdaLoc: Intro.Range.getBegin(), CallOperatorLoc,
1487 TrailingRequiresClause: AssociatedConstraint(ParamInfo.getTrailingRequiresClause()), MethodTyInfo,
1488 ConstexprKind: ParamInfo.getDeclSpec().getConstexprSpecifier(),
1489 SC: IsLambdaStatic ? SC_Static : SC_None, Params, HasExplicitResultType: ExplicitResultType);
1490
1491 CheckCXXDefaultArguments(FD: Method);
1492
1493 // This represents the function body for the lambda function, check if we
1494 // have to apply optnone due to a pragma.
1495 AddRangeBasedOptnone(FD: Method);
1496
1497 // code_seg attribute on lambda apply to the method.
1498 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(
1499 FD: Method, /*IsDefinition=*/true))
1500 Method->addAttr(A);
1501
1502 // Attributes on the lambda apply to the method.
1503 ProcessDeclAttributes(S: CurScope, D: Method, PD: ParamInfo);
1504
1505 if (Context.getTargetInfo().getTriple().isAArch64())
1506 ARM().CheckSMEFunctionDefAttributes(FD: Method);
1507
1508 // CUDA lambdas get implicit host and device attributes.
1509 if (getLangOpts().CUDA)
1510 CUDA().SetLambdaAttrs(Method);
1511
1512 // OpenMP lambdas might get assumumption attributes.
1513 if (LangOpts.OpenMP)
1514 OpenMP().ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(D: Method);
1515
1516 handleLambdaNumbering(Class, Method);
1517
1518 for (auto &&C : LSI->Captures) {
1519 if (!C.isVariableCapture())
1520 continue;
1521 ValueDecl *Var = C.getVariable();
1522 if (Var && Var->isInitCapture()) {
1523 PushOnScopeChains(D: Var, S: CurScope, AddToContext: false);
1524 }
1525 }
1526
1527 auto CheckRedefinition = [&](ParmVarDecl *Param) {
1528 for (const auto &Capture : Intro.Captures) {
1529 if (Capture.Id == Param->getIdentifier()) {
1530 Diag(Loc: Param->getLocation(), DiagID: diag::err_parameter_shadow_capture);
1531 Diag(Loc: Capture.Loc, DiagID: diag::note_var_explicitly_captured_here)
1532 << Capture.Id << true;
1533 return false;
1534 }
1535 }
1536 return true;
1537 };
1538
1539 for (ParmVarDecl *P : Params) {
1540 if (!P->getIdentifier())
1541 continue;
1542 if (CheckRedefinition(P))
1543 CheckShadow(S: CurScope, D: P);
1544 PushOnScopeChains(D: P, S: CurScope);
1545 }
1546
1547 // C++23 [expr.prim.lambda.capture]p5:
1548 // If an identifier in a capture appears as the declarator-id of a parameter
1549 // of the lambda-declarator's parameter-declaration-clause or as the name of a
1550 // template parameter of the lambda-expression's template-parameter-list, the
1551 // program is ill-formed.
1552 TemplateParameterList *TemplateParams =
1553 getGenericLambdaTemplateParameterList(LSI, SemaRef&: *this);
1554 if (TemplateParams) {
1555 for (const auto *TP : TemplateParams->asArray()) {
1556 if (!TP->getIdentifier())
1557 continue;
1558 for (const auto &Capture : Intro.Captures) {
1559 if (Capture.Id == TP->getIdentifier()) {
1560 Diag(Loc: Capture.Loc, DiagID: diag::err_template_param_shadow) << Capture.Id;
1561 NoteTemplateParameterLocation(Decl: *TP);
1562 }
1563 }
1564 }
1565 }
1566
1567 // C++20: dcl.decl.general p4:
1568 // The optional requires-clause ([temp.pre]) in an init-declarator or
1569 // member-declarator shall be present only if the declarator declares a
1570 // templated function ([dcl.fct]).
1571 if (const AssociatedConstraint &TRC = Method->getTrailingRequiresClause()) {
1572 // [temp.pre]/8:
1573 // An entity is templated if it is
1574 // - a template,
1575 // - an entity defined ([basic.def]) or created ([class.temporary]) in a
1576 // templated entity,
1577 // - a member of a templated entity,
1578 // - an enumerator for an enumeration that is a templated entity, or
1579 // - the closure type of a lambda-expression ([expr.prim.lambda.closure])
1580 // appearing in the declaration of a templated entity. [Note 6: A local
1581 // class, a local or block variable, or a friend function defined in a
1582 // templated entity is a templated entity. — end note]
1583 //
1584 // A templated function is a function template or a function that is
1585 // templated. A templated class is a class template or a class that is
1586 // templated. A templated variable is a variable template or a variable
1587 // that is templated.
1588
1589 // Note: we only have to check if this is defined in a template entity, OR
1590 // if we are a template, since the rest don't apply. The requires clause
1591 // applies to the call operator, which we already know is a member function,
1592 // AND defined.
1593 if (!Method->getDescribedFunctionTemplate() && !Method->isTemplated()) {
1594 Diag(Loc: TRC.ConstraintExpr->getBeginLoc(),
1595 DiagID: diag::err_constrained_non_templated_function);
1596 }
1597 }
1598
1599 // Enter a new evaluation context to insulate the lambda from any
1600 // cleanups from the enclosing full-expression.
1601 PushExpressionEvaluationContextForFunction(
1602 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated, FD: LSI->CallOperator);
1603}
1604
1605void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
1606 bool IsInstantiation) {
1607 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: FunctionScopes.back());
1608
1609 // Leave the expression-evaluation context.
1610 DiscardCleanupsInEvaluationContext();
1611 PopExpressionEvaluationContext();
1612
1613 // Leave the context of the lambda.
1614 if (!IsInstantiation)
1615 PopDeclContext();
1616
1617 // Finalize the lambda.
1618 CXXRecordDecl *Class = LSI->Lambda;
1619 Class->setInvalidDecl();
1620 SmallVector<Decl*, 4> Fields(Class->fields());
1621 ActOnFields(S: nullptr, RecLoc: Class->getLocation(), TagDecl: Class, Fields, LBrac: SourceLocation(),
1622 RBrac: SourceLocation(), AttrList: ParsedAttributesView());
1623 CheckCompletedCXXClass(S: nullptr, Record: Class);
1624
1625 PopFunctionScopeInfo();
1626}
1627
1628template <typename Func>
1629static void repeatForLambdaConversionFunctionCallingConvs(
1630 Sema &S, const FunctionProtoType &CallOpProto, Func F) {
1631 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
1632 IsVariadic: CallOpProto.isVariadic(), /*IsCXXMethod=*/false);
1633 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
1634 IsVariadic: CallOpProto.isVariadic(), /*IsCXXMethod=*/true);
1635 CallingConv CallOpCC = CallOpProto.getCallConv();
1636
1637 /// Implement emitting a version of the operator for many of the calling
1638 /// conventions for MSVC, as described here:
1639 /// https://devblogs.microsoft.com/oldnewthing/20150220-00/?p=44623.
1640 /// Experimentally, we determined that cdecl, stdcall, fastcall, and
1641 /// vectorcall are generated by MSVC when it is supported by the target.
1642 /// Additionally, we are ensuring that the default-free/default-member and
1643 /// call-operator calling convention are generated as well.
1644 /// NOTE: We intentionally generate a 'thiscall' on Win32 implicitly from the
1645 /// 'member default', despite MSVC not doing so. We do this in order to ensure
1646 /// that someone who intentionally places 'thiscall' on the lambda call
1647 /// operator will still get that overload, since we don't have the a way of
1648 /// detecting the attribute by the time we get here.
1649 if (S.getLangOpts().MSVCCompat) {
1650 CallingConv Convs[] = {
1651 CC_C, CC_X86StdCall, CC_X86FastCall, CC_X86VectorCall,
1652 DefaultFree, DefaultMember, CallOpCC};
1653 llvm::sort(C&: Convs);
1654 llvm::iterator_range<CallingConv *> Range(std::begin(arr&: Convs),
1655 llvm::unique(R&: Convs));
1656 const TargetInfo &TI = S.getASTContext().getTargetInfo();
1657
1658 for (CallingConv C : Range) {
1659 if (TI.checkCallingConvention(CC: C) == TargetInfo::CCCR_OK)
1660 F(C);
1661 }
1662 return;
1663 }
1664
1665 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree) {
1666 F(DefaultFree);
1667 F(DefaultMember);
1668 } else {
1669 F(CallOpCC);
1670 }
1671}
1672
1673// Returns the 'standard' calling convention to be used for the lambda
1674// conversion function, that is, the 'free' function calling convention unless
1675// it is overridden by a non-default calling convention attribute.
1676static CallingConv
1677getLambdaConversionFunctionCallConv(Sema &S,
1678 const FunctionProtoType *CallOpProto) {
1679 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
1680 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
1681 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
1682 IsVariadic: CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
1683 CallingConv CallOpCC = CallOpProto->getCallConv();
1684
1685 // If the call-operator hasn't been changed, return both the 'free' and
1686 // 'member' function calling convention.
1687 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree)
1688 return DefaultFree;
1689 return CallOpCC;
1690}
1691
1692QualType Sema::getLambdaConversionFunctionResultType(
1693 const FunctionProtoType *CallOpProto, CallingConv CC) {
1694 const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
1695 CallOpProto->getExtProtoInfo();
1696 FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
1697 InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(cc: CC);
1698 InvokerExtInfo.TypeQuals = Qualifiers();
1699 assert(InvokerExtInfo.RefQualifier == RQ_None &&
1700 "Lambda's call operator should not have a reference qualifier");
1701 return Context.getFunctionType(ResultTy: CallOpProto->getReturnType(),
1702 Args: CallOpProto->getParamTypes(), EPI: InvokerExtInfo);
1703}
1704
1705/// Add a lambda's conversion to function pointer, as described in
1706/// C++11 [expr.prim.lambda]p6.
1707static void addFunctionPointerConversion(Sema &S, SourceRange IntroducerRange,
1708 CXXRecordDecl *Class,
1709 CXXMethodDecl *CallOperator,
1710 QualType InvokerFunctionTy) {
1711 // This conversion is explicitly disabled if the lambda's function has
1712 // pass_object_size attributes on any of its parameters.
1713 auto HasPassObjectSizeAttr = [](const ParmVarDecl *P) {
1714 return P->hasAttr<PassObjectSizeAttr>();
1715 };
1716 if (llvm::any_of(Range: CallOperator->parameters(), P: HasPassObjectSizeAttr))
1717 return;
1718
1719 // Add the conversion to function pointer.
1720 QualType PtrToFunctionTy = S.Context.getPointerType(T: InvokerFunctionTy);
1721
1722 // Create the type of the conversion function.
1723 FunctionProtoType::ExtProtoInfo ConvExtInfo(
1724 S.Context.getDefaultCallingConvention(
1725 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1726 // The conversion function is always const and noexcept.
1727 ConvExtInfo.TypeQuals = Qualifiers();
1728 ConvExtInfo.TypeQuals.addConst();
1729 ConvExtInfo.ExceptionSpec.Type = EST_BasicNoexcept;
1730 QualType ConvTy = S.Context.getFunctionType(ResultTy: PtrToFunctionTy, Args: {}, EPI: ConvExtInfo);
1731
1732 SourceLocation Loc = IntroducerRange.getBegin();
1733 DeclarationName ConversionName
1734 = S.Context.DeclarationNames.getCXXConversionFunctionName(
1735 Ty: S.Context.getCanonicalType(T: PtrToFunctionTy));
1736 // Construct a TypeSourceInfo for the conversion function, and wire
1737 // all the parameters appropriately for the FunctionProtoTypeLoc
1738 // so that everything works during transformation/instantiation of
1739 // generic lambdas.
1740 // The main reason for wiring up the parameters of the conversion
1741 // function with that of the call operator is so that constructs
1742 // like the following work:
1743 // auto L = [](auto b) { <-- 1
1744 // return [](auto a) -> decltype(a) { <-- 2
1745 // return a;
1746 // };
1747 // };
1748 // int (*fp)(int) = L(5);
1749 // Because the trailing return type can contain DeclRefExprs that refer
1750 // to the original call operator's variables, we hijack the call
1751 // operators ParmVarDecls below.
1752 TypeSourceInfo *ConvNamePtrToFunctionTSI =
1753 S.Context.getTrivialTypeSourceInfo(T: PtrToFunctionTy, Loc);
1754 DeclarationNameLoc ConvNameLoc =
1755 DeclarationNameLoc::makeNamedTypeLoc(TInfo: ConvNamePtrToFunctionTSI);
1756
1757 // The conversion function is a conversion to a pointer-to-function.
1758 TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(T: ConvTy, Loc);
1759 FunctionProtoTypeLoc ConvTL =
1760 ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
1761 // Get the result of the conversion function which is a pointer-to-function.
1762 PointerTypeLoc PtrToFunctionTL =
1763 ConvTL.getReturnLoc().getAs<PointerTypeLoc>();
1764 // Do the same for the TypeSourceInfo that is used to name the conversion
1765 // operator.
1766 PointerTypeLoc ConvNamePtrToFunctionTL =
1767 ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
1768
1769 // Get the underlying function types that the conversion function will
1770 // be converting to (should match the type of the call operator).
1771 FunctionProtoTypeLoc CallOpConvTL =
1772 PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1773 FunctionProtoTypeLoc CallOpConvNameTL =
1774 ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1775
1776 // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
1777 // These parameter's are essentially used to transform the name and
1778 // the type of the conversion operator. By using the same parameters
1779 // as the call operator's we don't have to fix any back references that
1780 // the trailing return type of the call operator's uses (such as
1781 // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
1782 // - we can simply use the return type of the call operator, and
1783 // everything should work.
1784 SmallVector<ParmVarDecl *, 4> InvokerParams;
1785 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1786 ParmVarDecl *From = CallOperator->getParamDecl(i: I);
1787
1788 InvokerParams.push_back(Elt: ParmVarDecl::Create(
1789 C&: S.Context,
1790 // Temporarily add to the TU. This is set to the invoker below.
1791 DC: S.Context.getTranslationUnitDecl(), StartLoc: From->getBeginLoc(),
1792 IdLoc: From->getLocation(), Id: From->getIdentifier(), T: From->getType(),
1793 TInfo: From->getTypeSourceInfo(), S: From->getStorageClass(),
1794 /*DefArg=*/nullptr));
1795 CallOpConvTL.setParam(i: I, VD: From);
1796 CallOpConvNameTL.setParam(i: I, VD: From);
1797 }
1798
1799 CXXConversionDecl *Conversion = CXXConversionDecl::Create(
1800 C&: S.Context, RD: Class, StartLoc: Loc,
1801 NameInfo: DeclarationNameInfo(ConversionName, Loc, ConvNameLoc), T: ConvTy, TInfo: ConvTSI,
1802 UsesFPIntrin: S.getCurFPFeatures().isFPConstrained(),
1803 /*isInline=*/true, ES: ExplicitSpecifier(),
1804 ConstexprKind: S.getLangOpts().CPlusPlus17 ? ConstexprSpecKind::Constexpr
1805 : ConstexprSpecKind::Unspecified,
1806 EndLocation: CallOperator->getBody()->getEndLoc());
1807 Conversion->setAccess(AS_public);
1808 Conversion->setImplicit(true);
1809
1810 // A non-generic lambda may still be a templated entity. We need to preserve
1811 // constraints when converting the lambda to a function pointer. See GH63181.
1812 if (const AssociatedConstraint &Requires =
1813 CallOperator->getTrailingRequiresClause())
1814 Conversion->setTrailingRequiresClause(Requires);
1815
1816 if (Class->isGenericLambda()) {
1817 // Create a template version of the conversion operator, using the template
1818 // parameter list of the function call operator.
1819 FunctionTemplateDecl *TemplateCallOperator =
1820 CallOperator->getDescribedFunctionTemplate();
1821 FunctionTemplateDecl *ConversionTemplate =
1822 FunctionTemplateDecl::Create(C&: S.Context, DC: Class,
1823 L: Loc, Name: ConversionName,
1824 Params: TemplateCallOperator->getTemplateParameters(),
1825 Decl: Conversion);
1826 ConversionTemplate->setAccess(AS_public);
1827 ConversionTemplate->setImplicit(true);
1828 Conversion->setDescribedFunctionTemplate(ConversionTemplate);
1829 Class->addDecl(D: ConversionTemplate);
1830 } else
1831 Class->addDecl(D: Conversion);
1832
1833 // If the lambda is not static, we need to add a static member
1834 // function that will be the result of the conversion with a
1835 // certain unique ID.
1836 // When it is static we just return the static call operator instead.
1837 if (CallOperator->isImplicitObjectMemberFunction()) {
1838 DeclarationName InvokerName =
1839 &S.Context.Idents.get(Name: getLambdaStaticInvokerName());
1840 // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
1841 // we should get a prebuilt TrivialTypeSourceInfo from Context
1842 // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
1843 // then rewire the parameters accordingly, by hoisting up the InvokeParams
1844 // loop below and then use its Params to set Invoke->setParams(...) below.
1845 // This would avoid the 'const' qualifier of the calloperator from
1846 // contaminating the type of the invoker, which is currently adjusted
1847 // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the
1848 // trailing return type of the invoker would require a visitor to rebuild
1849 // the trailing return type and adjusting all back DeclRefExpr's to refer
1850 // to the new static invoker parameters - not the call operator's.
1851 CXXMethodDecl *Invoke = CXXMethodDecl::Create(
1852 C&: S.Context, RD: Class, StartLoc: Loc, NameInfo: DeclarationNameInfo(InvokerName, Loc),
1853 T: InvokerFunctionTy, TInfo: CallOperator->getTypeSourceInfo(), SC: SC_Static,
1854 UsesFPIntrin: S.getCurFPFeatures().isFPConstrained(),
1855 /*isInline=*/true, ConstexprKind: CallOperator->getConstexprKind(),
1856 EndLocation: CallOperator->getBody()->getEndLoc());
1857 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
1858 InvokerParams[I]->setOwningFunction(Invoke);
1859 Invoke->setParams(InvokerParams);
1860 Invoke->setAccess(AS_private);
1861 Invoke->setImplicit(true);
1862 if (Class->isGenericLambda()) {
1863 FunctionTemplateDecl *TemplateCallOperator =
1864 CallOperator->getDescribedFunctionTemplate();
1865 FunctionTemplateDecl *StaticInvokerTemplate =
1866 FunctionTemplateDecl::Create(
1867 C&: S.Context, DC: Class, L: Loc, Name: InvokerName,
1868 Params: TemplateCallOperator->getTemplateParameters(), Decl: Invoke);
1869 StaticInvokerTemplate->setAccess(AS_private);
1870 StaticInvokerTemplate->setImplicit(true);
1871 Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
1872 Class->addDecl(D: StaticInvokerTemplate);
1873 } else
1874 Class->addDecl(D: Invoke);
1875 }
1876}
1877
1878/// Add a lambda's conversion to function pointers, as described in
1879/// C++11 [expr.prim.lambda]p6. Note that in most cases, this should emit only a
1880/// single pointer conversion. In the event that the default calling convention
1881/// for free and member functions is different, it will emit both conventions.
1882static void addFunctionPointerConversions(Sema &S, SourceRange IntroducerRange,
1883 CXXRecordDecl *Class,
1884 CXXMethodDecl *CallOperator) {
1885 const FunctionProtoType *CallOpProto =
1886 CallOperator->getType()->castAs<FunctionProtoType>();
1887
1888 repeatForLambdaConversionFunctionCallingConvs(
1889 S, CallOpProto: *CallOpProto, F: [&](CallingConv CC) {
1890 QualType InvokerFunctionTy =
1891 S.getLambdaConversionFunctionResultType(CallOpProto, CC);
1892 addFunctionPointerConversion(S, IntroducerRange, Class, CallOperator,
1893 InvokerFunctionTy);
1894 });
1895}
1896
1897/// Add a lambda's conversion to block pointer.
1898static void addBlockPointerConversion(Sema &S,
1899 SourceRange IntroducerRange,
1900 CXXRecordDecl *Class,
1901 CXXMethodDecl *CallOperator) {
1902 const FunctionProtoType *CallOpProto =
1903 CallOperator->getType()->castAs<FunctionProtoType>();
1904 QualType FunctionTy = S.getLambdaConversionFunctionResultType(
1905 CallOpProto, CC: getLambdaConversionFunctionCallConv(S, CallOpProto));
1906 QualType BlockPtrTy = S.Context.getBlockPointerType(T: FunctionTy);
1907
1908 FunctionProtoType::ExtProtoInfo ConversionEPI(
1909 S.Context.getDefaultCallingConvention(
1910 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1911 ConversionEPI.TypeQuals = Qualifiers();
1912 ConversionEPI.TypeQuals.addConst();
1913 QualType ConvTy = S.Context.getFunctionType(ResultTy: BlockPtrTy, Args: {}, EPI: ConversionEPI);
1914
1915 SourceLocation Loc = IntroducerRange.getBegin();
1916 DeclarationName Name
1917 = S.Context.DeclarationNames.getCXXConversionFunctionName(
1918 Ty: S.Context.getCanonicalType(T: BlockPtrTy));
1919 DeclarationNameLoc NameLoc = DeclarationNameLoc::makeNamedTypeLoc(
1920 TInfo: S.Context.getTrivialTypeSourceInfo(T: BlockPtrTy, Loc));
1921 CXXConversionDecl *Conversion = CXXConversionDecl::Create(
1922 C&: S.Context, RD: Class, StartLoc: Loc, NameInfo: DeclarationNameInfo(Name, Loc, NameLoc), T: ConvTy,
1923 TInfo: S.Context.getTrivialTypeSourceInfo(T: ConvTy, Loc),
1924 UsesFPIntrin: S.getCurFPFeatures().isFPConstrained(),
1925 /*isInline=*/true, ES: ExplicitSpecifier(), ConstexprKind: ConstexprSpecKind::Unspecified,
1926 EndLocation: CallOperator->getBody()->getEndLoc());
1927 Conversion->setAccess(AS_public);
1928 Conversion->setImplicit(true);
1929 Class->addDecl(D: Conversion);
1930}
1931
1932ExprResult Sema::BuildCaptureInit(const Capture &Cap,
1933 SourceLocation ImplicitCaptureLoc,
1934 bool IsOpenMPMapping) {
1935 // VLA captures don't have a stored initialization expression.
1936 if (Cap.isVLATypeCapture())
1937 return ExprResult();
1938
1939 // An init-capture is initialized directly from its stored initializer.
1940 if (Cap.isInitCapture())
1941 return cast<VarDecl>(Val: Cap.getVariable())->getInit();
1942
1943 // For anything else, build an initialization expression. For an implicit
1944 // capture, the capture notionally happens at the capture-default, so use
1945 // that location here.
1946 SourceLocation Loc =
1947 ImplicitCaptureLoc.isValid() ? ImplicitCaptureLoc : Cap.getLocation();
1948
1949 // C++11 [expr.prim.lambda]p21:
1950 // When the lambda-expression is evaluated, the entities that
1951 // are captured by copy are used to direct-initialize each
1952 // corresponding non-static data member of the resulting closure
1953 // object. (For array members, the array elements are
1954 // direct-initialized in increasing subscript order.) These
1955 // initializations are performed in the (unspecified) order in
1956 // which the non-static data members are declared.
1957
1958 // C++ [expr.prim.lambda]p12:
1959 // An entity captured by a lambda-expression is odr-used (3.2) in
1960 // the scope containing the lambda-expression.
1961 ExprResult Init;
1962 IdentifierInfo *Name = nullptr;
1963 if (Cap.isThisCapture()) {
1964 QualType ThisTy = getCurrentThisType();
1965 Expr *This = BuildCXXThisExpr(Loc, Type: ThisTy, IsImplicit: ImplicitCaptureLoc.isValid());
1966 if (Cap.isCopyCapture())
1967 Init = CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_Deref, InputExpr: This);
1968 else
1969 Init = This;
1970 } else {
1971 assert(Cap.isVariableCapture() && "unknown kind of capture");
1972 ValueDecl *Var = Cap.getVariable();
1973 Name = Var->getIdentifier();
1974 Init = BuildDeclarationNameExpr(
1975 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(Var->getDeclName(), Loc), D: Var);
1976 }
1977
1978 // In OpenMP, the capture kind doesn't actually describe how to capture:
1979 // variables are "mapped" onto the device in a process that does not formally
1980 // make a copy, even for a "copy capture".
1981 if (IsOpenMPMapping)
1982 return Init;
1983
1984 if (Init.isInvalid())
1985 return ExprError();
1986
1987 Expr *InitExpr = Init.get();
1988 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
1989 VarID: Name, FieldType: Cap.getCaptureType(), Loc);
1990 InitializationKind InitKind =
1991 InitializationKind::CreateDirect(InitLoc: Loc, LParenLoc: Loc, RParenLoc: Loc);
1992 InitializationSequence InitSeq(*this, Entity, InitKind, InitExpr);
1993 return InitSeq.Perform(S&: *this, Entity, Kind: InitKind, Args: InitExpr);
1994}
1995
1996ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body) {
1997 LambdaScopeInfo &LSI = *cast<LambdaScopeInfo>(Val: FunctionScopes.back());
1998
1999 if (LSI.CallOperator->hasAttr<SYCLKernelEntryPointAttr>())
2000 SYCL().CheckSYCLEntryPointFunctionDecl(FD: LSI.CallOperator);
2001
2002 ActOnFinishFunctionBody(Decl: LSI.CallOperator, Body, /*IsInstantiation=*/false,
2003 /*RetainFunctionScopeInfo=*/true);
2004
2005 return BuildLambdaExpr(StartLoc, EndLoc: Body->getEndLoc());
2006}
2007
2008static LambdaCaptureDefault
2009mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS) {
2010 switch (ICS) {
2011 case CapturingScopeInfo::ImpCap_None:
2012 return LCD_None;
2013 case CapturingScopeInfo::ImpCap_LambdaByval:
2014 return LCD_ByCopy;
2015 case CapturingScopeInfo::ImpCap_CapturedRegion:
2016 case CapturingScopeInfo::ImpCap_LambdaByref:
2017 return LCD_ByRef;
2018 case CapturingScopeInfo::ImpCap_Block:
2019 llvm_unreachable("block capture in lambda");
2020 }
2021 llvm_unreachable("Unknown implicit capture style");
2022}
2023
2024bool Sema::CaptureHasSideEffects(const Capture &From) {
2025 if (From.isInitCapture()) {
2026 Expr *Init = cast<VarDecl>(Val: From.getVariable())->getInit();
2027 if (Init && Init->HasSideEffects(Ctx: Context))
2028 return true;
2029 }
2030
2031 if (!From.isCopyCapture())
2032 return false;
2033
2034 const QualType T = From.isThisCapture()
2035 ? getCurrentThisType()->getPointeeType()
2036 : From.getCaptureType();
2037
2038 if (T.isVolatileQualified())
2039 return true;
2040
2041 const Type *BaseT = T->getBaseElementTypeUnsafe();
2042 if (const CXXRecordDecl *RD = BaseT->getAsCXXRecordDecl())
2043 return !RD->isCompleteDefinition() || !RD->hasTrivialCopyConstructor() ||
2044 !RD->hasTrivialDestructor();
2045
2046 return false;
2047}
2048
2049bool Sema::DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
2050 SourceRange FixItRange,
2051 const Capture &From) {
2052 if (CaptureHasSideEffects(From))
2053 return false;
2054
2055 if (From.isVLATypeCapture())
2056 return false;
2057
2058 // FIXME: maybe we should warn on these if we can find a sensible diagnostic
2059 // message
2060 if (From.isInitCapture() &&
2061 From.getVariable()->isPlaceholderVar(LangOpts: getLangOpts()))
2062 return false;
2063
2064 auto diag = Diag(Loc: From.getLocation(), DiagID: diag::warn_unused_lambda_capture);
2065 if (From.isThisCapture())
2066 diag << "'this'";
2067 else
2068 diag << From.getVariable();
2069 diag << From.isNonODRUsed();
2070 // If we were able to resolve the fixit range we'll create a fixit,
2071 // otherwise we just use the raw capture range for the diagnostic.
2072 if (FixItRange.isValid())
2073 diag << FixItHint::CreateRemoval(RemoveRange: FixItRange);
2074 else
2075 diag << CaptureRange;
2076 return true;
2077}
2078
2079/// Create a field within the lambda class or captured statement record for the
2080/// given capture.
2081FieldDecl *Sema::BuildCaptureField(RecordDecl *RD,
2082 const sema::Capture &Capture) {
2083 SourceLocation Loc = Capture.getLocation();
2084 QualType FieldType = Capture.getCaptureType();
2085
2086 TypeSourceInfo *TSI = nullptr;
2087 if (Capture.isVariableCapture()) {
2088 const auto *Var = dyn_cast_or_null<VarDecl>(Val: Capture.getVariable());
2089 if (Var && Var->isInitCapture())
2090 TSI = Var->getTypeSourceInfo();
2091 }
2092
2093 // FIXME: Should we really be doing this? A null TypeSourceInfo seems more
2094 // appropriate, at least for an implicit capture.
2095 if (!TSI)
2096 TSI = Context.getTrivialTypeSourceInfo(T: FieldType, Loc);
2097
2098 // Build the non-static data member.
2099 FieldDecl *Field =
2100 FieldDecl::Create(C: Context, DC: RD, /*StartLoc=*/Loc, /*IdLoc=*/Loc,
2101 /*Id=*/nullptr, T: FieldType, TInfo: TSI, /*BW=*/nullptr,
2102 /*Mutable=*/false, InitStyle: ICIS_NoInit);
2103 // If the variable being captured has an invalid type, mark the class as
2104 // invalid as well.
2105 if (!FieldType->isDependentType()) {
2106 if (RequireCompleteSizedType(Loc, T: FieldType,
2107 DiagID: diag::err_field_incomplete_or_sizeless)) {
2108 RD->setInvalidDecl();
2109 Field->setInvalidDecl();
2110 } else {
2111 NamedDecl *Def;
2112 FieldType->isIncompleteType(Def: &Def);
2113 if (Def && Def->isInvalidDecl()) {
2114 RD->setInvalidDecl();
2115 Field->setInvalidDecl();
2116 }
2117 }
2118 }
2119 Field->setImplicit(true);
2120 Field->setAccess(AS_private);
2121 RD->addDecl(D: Field);
2122
2123 if (Capture.isVLATypeCapture())
2124 Field->setCapturedVLAType(Capture.getCapturedVLAType());
2125
2126 return Field;
2127}
2128
2129static SourceRange
2130ConstructFixItRangeForUnusedCapture(Sema &S, SourceRange CaptureRange,
2131 SourceLocation PrevCaptureLoc,
2132 bool CurHasPreviousCapture, bool IsLast) {
2133 if (!CaptureRange.isValid())
2134 return SourceRange();
2135
2136 auto GetTrailingEndLocation = [&](SourceLocation StartPoint) {
2137 SourceRange NextToken = S.getRangeForNextToken(
2138 Loc: StartPoint, /*IncludeMacros=*/false, /*IncludeComments=*/true);
2139 if (!NextToken.isValid())
2140 return SourceLocation();
2141 // Return the last location preceding the next token
2142 return NextToken.getBegin().getLocWithOffset(Offset: -1);
2143 };
2144
2145 if (!CurHasPreviousCapture && !IsLast) {
2146 // If there are no captures preceding this capture, remove the
2147 // trailing comma and anything up to the next token
2148 SourceRange CommaRange =
2149 S.getRangeForNextToken(Loc: CaptureRange.getEnd(), /*IncludeMacros=*/false,
2150 /*IncludeComments=*/false, ExpectedToken: tok::comma);
2151 SourceLocation FixItEnd = GetTrailingEndLocation(CommaRange.getBegin());
2152 return SourceRange(CaptureRange.getBegin(), FixItEnd);
2153 }
2154
2155 // Otherwise, remove the comma since the last used capture, and
2156 // anything up to the next token
2157 SourceLocation FixItStart = S.getLocForEndOfToken(Loc: PrevCaptureLoc);
2158 SourceLocation FixItEnd = GetTrailingEndLocation(CaptureRange.getEnd());
2159 return SourceRange(FixItStart, FixItEnd);
2160}
2161
2162ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc,
2163 SourceLocation EndLoc) {
2164 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(Val: FunctionScopes.back());
2165 // Collect information from the lambda scope.
2166 SmallVector<LambdaCapture, 4> Captures;
2167 SmallVector<Expr *, 4> CaptureInits;
2168 SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc;
2169 LambdaCaptureDefault CaptureDefault =
2170 mapImplicitCaptureStyle(ICS: LSI->ImpCaptureStyle);
2171 CXXRecordDecl *Class = LSI->Lambda;
2172 CXXMethodDecl *CallOperator = LSI->CallOperator;
2173 SourceRange IntroducerRange = LSI->IntroducerRange;
2174 bool ExplicitParams = LSI->ExplicitParams;
2175 bool ExplicitResultType = !LSI->HasImplicitReturnType;
2176 CleanupInfo LambdaCleanup = LSI->Cleanup;
2177 bool ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
2178 bool IsGenericLambda = Class->isGenericLambda();
2179
2180 CallOperator->setLexicalDeclContext(Class);
2181 Decl *TemplateOrNonTemplateCallOperatorDecl =
2182 CallOperator->getDescribedFunctionTemplate()
2183 ? CallOperator->getDescribedFunctionTemplate()
2184 : cast<Decl>(Val: CallOperator);
2185
2186 // FIXME: Is this really the best choice? Keeping the lexical decl context
2187 // set as CurContext seems more faithful to the source.
2188 TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
2189
2190 {
2191 // TreeTransform of immediate functions may call getCurLambda, which
2192 // requires both the paired LSI and the lambda DeclContext.
2193 ContextRAII SavedContext(*this, CallOperator, /*NewThisContext=*/false);
2194 PopExpressionEvaluationContext();
2195 }
2196
2197 sema::AnalysisBasedWarnings::Policy WP =
2198 AnalysisWarnings.getPolicyInEffectAt(Loc: EndLoc);
2199 // We cannot release LSI until we finish computing captures, which
2200 // requires the scope to be popped.
2201 Sema::PoppedFunctionScopePtr _ = PopFunctionScopeInfo(WP: &WP, D: LSI->CallOperator);
2202
2203 // True if the current capture has a used capture or default before it.
2204 bool CurHasPreviousCapture = CaptureDefault != LCD_None;
2205 SourceLocation PrevCaptureLoc =
2206 CurHasPreviousCapture ? CaptureDefaultLoc : IntroducerRange.getBegin();
2207
2208 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
2209 const Capture &From = LSI->Captures[I];
2210
2211 if (From.isInvalid())
2212 return ExprError();
2213
2214 assert(!From.isBlockCapture() && "Cannot capture __block variables");
2215 bool IsImplicit = I >= LSI->NumExplicitCaptures;
2216 SourceLocation ImplicitCaptureLoc =
2217 IsImplicit ? CaptureDefaultLoc : SourceLocation();
2218
2219 // Use source ranges of explicit captures for fixits where available.
2220 SourceRange CaptureRange = LSI->ExplicitCaptureRanges[I];
2221
2222 // Warn about unused explicit captures.
2223 bool IsCaptureUsed = true;
2224 if (!CurContext->isDependentContext() && !IsImplicit && !From.isODRUsed()) {
2225 // Initialized captures that are non-ODR used may not be eliminated.
2226 // FIXME: Where did the IsGenericLambda here come from?
2227 bool NonODRUsedInitCapture =
2228 IsGenericLambda && From.isNonODRUsed() && From.isInitCapture();
2229 if (!NonODRUsedInitCapture) {
2230 bool IsLast = (I + 1) == LSI->NumExplicitCaptures;
2231 SourceRange FixItRange = ConstructFixItRangeForUnusedCapture(
2232 S&: *this, CaptureRange, PrevCaptureLoc, CurHasPreviousCapture, IsLast);
2233 IsCaptureUsed =
2234 !DiagnoseUnusedLambdaCapture(CaptureRange, FixItRange, From);
2235 }
2236 }
2237
2238 if (CaptureRange.isValid()) {
2239 CurHasPreviousCapture |= IsCaptureUsed;
2240 PrevCaptureLoc = CaptureRange.getEnd();
2241 }
2242
2243 // Map the capture to our AST representation.
2244 LambdaCapture Capture = [&] {
2245 if (From.isThisCapture()) {
2246 // Capturing 'this' implicitly with a default of '[=]' is deprecated,
2247 // because it results in a reference capture. Don't warn prior to
2248 // C++2a; there's nothing that can be done about it before then.
2249 if (getLangOpts().CPlusPlus20 && IsImplicit &&
2250 CaptureDefault == LCD_ByCopy) {
2251 Diag(Loc: From.getLocation(), DiagID: diag::warn_deprecated_this_capture);
2252 Diag(Loc: CaptureDefaultLoc, DiagID: diag::note_deprecated_this_capture)
2253 << FixItHint::CreateInsertion(
2254 InsertionLoc: getLocForEndOfToken(Loc: CaptureDefaultLoc), Code: ", this");
2255 }
2256 return LambdaCapture(From.getLocation(), IsImplicit,
2257 From.isCopyCapture() ? LCK_StarThis : LCK_This);
2258 } else if (From.isVLATypeCapture()) {
2259 return LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType);
2260 } else {
2261 assert(From.isVariableCapture() && "unknown kind of capture");
2262 ValueDecl *Var = From.getVariable();
2263 LambdaCaptureKind Kind = From.isCopyCapture() ? LCK_ByCopy : LCK_ByRef;
2264 return LambdaCapture(From.getLocation(), IsImplicit, Kind, Var,
2265 From.getEllipsisLoc());
2266 }
2267 }();
2268
2269 // Form the initializer for the capture field.
2270 ExprResult Init = BuildCaptureInit(Cap: From, ImplicitCaptureLoc);
2271
2272 // FIXME: Skip this capture if the capture is not used, the initializer
2273 // has no side-effects, the type of the capture is trivial, and the
2274 // lambda is not externally visible.
2275
2276 // Add a FieldDecl for the capture and form its initializer.
2277 BuildCaptureField(RD: Class, Capture: From);
2278 Captures.push_back(Elt: Capture);
2279 CaptureInits.push_back(Elt: Init.get());
2280
2281 if (LangOpts.CUDA)
2282 CUDA().CheckLambdaCapture(D: CallOperator, Capture: From);
2283 }
2284
2285 Class->setCaptures(Context, Captures);
2286
2287 // C++11 [expr.prim.lambda]p6:
2288 // The closure type for a lambda-expression with no lambda-capture
2289 // has a public non-virtual non-explicit const conversion function
2290 // to pointer to function having the same parameter and return
2291 // types as the closure type's function call operator.
2292 if (Captures.empty() && CaptureDefault == LCD_None)
2293 addFunctionPointerConversions(S&: *this, IntroducerRange, Class, CallOperator);
2294
2295 // Objective-C++:
2296 // The closure type for a lambda-expression has a public non-virtual
2297 // non-explicit const conversion function to a block pointer having the
2298 // same parameter and return types as the closure type's function call
2299 // operator.
2300 // FIXME: Fix generic lambda to block conversions.
2301 if (getLangOpts().Blocks && getLangOpts().ObjC && !IsGenericLambda)
2302 addBlockPointerConversion(S&: *this, IntroducerRange, Class, CallOperator);
2303
2304 // Finalize the lambda class.
2305 SmallVector<Decl *, 4> Fields(Class->fields());
2306 ActOnFields(S: nullptr, RecLoc: Class->getLocation(), TagDecl: Class, Fields, LBrac: SourceLocation(),
2307 RBrac: SourceLocation(), AttrList: ParsedAttributesView());
2308 CheckCompletedCXXClass(S: nullptr, Record: Class);
2309
2310 Cleanup.mergeFrom(Rhs: LambdaCleanup);
2311
2312 LambdaExpr *Lambda =
2313 LambdaExpr::Create(C: Context, Class, IntroducerRange, CaptureDefault,
2314 CaptureDefaultLoc, ExplicitParams, ExplicitResultType,
2315 CaptureInits, ClosingBrace: EndLoc, ContainsUnexpandedParameterPack);
2316
2317 // If the lambda expression's call operator is not explicitly marked constexpr
2318 // and is not dependent, analyze the call operator to infer
2319 // its constexpr-ness, suppressing diagnostics while doing so.
2320 if (getLangOpts().CPlusPlus17 && !CallOperator->isInvalidDecl() &&
2321 !CallOperator->isConstexpr() &&
2322 !isa<CoroutineBodyStmt>(Val: CallOperator->getBody()) &&
2323 !Class->isDependentContext()) {
2324 CallOperator->setConstexprKind(
2325 CheckConstexprFunctionDefinition(FD: CallOperator,
2326 Kind: CheckConstexprKind::CheckValid)
2327 ? ConstexprSpecKind::Constexpr
2328 : ConstexprSpecKind::Unspecified);
2329 }
2330
2331 // Emit delayed shadowing warnings now that the full capture list is known.
2332 DiagnoseShadowingLambdaDecls(LSI);
2333
2334 if (!CurContext->isDependentContext()) {
2335 switch (ExprEvalContexts.back().Context) {
2336 // C++11 [expr.prim.lambda]p2:
2337 // A lambda-expression shall not appear in an unevaluated operand
2338 // (Clause 5).
2339 case ExpressionEvaluationContext::Unevaluated:
2340 case ExpressionEvaluationContext::UnevaluatedList:
2341 case ExpressionEvaluationContext::UnevaluatedAbstract:
2342 // C++1y [expr.const]p2:
2343 // A conditional-expression e is a core constant expression unless the
2344 // evaluation of e, following the rules of the abstract machine, would
2345 // evaluate [...] a lambda-expression.
2346 //
2347 // This is technically incorrect, there are some constant evaluated contexts
2348 // where this should be allowed. We should probably fix this when DR1607 is
2349 // ratified, it lays out the exact set of conditions where we shouldn't
2350 // allow a lambda-expression.
2351 case ExpressionEvaluationContext::ConstantEvaluated:
2352 case ExpressionEvaluationContext::ImmediateFunctionContext:
2353 // We don't actually diagnose this case immediately, because we
2354 // could be within a context where we might find out later that
2355 // the expression is potentially evaluated (e.g., for typeid).
2356 ExprEvalContexts.back().Lambdas.push_back(Elt: Lambda);
2357 break;
2358
2359 case ExpressionEvaluationContext::DiscardedStatement:
2360 case ExpressionEvaluationContext::PotentiallyEvaluated:
2361 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
2362 break;
2363 }
2364 maybeAddDeclWithEffects(D: LSI->CallOperator);
2365 }
2366
2367 return MaybeBindToTemporary(E: Lambda);
2368}
2369
2370ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
2371 SourceLocation ConvLocation,
2372 CXXConversionDecl *Conv,
2373 Expr *Src) {
2374 // Make sure that the lambda call operator is marked used.
2375 CXXRecordDecl *Lambda = Conv->getParent();
2376 CXXMethodDecl *CallOperator
2377 = cast<CXXMethodDecl>(
2378 Val: Lambda->lookup(
2379 Name: Context.DeclarationNames.getCXXOperatorName(Op: OO_Call)).front());
2380 CallOperator->setReferenced();
2381 CallOperator->markUsed(C&: Context);
2382
2383 ExprResult Init = PerformCopyInitialization(
2384 Entity: InitializedEntity::InitializeLambdaToBlock(BlockVarLoc: ConvLocation, Type: Src->getType()),
2385 EqualLoc: CurrentLocation, Init: Src);
2386 if (!Init.isInvalid())
2387 Init = ActOnFinishFullExpr(Expr: Init.get(), /*DiscardedValue*/ false);
2388
2389 if (Init.isInvalid())
2390 return ExprError();
2391
2392 // Create the new block to be returned.
2393 BlockDecl *Block = BlockDecl::Create(C&: Context, DC: CurContext, L: ConvLocation);
2394
2395 // Set the type information.
2396 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
2397 Block->setIsVariadic(CallOperator->isVariadic());
2398 Block->setBlockMissingReturnType(false);
2399
2400 // Add parameters.
2401 SmallVector<ParmVarDecl *, 4> BlockParams;
2402 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
2403 ParmVarDecl *From = CallOperator->getParamDecl(i: I);
2404 BlockParams.push_back(Elt: ParmVarDecl::Create(
2405 C&: Context, DC: Block, StartLoc: From->getBeginLoc(), IdLoc: From->getLocation(),
2406 Id: From->getIdentifier(), T: From->getType(), TInfo: From->getTypeSourceInfo(),
2407 S: From->getStorageClass(),
2408 /*DefArg=*/nullptr));
2409 }
2410 Block->setParams(BlockParams);
2411
2412 Block->setIsConversionFromLambda(true);
2413
2414 // Add capture. The capture uses a fake variable, which doesn't correspond
2415 // to any actual memory location. However, the initializer copy-initializes
2416 // the lambda object.
2417 TypeSourceInfo *CapVarTSI =
2418 Context.getTrivialTypeSourceInfo(T: Src->getType());
2419 VarDecl *CapVar = VarDecl::Create(C&: Context, DC: Block, StartLoc: ConvLocation,
2420 IdLoc: ConvLocation, Id: nullptr,
2421 T: Src->getType(), TInfo: CapVarTSI,
2422 S: SC_None);
2423 BlockDecl::Capture Capture(/*variable=*/CapVar, /*byRef=*/false,
2424 /*nested=*/false, /*copy=*/Init.get());
2425 Block->setCaptures(Context, Captures: Capture, /*CapturesCXXThis=*/false);
2426
2427 // Add a fake function body to the block. IR generation is responsible
2428 // for filling in the actual body, which cannot be expressed as an AST.
2429 Block->setBody(new (Context) CompoundStmt(ConvLocation));
2430
2431 // Create the block literal expression.
2432 // TODO: Do we ever get here if we have unexpanded packs in the lambda???
2433 Expr *BuildBlock =
2434 new (Context) BlockExpr(Block, Conv->getConversionType(),
2435 /*ContainsUnexpandedParameterPack=*/false);
2436 ExprCleanupObjects.push_back(Elt: Block);
2437 Cleanup.setExprNeedsCleanups(true);
2438
2439 return BuildBlock;
2440}
2441
2442static FunctionDecl *getPatternFunctionDecl(FunctionDecl *FD) {
2443 if (FD->getTemplatedKind() == FunctionDecl::TK_MemberSpecialization) {
2444 while (FD->getInstantiatedFromMemberFunction())
2445 FD = FD->getInstantiatedFromMemberFunction();
2446 return FD;
2447 }
2448
2449 if (FD->getTemplatedKind() == FunctionDecl::TK_DependentNonTemplate)
2450 return FD->getInstantiatedFromDecl();
2451
2452 FunctionTemplateDecl *FTD = FD->getPrimaryTemplate();
2453 if (!FTD)
2454 return nullptr;
2455
2456 while (FTD->getInstantiatedFromMemberTemplate())
2457 FTD = FTD->getInstantiatedFromMemberTemplate();
2458
2459 return FTD->getTemplatedDecl();
2460}
2461
2462bool Sema::addInstantiatedCapturesToScope(
2463 FunctionDecl *Function, const FunctionDecl *PatternDecl,
2464 LocalInstantiationScope &Scope,
2465 const MultiLevelTemplateArgumentList &TemplateArgs) {
2466 const auto *LambdaClass = cast<CXXMethodDecl>(Val: Function)->getParent();
2467 const auto *LambdaPattern = cast<CXXMethodDecl>(Val: PatternDecl)->getParent();
2468
2469 unsigned Instantiated = 0;
2470
2471 // FIXME: This is a workaround for not having deferred lambda body
2472 // instantiation.
2473 // When transforming a lambda's body, if we encounter another call to a
2474 // nested lambda that contains a constraint expression, we add all of the
2475 // outer lambda's instantiated captures to the current instantiation scope to
2476 // facilitate constraint evaluation. However, these captures don't appear in
2477 // the CXXRecordDecl until after the lambda expression is rebuilt, so we
2478 // pull them out from the corresponding LSI.
2479 LambdaScopeInfo *InstantiatingScope = nullptr;
2480 if (LambdaPattern->capture_size() && !LambdaClass->capture_size()) {
2481 for (FunctionScopeInfo *Scope : llvm::reverse(C&: FunctionScopes)) {
2482 auto *LSI = dyn_cast<LambdaScopeInfo>(Val: Scope);
2483 if (!LSI || getPatternFunctionDecl(FD: LSI->CallOperator) != PatternDecl)
2484 continue;
2485 InstantiatingScope = LSI;
2486 break;
2487 }
2488 assert(InstantiatingScope);
2489 }
2490
2491 auto AddSingleCapture = [&](const ValueDecl *CapturedPattern,
2492 unsigned Index) {
2493 ValueDecl *CapturedVar =
2494 InstantiatingScope ? InstantiatingScope->Captures[Index].getVariable()
2495 : LambdaClass->getCapture(I: Index)->getCapturedVar();
2496 assert(CapturedVar->isInitCapture());
2497 Scope.InstantiatedLocal(D: CapturedPattern, Inst: CapturedVar);
2498 };
2499
2500 for (const LambdaCapture &CapturePattern : LambdaPattern->captures()) {
2501 if (!CapturePattern.capturesVariable()) {
2502 Instantiated++;
2503 continue;
2504 }
2505 ValueDecl *CapturedPattern = CapturePattern.getCapturedVar();
2506
2507 if (!CapturedPattern->isInitCapture()) {
2508 Instantiated++;
2509 continue;
2510 }
2511
2512 if (!CapturedPattern->isParameterPack()) {
2513 AddSingleCapture(CapturedPattern, Instantiated++);
2514 } else {
2515 Scope.MakeInstantiatedLocalArgPack(D: CapturedPattern);
2516 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2517 SemaRef.collectUnexpandedParameterPacks(
2518 E: dyn_cast<VarDecl>(Val: CapturedPattern)->getInit(), Unexpanded);
2519 auto NumArgumentsInExpansion =
2520 getNumArgumentsInExpansionFromUnexpanded(Unexpanded, TemplateArgs);
2521 if (!NumArgumentsInExpansion)
2522 continue;
2523 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg)
2524 AddSingleCapture(CapturedPattern, Instantiated++);
2525 }
2526 }
2527 return false;
2528}
2529
2530Sema::LambdaScopeForCallOperatorInstantiationRAII::
2531 LambdaScopeForCallOperatorInstantiationRAII(
2532 Sema &SemaRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL,
2533 LocalInstantiationScope &Scope, bool ShouldAddDeclsFromParentScope)
2534 : FunctionScopeRAII(SemaRef) {
2535 if (!isLambdaCallOperator(DC: FD)) {
2536 FunctionScopeRAII::disable();
2537 return;
2538 }
2539
2540 SemaRef.RebuildLambdaScopeInfo(CallOperator: cast<CXXMethodDecl>(Val: FD));
2541
2542 FunctionDecl *FDPattern = getPatternFunctionDecl(FD);
2543 if (!FDPattern)
2544 return;
2545
2546 if (!ShouldAddDeclsFromParentScope)
2547 return;
2548
2549 llvm::SmallVector<std::pair<FunctionDecl *, FunctionDecl *>, 4>
2550 InstantiationAndPatterns;
2551 while (FDPattern && FD) {
2552 InstantiationAndPatterns.emplace_back(Args&: FDPattern, Args&: FD);
2553
2554 FDPattern = dyn_cast<FunctionDecl>(
2555 Val: getLambdaAwareParentOfDeclContext(DC: FDPattern)
2556 ->getEnclosingNonExpansionStatementContext());
2557 FD = dyn_cast<FunctionDecl>(
2558 Val: getLambdaAwareParentOfDeclContext(DC: FD)
2559 ->getEnclosingNonExpansionStatementContext());
2560 }
2561
2562 // Add instantiated parameters and local vars to scopes, starting from the
2563 // outermost lambda to the innermost lambda. This ordering ensures that
2564 // the outer instantiations can be found when referenced from within inner
2565 // lambdas.
2566 //
2567 // auto L = [](auto... x) {
2568 // return [](decltype(x)... y) { }; // Instantiating y needs x
2569 // };
2570 //
2571
2572 for (auto [FDPattern, FD] : llvm::reverse(C&: InstantiationAndPatterns)) {
2573 SemaRef.addInstantiatedParametersToScope(Function: FD, PatternDecl: FDPattern, Scope, TemplateArgs: MLTAL);
2574 SemaRef.addInstantiatedLocalVarsToScope(Function: FD, PatternDecl: FDPattern, Scope);
2575
2576 if (isLambdaCallOperator(DC: FD))
2577 SemaRef.addInstantiatedCapturesToScope(Function: FD, PatternDecl: FDPattern, Scope, TemplateArgs: MLTAL);
2578 }
2579}
2580