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