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

Provided by KDAB

Privacy Policy
Update your C++ knowledge – Modern C++11/14/17 Training
Find out more

source code of clang/lib/Sema/SemaLambda.cpp