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/DeclSpec.h"
13 #include "TypeLocBuilder.h"
14 #include "clang/AST/ASTLambda.h"
15 #include "clang/AST/ExprCXX.h"
16 #include "clang/Basic/TargetInfo.h"
17 #include "clang/Sema/Initialization.h"
18 #include "clang/Sema/Lookup.h"
19 #include "clang/Sema/Scope.h"
20 #include "clang/Sema/ScopeInfo.h"
21 #include "clang/Sema/SemaInternal.h"
22 #include "clang/Sema/SemaLambda.h"
23 #include "llvm/ADT/STLExtras.h"
24 using namespace clang;
25 using namespace sema;
26
27 /// Examines the FunctionScopeInfo stack to determine the nearest
28 /// enclosing lambda (to the current lambda) that is 'capture-ready' for
29 /// the variable referenced in the current lambda (i.e. \p VarToCapture).
30 /// If successful, returns the index into Sema's FunctionScopeInfo stack
31 /// of the capture-ready lambda's LambdaScopeInfo.
32 ///
33 /// Climbs down the stack of lambdas (deepest nested lambda - i.e. current
34 /// lambda - is on top) to determine the index of the nearest enclosing/outer
35 /// lambda that is ready to capture the \p VarToCapture being referenced in
36 /// the current lambda.
37 /// As we climb down the stack, we want the index of the first such lambda -
38 /// that is the lambda with the highest index that is 'capture-ready'.
39 ///
40 /// A lambda 'L' is capture-ready for 'V' (var or this) if:
41 /// - its enclosing context is non-dependent
42 /// - and if the chain of lambdas between L and the lambda in which
43 /// V is potentially used (i.e. the lambda at the top of the scope info
44 /// stack), can all capture or have already captured V.
45 /// If \p VarToCapture is 'null' then we are trying to capture 'this'.
46 ///
47 /// Note that a lambda that is deemed 'capture-ready' still needs to be checked
48 /// for whether it is 'capture-capable' (see
49 /// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly
50 /// capture.
51 ///
52 /// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
53 /// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
54 /// is at the top of the stack and has the highest index.
55 /// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
56 ///
57 /// \returns An Optional<unsigned> Index that if evaluates to 'true' contains
58 /// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda
59 /// which is capture-ready. If the return value evaluates to 'false' then
60 /// no lambda is capture-ready for \p VarToCapture.
61
62 static inline Optional<unsigned>
getStackIndexOfNearestEnclosingCaptureReadyLambda(ArrayRef<const clang::sema::FunctionScopeInfo * > FunctionScopes,VarDecl * VarToCapture)63 getStackIndexOfNearestEnclosingCaptureReadyLambda(
64 ArrayRef<const clang::sema::FunctionScopeInfo *> FunctionScopes,
65 VarDecl *VarToCapture) {
66 // Label failure to capture.
67 const Optional<unsigned> NoLambdaIsCaptureReady;
68
69 // Ignore all inner captured regions.
70 unsigned CurScopeIndex = FunctionScopes.size() - 1;
71 while (CurScopeIndex > 0 && isa<clang::sema::CapturedRegionScopeInfo>(
72 FunctionScopes[CurScopeIndex]))
73 --CurScopeIndex;
74 assert(
75 isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) &&
76 "The function on the top of sema's function-info stack must be a lambda");
77
78 // If VarToCapture is null, we are attempting to capture 'this'.
79 const bool IsCapturingThis = !VarToCapture;
80 const bool IsCapturingVariable = !IsCapturingThis;
81
82 // Start with the current lambda at the top of the stack (highest index).
83 DeclContext *EnclosingDC =
84 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator;
85
86 do {
87 const clang::sema::LambdaScopeInfo *LSI =
88 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]);
89 // IF we have climbed down to an intervening enclosing lambda that contains
90 // the variable declaration - it obviously can/must not capture the
91 // variable.
92 // Since its enclosing DC is dependent, all the lambdas between it and the
93 // innermost nested lambda are dependent (otherwise we wouldn't have
94 // arrived here) - so we don't yet have a lambda that can capture the
95 // variable.
96 if (IsCapturingVariable &&
97 VarToCapture->getDeclContext()->Equals(EnclosingDC))
98 return NoLambdaIsCaptureReady;
99
100 // For an enclosing lambda to be capture ready for an entity, all
101 // intervening lambda's have to be able to capture that entity. If even
102 // one of the intervening lambda's is not capable of capturing the entity
103 // then no enclosing lambda can ever capture that entity.
104 // For e.g.
105 // const int x = 10;
106 // [=](auto a) { #1
107 // [](auto b) { #2 <-- an intervening lambda that can never capture 'x'
108 // [=](auto c) { #3
109 // f(x, c); <-- can not lead to x's speculative capture by #1 or #2
110 // }; }; };
111 // If they do not have a default implicit capture, check to see
112 // if the entity has already been explicitly captured.
113 // If even a single dependent enclosing lambda lacks the capability
114 // to ever capture this variable, there is no further enclosing
115 // non-dependent lambda that can capture this variable.
116 if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) {
117 if (IsCapturingVariable && !LSI->isCaptured(VarToCapture))
118 return NoLambdaIsCaptureReady;
119 if (IsCapturingThis && !LSI->isCXXThisCaptured())
120 return NoLambdaIsCaptureReady;
121 }
122 EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC);
123
124 assert(CurScopeIndex);
125 --CurScopeIndex;
126 } while (!EnclosingDC->isTranslationUnit() &&
127 EnclosingDC->isDependentContext() &&
128 isLambdaCallOperator(EnclosingDC));
129
130 assert(CurScopeIndex < (FunctionScopes.size() - 1));
131 // If the enclosingDC is not dependent, then the immediately nested lambda
132 // (one index above) is capture-ready.
133 if (!EnclosingDC->isDependentContext())
134 return CurScopeIndex + 1;
135 return NoLambdaIsCaptureReady;
136 }
137
138 /// Examines the FunctionScopeInfo stack to determine the nearest
139 /// enclosing lambda (to the current lambda) that is 'capture-capable' for
140 /// the variable referenced in the current lambda (i.e. \p VarToCapture).
141 /// If successful, returns the index into Sema's FunctionScopeInfo stack
142 /// of the capture-capable lambda's LambdaScopeInfo.
143 ///
144 /// Given the current stack of lambdas being processed by Sema and
145 /// the variable of interest, to identify the nearest enclosing lambda (to the
146 /// current lambda at the top of the stack) that can truly capture
147 /// a variable, it has to have the following two properties:
148 /// a) 'capture-ready' - be the innermost lambda that is 'capture-ready':
149 /// - climb down the stack (i.e. starting from the innermost and examining
150 /// each outer lambda step by step) checking if each enclosing
151 /// lambda can either implicitly or explicitly capture the variable.
152 /// Record the first such lambda that is enclosed in a non-dependent
153 /// context. If no such lambda currently exists return failure.
154 /// b) 'capture-capable' - make sure the 'capture-ready' lambda can truly
155 /// capture the variable by checking all its enclosing lambdas:
156 /// - check if all outer lambdas enclosing the 'capture-ready' lambda
157 /// identified above in 'a' can also capture the variable (this is done
158 /// via tryCaptureVariable for variables and CheckCXXThisCapture for
159 /// 'this' by passing in the index of the Lambda identified in step 'a')
160 ///
161 /// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
162 /// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
163 /// is at the top of the stack.
164 ///
165 /// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
166 ///
167 ///
168 /// \returns An Optional<unsigned> Index that if evaluates to 'true' contains
169 /// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda
170 /// which is capture-capable. If the return value evaluates to 'false' then
171 /// no lambda is capture-capable for \p VarToCapture.
172
getStackIndexOfNearestEnclosingCaptureCapableLambda(ArrayRef<const sema::FunctionScopeInfo * > FunctionScopes,VarDecl * VarToCapture,Sema & S)173 Optional<unsigned> clang::getStackIndexOfNearestEnclosingCaptureCapableLambda(
174 ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes,
175 VarDecl *VarToCapture, Sema &S) {
176
177 const Optional<unsigned> NoLambdaIsCaptureCapable;
178
179 const Optional<unsigned> OptionalStackIndex =
180 getStackIndexOfNearestEnclosingCaptureReadyLambda(FunctionScopes,
181 VarToCapture);
182 if (!OptionalStackIndex)
183 return NoLambdaIsCaptureCapable;
184
185 const unsigned IndexOfCaptureReadyLambda = OptionalStackIndex.getValue();
186 assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) ||
187 S.getCurGenericLambda()) &&
188 "The capture ready lambda for a potential capture can only be the "
189 "current lambda if it is a generic lambda");
190
191 const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI =
192 cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]);
193
194 // If VarToCapture is null, we are attempting to capture 'this'
195 const bool IsCapturingThis = !VarToCapture;
196 const bool IsCapturingVariable = !IsCapturingThis;
197
198 if (IsCapturingVariable) {
199 // Check if the capture-ready lambda can truly capture the variable, by
200 // checking whether all enclosing lambdas of the capture-ready lambda allow
201 // the capture - i.e. make sure it is capture-capable.
202 QualType CaptureType, DeclRefType;
203 const bool CanCaptureVariable =
204 !S.tryCaptureVariable(VarToCapture,
205 /*ExprVarIsUsedInLoc*/ SourceLocation(),
206 clang::Sema::TryCapture_Implicit,
207 /*EllipsisLoc*/ SourceLocation(),
208 /*BuildAndDiagnose*/ false, CaptureType,
209 DeclRefType, &IndexOfCaptureReadyLambda);
210 if (!CanCaptureVariable)
211 return NoLambdaIsCaptureCapable;
212 } else {
213 // Check if the capture-ready lambda can truly capture 'this' by checking
214 // whether all enclosing lambdas of the capture-ready lambda can capture
215 // 'this'.
216 const bool CanCaptureThis =
217 !S.CheckCXXThisCapture(
218 CaptureReadyLambdaLSI->PotentialThisCaptureLocation,
219 /*Explicit*/ false, /*BuildAndDiagnose*/ false,
220 &IndexOfCaptureReadyLambda);
221 if (!CanCaptureThis)
222 return NoLambdaIsCaptureCapable;
223 }
224 return IndexOfCaptureReadyLambda;
225 }
226
227 static inline TemplateParameterList *
getGenericLambdaTemplateParameterList(LambdaScopeInfo * LSI,Sema & SemaRef)228 getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) {
229 if (!LSI->GLTemplateParameterList && !LSI->TemplateParams.empty()) {
230 LSI->GLTemplateParameterList = TemplateParameterList::Create(
231 SemaRef.Context,
232 /*Template kw loc*/ SourceLocation(),
233 /*L angle loc*/ LSI->ExplicitTemplateParamsRange.getBegin(),
234 LSI->TemplateParams,
235 /*R angle loc*/LSI->ExplicitTemplateParamsRange.getEnd(),
236 LSI->RequiresClause.get());
237 }
238 return LSI->GLTemplateParameterList;
239 }
240
createLambdaClosureType(SourceRange IntroducerRange,TypeSourceInfo * Info,bool KnownDependent,LambdaCaptureDefault CaptureDefault)241 CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
242 TypeSourceInfo *Info,
243 bool KnownDependent,
244 LambdaCaptureDefault CaptureDefault) {
245 DeclContext *DC = CurContext;
246 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
247 DC = DC->getParent();
248 bool IsGenericLambda = getGenericLambdaTemplateParameterList(getCurLambda(),
249 *this);
250 // Start constructing the lambda class.
251 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info,
252 IntroducerRange.getBegin(),
253 KnownDependent,
254 IsGenericLambda,
255 CaptureDefault);
256 DC->addDecl(Class);
257
258 return Class;
259 }
260
261 /// Determine whether the given context is or is enclosed in an inline
262 /// function.
isInInlineFunction(const DeclContext * DC)263 static bool isInInlineFunction(const DeclContext *DC) {
264 while (!DC->isFileContext()) {
265 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
266 if (FD->isInlined())
267 return true;
268
269 DC = DC->getLexicalParent();
270 }
271
272 return false;
273 }
274
275 std::tuple<MangleNumberingContext *, Decl *>
getCurrentMangleNumberContext(const DeclContext * DC)276 Sema::getCurrentMangleNumberContext(const DeclContext *DC) {
277 // Compute the context for allocating mangling numbers in the current
278 // expression, if the ABI requires them.
279 Decl *ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
280
281 enum ContextKind {
282 Normal,
283 DefaultArgument,
284 DataMember,
285 StaticDataMember,
286 InlineVariable,
287 VariableTemplate
288 } Kind = Normal;
289
290 // Default arguments of member function parameters that appear in a class
291 // definition, as well as the initializers of data members, receive special
292 // treatment. Identify them.
293 if (ManglingContextDecl) {
294 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
295 if (const DeclContext *LexicalDC
296 = Param->getDeclContext()->getLexicalParent())
297 if (LexicalDC->isRecord())
298 Kind = DefaultArgument;
299 } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
300 if (Var->getDeclContext()->isRecord())
301 Kind = StaticDataMember;
302 else if (Var->getMostRecentDecl()->isInline())
303 Kind = InlineVariable;
304 else if (Var->getDescribedVarTemplate())
305 Kind = VariableTemplate;
306 else if (auto *VTS = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
307 if (!VTS->isExplicitSpecialization())
308 Kind = VariableTemplate;
309 }
310 } else if (isa<FieldDecl>(ManglingContextDecl)) {
311 Kind = DataMember;
312 }
313 }
314
315 // Itanium ABI [5.1.7]:
316 // In the following contexts [...] the one-definition rule requires closure
317 // types in different translation units to "correspond":
318 bool IsInNonspecializedTemplate =
319 inTemplateInstantiation() || CurContext->isDependentContext();
320 switch (Kind) {
321 case Normal: {
322 // -- the bodies of non-exported nonspecialized template functions
323 // -- the bodies of inline functions
324 if ((IsInNonspecializedTemplate &&
325 !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
326 isInInlineFunction(CurContext)) {
327 while (auto *CD = dyn_cast<CapturedDecl>(DC))
328 DC = CD->getParent();
329 return std::make_tuple(&Context.getManglingNumberContext(DC), nullptr);
330 }
331
332 return std::make_tuple(nullptr, nullptr);
333 }
334
335 case StaticDataMember:
336 // -- the initializers of nonspecialized static members of template classes
337 if (!IsInNonspecializedTemplate)
338 return std::make_tuple(nullptr, ManglingContextDecl);
339 // Fall through to get the current context.
340 LLVM_FALLTHROUGH;
341
342 case DataMember:
343 // -- the in-class initializers of class members
344 case DefaultArgument:
345 // -- default arguments appearing in class definitions
346 case InlineVariable:
347 // -- the initializers of inline variables
348 case VariableTemplate:
349 // -- the initializers of templated variables
350 return std::make_tuple(
351 &Context.getManglingNumberContext(ASTContext::NeedExtraManglingDecl,
352 ManglingContextDecl),
353 ManglingContextDecl);
354 }
355
356 llvm_unreachable("unexpected context");
357 }
358
startLambdaDefinition(CXXRecordDecl * Class,SourceRange IntroducerRange,TypeSourceInfo * MethodTypeInfo,SourceLocation EndLoc,ArrayRef<ParmVarDecl * > Params,ConstexprSpecKind ConstexprKind,Expr * TrailingRequiresClause)359 CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
360 SourceRange IntroducerRange,
361 TypeSourceInfo *MethodTypeInfo,
362 SourceLocation EndLoc,
363 ArrayRef<ParmVarDecl *> Params,
364 ConstexprSpecKind ConstexprKind,
365 Expr *TrailingRequiresClause) {
366 QualType MethodType = MethodTypeInfo->getType();
367 TemplateParameterList *TemplateParams =
368 getGenericLambdaTemplateParameterList(getCurLambda(), *this);
369 // If a lambda appears in a dependent context or is a generic lambda (has
370 // template parameters) and has an 'auto' return type, deduce it to a
371 // dependent type.
372 if (Class->isDependentContext() || TemplateParams) {
373 const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
374 QualType Result = FPT->getReturnType();
375 if (Result->isUndeducedType()) {
376 Result = SubstAutoType(Result, Context.DependentTy);
377 MethodType = Context.getFunctionType(Result, FPT->getParamTypes(),
378 FPT->getExtProtoInfo());
379 }
380 }
381
382 // C++11 [expr.prim.lambda]p5:
383 // The closure type for a lambda-expression has a public inline function
384 // call operator (13.5.4) whose parameters and return type are described by
385 // the lambda-expression's parameter-declaration-clause and
386 // trailing-return-type respectively.
387 DeclarationName MethodName
388 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
389 DeclarationNameLoc MethodNameLoc =
390 DeclarationNameLoc::makeCXXOperatorNameLoc(IntroducerRange);
391 CXXMethodDecl *Method = CXXMethodDecl::Create(
392 Context, Class, EndLoc,
393 DeclarationNameInfo(MethodName, IntroducerRange.getBegin(),
394 MethodNameLoc),
395 MethodType, MethodTypeInfo, SC_None,
396 /*isInline=*/true, ConstexprKind, EndLoc, TrailingRequiresClause);
397 Method->setAccess(AS_public);
398 if (!TemplateParams)
399 Class->addDecl(Method);
400
401 // Temporarily set the lexical declaration context to the current
402 // context, so that the Scope stack matches the lexical nesting.
403 Method->setLexicalDeclContext(CurContext);
404 // Create a function template if we have a template parameter list
405 FunctionTemplateDecl *const TemplateMethod = TemplateParams ?
406 FunctionTemplateDecl::Create(Context, Class,
407 Method->getLocation(), MethodName,
408 TemplateParams,
409 Method) : nullptr;
410 if (TemplateMethod) {
411 TemplateMethod->setAccess(AS_public);
412 Method->setDescribedFunctionTemplate(TemplateMethod);
413 Class->addDecl(TemplateMethod);
414 TemplateMethod->setLexicalDeclContext(CurContext);
415 }
416
417 // Add parameters.
418 if (!Params.empty()) {
419 Method->setParams(Params);
420 CheckParmsForFunctionDef(Params,
421 /*CheckParameterNames=*/false);
422
423 for (auto P : Method->parameters())
424 P->setOwningFunction(Method);
425 }
426
427 return Method;
428 }
429
handleLambdaNumbering(CXXRecordDecl * Class,CXXMethodDecl * Method,Optional<std::tuple<bool,unsigned,unsigned,Decl * >> Mangling)430 void Sema::handleLambdaNumbering(
431 CXXRecordDecl *Class, CXXMethodDecl *Method,
432 Optional<std::tuple<bool, unsigned, unsigned, Decl *>> Mangling) {
433 if (Mangling) {
434 bool HasKnownInternalLinkage;
435 unsigned ManglingNumber, DeviceManglingNumber;
436 Decl *ManglingContextDecl;
437 std::tie(HasKnownInternalLinkage, ManglingNumber, DeviceManglingNumber,
438 ManglingContextDecl) = Mangling.getValue();
439 Class->setLambdaMangling(ManglingNumber, ManglingContextDecl,
440 HasKnownInternalLinkage);
441 Class->setDeviceLambdaManglingNumber(DeviceManglingNumber);
442 return;
443 }
444
445 auto getMangleNumberingContext =
446 [this](CXXRecordDecl *Class,
447 Decl *ManglingContextDecl) -> MangleNumberingContext * {
448 // Get mangle numbering context if there's any extra decl context.
449 if (ManglingContextDecl)
450 return &Context.getManglingNumberContext(
451 ASTContext::NeedExtraManglingDecl, ManglingContextDecl);
452 // Otherwise, from that lambda's decl context.
453 auto DC = Class->getDeclContext();
454 while (auto *CD = dyn_cast<CapturedDecl>(DC))
455 DC = CD->getParent();
456 return &Context.getManglingNumberContext(DC);
457 };
458
459 MangleNumberingContext *MCtx;
460 Decl *ManglingContextDecl;
461 std::tie(MCtx, ManglingContextDecl) =
462 getCurrentMangleNumberContext(Class->getDeclContext());
463 bool HasKnownInternalLinkage = false;
464 if (!MCtx && getLangOpts().CUDA) {
465 // Force lambda numbering in CUDA/HIP as we need to name lambdas following
466 // ODR. Both device- and host-compilation need to have a consistent naming
467 // on kernel functions. As lambdas are potential part of these `__global__`
468 // function names, they needs numbering following ODR.
469 MCtx = getMangleNumberingContext(Class, ManglingContextDecl);
470 assert(MCtx && "Retrieving mangle numbering context failed!");
471 HasKnownInternalLinkage = true;
472 }
473 if (MCtx) {
474 unsigned ManglingNumber = MCtx->getManglingNumber(Method);
475 Class->setLambdaMangling(ManglingNumber, ManglingContextDecl,
476 HasKnownInternalLinkage);
477 Class->setDeviceLambdaManglingNumber(MCtx->getDeviceManglingNumber(Method));
478 }
479 }
480
buildLambdaScope(LambdaScopeInfo * LSI,CXXMethodDecl * CallOperator,SourceRange IntroducerRange,LambdaCaptureDefault CaptureDefault,SourceLocation CaptureDefaultLoc,bool ExplicitParams,bool ExplicitResultType,bool Mutable)481 void Sema::buildLambdaScope(LambdaScopeInfo *LSI,
482 CXXMethodDecl *CallOperator,
483 SourceRange IntroducerRange,
484 LambdaCaptureDefault CaptureDefault,
485 SourceLocation CaptureDefaultLoc,
486 bool ExplicitParams,
487 bool ExplicitResultType,
488 bool Mutable) {
489 LSI->CallOperator = CallOperator;
490 CXXRecordDecl *LambdaClass = CallOperator->getParent();
491 LSI->Lambda = LambdaClass;
492 if (CaptureDefault == LCD_ByCopy)
493 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
494 else if (CaptureDefault == LCD_ByRef)
495 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
496 LSI->CaptureDefaultLoc = CaptureDefaultLoc;
497 LSI->IntroducerRange = IntroducerRange;
498 LSI->ExplicitParams = ExplicitParams;
499 LSI->Mutable = Mutable;
500
501 if (ExplicitResultType) {
502 LSI->ReturnType = CallOperator->getReturnType();
503
504 if (!LSI->ReturnType->isDependentType() &&
505 !LSI->ReturnType->isVoidType()) {
506 if (RequireCompleteType(CallOperator->getBeginLoc(), LSI->ReturnType,
507 diag::err_lambda_incomplete_result)) {
508 // Do nothing.
509 }
510 }
511 } else {
512 LSI->HasImplicitReturnType = true;
513 }
514 }
515
finishLambdaExplicitCaptures(LambdaScopeInfo * LSI)516 void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
517 LSI->finishedExplicitCaptures();
518 }
519
ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc,ArrayRef<NamedDecl * > TParams,SourceLocation RAngleLoc,ExprResult RequiresClause)520 void Sema::ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc,
521 ArrayRef<NamedDecl *> TParams,
522 SourceLocation RAngleLoc,
523 ExprResult RequiresClause) {
524 LambdaScopeInfo *LSI = getCurLambda();
525 assert(LSI && "Expected a lambda scope");
526 assert(LSI->NumExplicitTemplateParams == 0 &&
527 "Already acted on explicit template parameters");
528 assert(LSI->TemplateParams.empty() &&
529 "Explicit template parameters should come "
530 "before invented (auto) ones");
531 assert(!TParams.empty() &&
532 "No template parameters to act on");
533 LSI->TemplateParams.append(TParams.begin(), TParams.end());
534 LSI->NumExplicitTemplateParams = TParams.size();
535 LSI->ExplicitTemplateParamsRange = {LAngleLoc, RAngleLoc};
536 LSI->RequiresClause = RequiresClause;
537 }
538
addLambdaParameters(ArrayRef<LambdaIntroducer::LambdaCapture> Captures,CXXMethodDecl * CallOperator,Scope * CurScope)539 void Sema::addLambdaParameters(
540 ArrayRef<LambdaIntroducer::LambdaCapture> Captures,
541 CXXMethodDecl *CallOperator, Scope *CurScope) {
542 // Introduce our parameters into the function scope
543 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
544 p < NumParams; ++p) {
545 ParmVarDecl *Param = CallOperator->getParamDecl(p);
546
547 // If this has an identifier, add it to the scope stack.
548 if (CurScope && Param->getIdentifier()) {
549 bool Error = false;
550 // Resolution of CWG 2211 in C++17 renders shadowing ill-formed, but we
551 // retroactively apply it.
552 for (const auto &Capture : Captures) {
553 if (Capture.Id == Param->getIdentifier()) {
554 Error = true;
555 Diag(Param->getLocation(), diag::err_parameter_shadow_capture);
556 Diag(Capture.Loc, diag::note_var_explicitly_captured_here)
557 << Capture.Id << true;
558 }
559 }
560 if (!Error)
561 CheckShadow(CurScope, Param);
562
563 PushOnScopeChains(Param, CurScope);
564 }
565 }
566 }
567
568 /// If this expression is an enumerator-like expression of some type
569 /// T, return the type T; otherwise, return null.
570 ///
571 /// Pointer comparisons on the result here should always work because
572 /// it's derived from either the parent of an EnumConstantDecl
573 /// (i.e. the definition) or the declaration returned by
574 /// EnumType::getDecl() (i.e. the definition).
findEnumForBlockReturn(Expr * E)575 static EnumDecl *findEnumForBlockReturn(Expr *E) {
576 // An expression is an enumerator-like expression of type T if,
577 // ignoring parens and parens-like expressions:
578 E = E->IgnoreParens();
579
580 // - it is an enumerator whose enum type is T or
581 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
582 if (EnumConstantDecl *D
583 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
584 return cast<EnumDecl>(D->getDeclContext());
585 }
586 return nullptr;
587 }
588
589 // - it is a comma expression whose RHS is an enumerator-like
590 // expression of type T or
591 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
592 if (BO->getOpcode() == BO_Comma)
593 return findEnumForBlockReturn(BO->getRHS());
594 return nullptr;
595 }
596
597 // - it is a statement-expression whose value expression is an
598 // enumerator-like expression of type T or
599 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
600 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
601 return findEnumForBlockReturn(last);
602 return nullptr;
603 }
604
605 // - it is a ternary conditional operator (not the GNU ?:
606 // extension) whose second and third operands are
607 // enumerator-like expressions of type T or
608 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
609 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
610 if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
611 return ED;
612 return nullptr;
613 }
614
615 // (implicitly:)
616 // - it is an implicit integral conversion applied to an
617 // enumerator-like expression of type T or
618 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
619 // We can sometimes see integral conversions in valid
620 // enumerator-like expressions.
621 if (ICE->getCastKind() == CK_IntegralCast)
622 return findEnumForBlockReturn(ICE->getSubExpr());
623
624 // Otherwise, just rely on the type.
625 }
626
627 // - it is an expression of that formal enum type.
628 if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
629 return ET->getDecl();
630 }
631
632 // Otherwise, nope.
633 return nullptr;
634 }
635
636 /// Attempt to find a type T for which the returned expression of the
637 /// given statement is an enumerator-like expression of that type.
findEnumForBlockReturn(ReturnStmt * ret)638 static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
639 if (Expr *retValue = ret->getRetValue())
640 return findEnumForBlockReturn(retValue);
641 return nullptr;
642 }
643
644 /// Attempt to find a common type T for which all of the returned
645 /// expressions in a block are enumerator-like expressions of that
646 /// type.
findCommonEnumForBlockReturns(ArrayRef<ReturnStmt * > returns)647 static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
648 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
649
650 // Try to find one for the first return.
651 EnumDecl *ED = findEnumForBlockReturn(*i);
652 if (!ED) return nullptr;
653
654 // Check that the rest of the returns have the same enum.
655 for (++i; i != e; ++i) {
656 if (findEnumForBlockReturn(*i) != ED)
657 return nullptr;
658 }
659
660 // Never infer an anonymous enum type.
661 if (!ED->hasNameForLinkage()) return nullptr;
662
663 return ED;
664 }
665
666 /// Adjust the given return statements so that they formally return
667 /// the given type. It should require, at most, an IntegralCast.
adjustBlockReturnsToEnum(Sema & S,ArrayRef<ReturnStmt * > returns,QualType returnType)668 static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
669 QualType returnType) {
670 for (ArrayRef<ReturnStmt*>::iterator
671 i = returns.begin(), e = returns.end(); i != e; ++i) {
672 ReturnStmt *ret = *i;
673 Expr *retValue = ret->getRetValue();
674 if (S.Context.hasSameType(retValue->getType(), returnType))
675 continue;
676
677 // Right now we only support integral fixup casts.
678 assert(returnType->isIntegralOrUnscopedEnumerationType());
679 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
680
681 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
682
683 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
684 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast, E,
685 /*base path*/ nullptr, VK_RValue,
686 FPOptionsOverride());
687 if (cleanups) {
688 cleanups->setSubExpr(E);
689 } else {
690 ret->setRetValue(E);
691 }
692 }
693 }
694
deduceClosureReturnType(CapturingScopeInfo & CSI)695 void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
696 assert(CSI.HasImplicitReturnType);
697 // If it was ever a placeholder, it had to been deduced to DependentTy.
698 assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
699 assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) &&
700 "lambda expressions use auto deduction in C++14 onwards");
701
702 // C++ core issue 975:
703 // If a lambda-expression does not include a trailing-return-type,
704 // it is as if the trailing-return-type denotes the following type:
705 // - if there are no return statements in the compound-statement,
706 // or all return statements return either an expression of type
707 // void or no expression or braced-init-list, the type void;
708 // - otherwise, if all return statements return an expression
709 // and the types of the returned expressions after
710 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
711 // array-to-pointer conversion (4.2 [conv.array]), and
712 // function-to-pointer conversion (4.3 [conv.func]) are the
713 // same, that common type;
714 // - otherwise, the program is ill-formed.
715 //
716 // C++ core issue 1048 additionally removes top-level cv-qualifiers
717 // from the types of returned expressions to match the C++14 auto
718 // deduction rules.
719 //
720 // In addition, in blocks in non-C++ modes, if all of the return
721 // statements are enumerator-like expressions of some type T, where
722 // T has a name for linkage, then we infer the return type of the
723 // block to be that type.
724
725 // First case: no return statements, implicit void return type.
726 ASTContext &Ctx = getASTContext();
727 if (CSI.Returns.empty()) {
728 // It's possible there were simply no /valid/ return statements.
729 // In this case, the first one we found may have at least given us a type.
730 if (CSI.ReturnType.isNull())
731 CSI.ReturnType = Ctx.VoidTy;
732 return;
733 }
734
735 // Second case: at least one return statement has dependent type.
736 // Delay type checking until instantiation.
737 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
738 if (CSI.ReturnType->isDependentType())
739 return;
740
741 // Try to apply the enum-fuzz rule.
742 if (!getLangOpts().CPlusPlus) {
743 assert(isa<BlockScopeInfo>(CSI));
744 const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
745 if (ED) {
746 CSI.ReturnType = Context.getTypeDeclType(ED);
747 adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
748 return;
749 }
750 }
751
752 // Third case: only one return statement. Don't bother doing extra work!
753 if (CSI.Returns.size() == 1)
754 return;
755
756 // General case: many return statements.
757 // Check that they all have compatible return types.
758
759 // We require the return types to strictly match here.
760 // Note that we've already done the required promotions as part of
761 // processing the return statement.
762 for (const ReturnStmt *RS : CSI.Returns) {
763 const Expr *RetE = RS->getRetValue();
764
765 QualType ReturnType =
766 (RetE ? RetE->getType() : Context.VoidTy).getUnqualifiedType();
767 if (Context.getCanonicalFunctionResultType(ReturnType) ==
768 Context.getCanonicalFunctionResultType(CSI.ReturnType)) {
769 // Use the return type with the strictest possible nullability annotation.
770 auto RetTyNullability = ReturnType->getNullability(Ctx);
771 auto BlockNullability = CSI.ReturnType->getNullability(Ctx);
772 if (BlockNullability &&
773 (!RetTyNullability ||
774 hasWeakerNullability(*RetTyNullability, *BlockNullability)))
775 CSI.ReturnType = ReturnType;
776 continue;
777 }
778
779 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
780 // TODO: It's possible that the *first* return is the divergent one.
781 Diag(RS->getBeginLoc(),
782 diag::err_typecheck_missing_return_type_incompatible)
783 << ReturnType << CSI.ReturnType << isa<LambdaScopeInfo>(CSI);
784 // Continue iterating so that we keep emitting diagnostics.
785 }
786 }
787
buildLambdaInitCaptureInitialization(SourceLocation Loc,bool ByRef,SourceLocation EllipsisLoc,Optional<unsigned> NumExpansions,IdentifierInfo * Id,bool IsDirectInit,Expr * & Init)788 QualType Sema::buildLambdaInitCaptureInitialization(
789 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
790 Optional<unsigned> NumExpansions, IdentifierInfo *Id, bool IsDirectInit,
791 Expr *&Init) {
792 // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to
793 // deduce against.
794 QualType DeductType = Context.getAutoDeductType();
795 TypeLocBuilder TLB;
796 AutoTypeLoc TL = TLB.push<AutoTypeLoc>(DeductType);
797 TL.setNameLoc(Loc);
798 if (ByRef) {
799 DeductType = BuildReferenceType(DeductType, true, Loc, Id);
800 assert(!DeductType.isNull() && "can't build reference to auto");
801 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
802 }
803 if (EllipsisLoc.isValid()) {
804 if (Init->containsUnexpandedParameterPack()) {
805 Diag(EllipsisLoc, getLangOpts().CPlusPlus20
806 ? diag::warn_cxx17_compat_init_capture_pack
807 : diag::ext_init_capture_pack);
808 DeductType = Context.getPackExpansionType(DeductType, NumExpansions,
809 /*ExpectPackInType=*/false);
810 TLB.push<PackExpansionTypeLoc>(DeductType).setEllipsisLoc(EllipsisLoc);
811 } else {
812 // Just ignore the ellipsis for now and form a non-pack variable. We'll
813 // diagnose this later when we try to capture it.
814 }
815 }
816 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
817
818 // Deduce the type of the init capture.
819 QualType DeducedType = deduceVarTypeFromInitializer(
820 /*VarDecl*/nullptr, DeclarationName(Id), DeductType, TSI,
821 SourceRange(Loc, Loc), IsDirectInit, Init);
822 if (DeducedType.isNull())
823 return QualType();
824
825 // Are we a non-list direct initialization?
826 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
827
828 // Perform initialization analysis and ensure any implicit conversions
829 // (such as lvalue-to-rvalue) are enforced.
830 InitializedEntity Entity =
831 InitializedEntity::InitializeLambdaCapture(Id, DeducedType, Loc);
832 InitializationKind Kind =
833 IsDirectInit
834 ? (CXXDirectInit ? InitializationKind::CreateDirect(
835 Loc, Init->getBeginLoc(), Init->getEndLoc())
836 : InitializationKind::CreateDirectList(Loc))
837 : InitializationKind::CreateCopy(Loc, Init->getBeginLoc());
838
839 MultiExprArg Args = Init;
840 if (CXXDirectInit)
841 Args =
842 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
843 QualType DclT;
844 InitializationSequence InitSeq(*this, Entity, Kind, Args);
845 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
846
847 if (Result.isInvalid())
848 return QualType();
849
850 Init = Result.getAs<Expr>();
851 return DeducedType;
852 }
853
createLambdaInitCaptureVarDecl(SourceLocation Loc,QualType InitCaptureType,SourceLocation EllipsisLoc,IdentifierInfo * Id,unsigned InitStyle,Expr * Init)854 VarDecl *Sema::createLambdaInitCaptureVarDecl(SourceLocation Loc,
855 QualType InitCaptureType,
856 SourceLocation EllipsisLoc,
857 IdentifierInfo *Id,
858 unsigned InitStyle, Expr *Init) {
859 // FIXME: Retain the TypeSourceInfo from buildLambdaInitCaptureInitialization
860 // rather than reconstructing it here.
861 TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType, Loc);
862 if (auto PETL = TSI->getTypeLoc().getAs<PackExpansionTypeLoc>())
863 PETL.setEllipsisLoc(EllipsisLoc);
864
865 // Create a dummy variable representing the init-capture. This is not actually
866 // used as a variable, and only exists as a way to name and refer to the
867 // init-capture.
868 // FIXME: Pass in separate source locations for '&' and identifier.
869 VarDecl *NewVD = VarDecl::Create(Context, CurContext, Loc,
870 Loc, Id, InitCaptureType, TSI, SC_Auto);
871 NewVD->setInitCapture(true);
872 NewVD->setReferenced(true);
873 // FIXME: Pass in a VarDecl::InitializationStyle.
874 NewVD->setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle));
875 NewVD->markUsed(Context);
876 NewVD->setInit(Init);
877 if (NewVD->isParameterPack())
878 getCurLambda()->LocalPacks.push_back(NewVD);
879 return NewVD;
880 }
881
addInitCapture(LambdaScopeInfo * LSI,VarDecl * Var)882 void Sema::addInitCapture(LambdaScopeInfo *LSI, VarDecl *Var) {
883 assert(Var->isInitCapture() && "init capture flag should be set");
884 LSI->addCapture(Var, /*isBlock*/false, Var->getType()->isReferenceType(),
885 /*isNested*/false, Var->getLocation(), SourceLocation(),
886 Var->getType(), /*Invalid*/false);
887 }
888
ActOnStartOfLambdaDefinition(LambdaIntroducer & Intro,Declarator & ParamInfo,Scope * CurScope)889 void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
890 Declarator &ParamInfo,
891 Scope *CurScope) {
892 LambdaScopeInfo *const LSI = getCurLambda();
893 assert(LSI && "LambdaScopeInfo should be on stack!");
894
895 // Determine if we're within a context where we know that the lambda will
896 // be dependent, because there are template parameters in scope.
897 bool KnownDependent;
898 if (LSI->NumExplicitTemplateParams > 0) {
899 auto *TemplateParamScope = CurScope->getTemplateParamParent();
900 assert(TemplateParamScope &&
901 "Lambda with explicit template param list should establish a "
902 "template param scope");
903 assert(TemplateParamScope->getParent());
904 KnownDependent = TemplateParamScope->getParent()
905 ->getTemplateParamParent() != nullptr;
906 } else {
907 KnownDependent = CurScope->getTemplateParamParent() != nullptr;
908 }
909
910 // Determine the signature of the call operator.
911 TypeSourceInfo *MethodTyInfo;
912 bool ExplicitParams = true;
913 bool ExplicitResultType = true;
914 bool ContainsUnexpandedParameterPack = false;
915 SourceLocation EndLoc;
916 SmallVector<ParmVarDecl *, 8> Params;
917 if (ParamInfo.getNumTypeObjects() == 0) {
918 // C++11 [expr.prim.lambda]p4:
919 // If a lambda-expression does not include a lambda-declarator, it is as
920 // if the lambda-declarator were ().
921 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
922 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
923 EPI.HasTrailingReturn = true;
924 EPI.TypeQuals.addConst();
925 LangAS AS = getDefaultCXXMethodAddrSpace();
926 if (AS != LangAS::Default)
927 EPI.TypeQuals.addAddressSpace(AS);
928
929 // C++1y [expr.prim.lambda]:
930 // The lambda return type is 'auto', which is replaced by the
931 // trailing-return type if provided and/or deduced from 'return'
932 // statements
933 // We don't do this before C++1y, because we don't support deduced return
934 // types there.
935 QualType DefaultTypeForNoTrailingReturn =
936 getLangOpts().CPlusPlus14 ? Context.getAutoDeductType()
937 : Context.DependentTy;
938 QualType MethodTy =
939 Context.getFunctionType(DefaultTypeForNoTrailingReturn, None, EPI);
940 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
941 ExplicitParams = false;
942 ExplicitResultType = false;
943 EndLoc = Intro.Range.getEnd();
944 } else {
945 assert(ParamInfo.isFunctionDeclarator() &&
946 "lambda-declarator is a function");
947 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
948
949 // C++11 [expr.prim.lambda]p5:
950 // This function call operator is declared const (9.3.1) if and only if
951 // the lambda-expression's parameter-declaration-clause is not followed
952 // by mutable. It is neither virtual nor declared volatile. [...]
953 if (!FTI.hasMutableQualifier()) {
954 FTI.getOrCreateMethodQualifiers().SetTypeQual(DeclSpec::TQ_const,
955 SourceLocation());
956 }
957
958 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
959 assert(MethodTyInfo && "no type from lambda-declarator");
960 EndLoc = ParamInfo.getSourceRange().getEnd();
961
962 ExplicitResultType = FTI.hasTrailingReturnType();
963
964 if (FTIHasNonVoidParameters(FTI)) {
965 Params.reserve(FTI.NumParams);
966 for (unsigned i = 0, e = FTI.NumParams; i != e; ++i)
967 Params.push_back(cast<ParmVarDecl>(FTI.Params[i].Param));
968 }
969
970 // Check for unexpanded parameter packs in the method type.
971 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
972 DiagnoseUnexpandedParameterPack(Intro.Range.getBegin(), MethodTyInfo,
973 UPPC_DeclarationType);
974 }
975
976 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
977 KnownDependent, Intro.Default);
978 CXXMethodDecl *Method =
979 startLambdaDefinition(Class, Intro.Range, MethodTyInfo, EndLoc, Params,
980 ParamInfo.getDeclSpec().getConstexprSpecifier(),
981 ParamInfo.getTrailingRequiresClause());
982 if (ExplicitParams)
983 CheckCXXDefaultArguments(Method);
984
985 // This represents the function body for the lambda function, check if we
986 // have to apply optnone due to a pragma.
987 AddRangeBasedOptnone(Method);
988
989 // code_seg attribute on lambda apply to the method.
990 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method, /*IsDefinition=*/true))
991 Method->addAttr(A);
992
993 // Attributes on the lambda apply to the method.
994 ProcessDeclAttributes(CurScope, Method, ParamInfo);
995
996 // CUDA lambdas get implicit host and device attributes.
997 if (getLangOpts().CUDA)
998 CUDASetLambdaAttrs(Method);
999
1000 // OpenMP lambdas might get assumumption attributes.
1001 if (LangOpts.OpenMP)
1002 ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Method);
1003
1004 // Number the lambda for linkage purposes if necessary.
1005 handleLambdaNumbering(Class, Method);
1006
1007 // Introduce the function call operator as the current declaration context.
1008 PushDeclContext(CurScope, Method);
1009
1010 // Build the lambda scope.
1011 buildLambdaScope(LSI, Method, Intro.Range, Intro.Default, Intro.DefaultLoc,
1012 ExplicitParams, ExplicitResultType, !Method->isConst());
1013
1014 // C++11 [expr.prim.lambda]p9:
1015 // A lambda-expression whose smallest enclosing scope is a block scope is a
1016 // local lambda expression; any other lambda expression shall not have a
1017 // capture-default or simple-capture in its lambda-introducer.
1018 //
1019 // For simple-captures, this is covered by the check below that any named
1020 // entity is a variable that can be captured.
1021 //
1022 // For DR1632, we also allow a capture-default in any context where we can
1023 // odr-use 'this' (in particular, in a default initializer for a non-static
1024 // data member).
1025 if (Intro.Default != LCD_None && !Class->getParent()->isFunctionOrMethod() &&
1026 (getCurrentThisType().isNull() ||
1027 CheckCXXThisCapture(SourceLocation(), /*Explicit*/true,
1028 /*BuildAndDiagnose*/false)))
1029 Diag(Intro.DefaultLoc, diag::err_capture_default_non_local);
1030
1031 // Distinct capture names, for diagnostics.
1032 llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
1033
1034 // Handle explicit captures.
1035 SourceLocation PrevCaptureLoc
1036 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
1037 for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E;
1038 PrevCaptureLoc = C->Loc, ++C) {
1039 if (C->Kind == LCK_This || C->Kind == LCK_StarThis) {
1040 if (C->Kind == LCK_StarThis)
1041 Diag(C->Loc, !getLangOpts().CPlusPlus17
1042 ? diag::ext_star_this_lambda_capture_cxx17
1043 : diag::warn_cxx14_compat_star_this_lambda_capture);
1044
1045 // C++11 [expr.prim.lambda]p8:
1046 // An identifier or this shall not appear more than once in a
1047 // lambda-capture.
1048 if (LSI->isCXXThisCaptured()) {
1049 Diag(C->Loc, diag::err_capture_more_than_once)
1050 << "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation())
1051 << FixItHint::CreateRemoval(
1052 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1053 continue;
1054 }
1055
1056 // C++2a [expr.prim.lambda]p8:
1057 // If a lambda-capture includes a capture-default that is =,
1058 // each simple-capture of that lambda-capture shall be of the form
1059 // "&identifier", "this", or "* this". [ Note: The form [&,this] is
1060 // redundant but accepted for compatibility with ISO C++14. --end note ]
1061 if (Intro.Default == LCD_ByCopy && C->Kind != LCK_StarThis)
1062 Diag(C->Loc, !getLangOpts().CPlusPlus20
1063 ? diag::ext_equals_this_lambda_capture_cxx20
1064 : diag::warn_cxx17_compat_equals_this_lambda_capture);
1065
1066 // C++11 [expr.prim.lambda]p12:
1067 // If this is captured by a local lambda expression, its nearest
1068 // enclosing function shall be a non-static member function.
1069 QualType ThisCaptureType = getCurrentThisType();
1070 if (ThisCaptureType.isNull()) {
1071 Diag(C->Loc, diag::err_this_capture) << true;
1072 continue;
1073 }
1074
1075 CheckCXXThisCapture(C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true,
1076 /*FunctionScopeIndexToStopAtPtr*/ nullptr,
1077 C->Kind == LCK_StarThis);
1078 if (!LSI->Captures.empty())
1079 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1080 continue;
1081 }
1082
1083 assert(C->Id && "missing identifier for capture");
1084
1085 if (C->Init.isInvalid())
1086 continue;
1087
1088 VarDecl *Var = nullptr;
1089 if (C->Init.isUsable()) {
1090 Diag(C->Loc, getLangOpts().CPlusPlus14
1091 ? diag::warn_cxx11_compat_init_capture
1092 : diag::ext_init_capture);
1093
1094 // If the initializer expression is usable, but the InitCaptureType
1095 // is not, then an error has occurred - so ignore the capture for now.
1096 // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
1097 // FIXME: we should create the init capture variable and mark it invalid
1098 // in this case.
1099 if (C->InitCaptureType.get().isNull())
1100 continue;
1101
1102 if (C->Init.get()->containsUnexpandedParameterPack() &&
1103 !C->InitCaptureType.get()->getAs<PackExpansionType>())
1104 DiagnoseUnexpandedParameterPack(C->Init.get(), UPPC_Initializer);
1105
1106 unsigned InitStyle;
1107 switch (C->InitKind) {
1108 case LambdaCaptureInitKind::NoInit:
1109 llvm_unreachable("not an init-capture?");
1110 case LambdaCaptureInitKind::CopyInit:
1111 InitStyle = VarDecl::CInit;
1112 break;
1113 case LambdaCaptureInitKind::DirectInit:
1114 InitStyle = VarDecl::CallInit;
1115 break;
1116 case LambdaCaptureInitKind::ListInit:
1117 InitStyle = VarDecl::ListInit;
1118 break;
1119 }
1120 Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
1121 C->EllipsisLoc, C->Id, InitStyle,
1122 C->Init.get());
1123 // C++1y [expr.prim.lambda]p11:
1124 // An init-capture behaves as if it declares and explicitly
1125 // captures a variable [...] whose declarative region is the
1126 // lambda-expression's compound-statement
1127 if (Var)
1128 PushOnScopeChains(Var, CurScope, false);
1129 } else {
1130 assert(C->InitKind == LambdaCaptureInitKind::NoInit &&
1131 "init capture has valid but null init?");
1132
1133 // C++11 [expr.prim.lambda]p8:
1134 // If a lambda-capture includes a capture-default that is &, the
1135 // identifiers in the lambda-capture shall not be preceded by &.
1136 // If a lambda-capture includes a capture-default that is =, [...]
1137 // each identifier it contains shall be preceded by &.
1138 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
1139 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
1140 << FixItHint::CreateRemoval(
1141 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1142 continue;
1143 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
1144 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
1145 << FixItHint::CreateRemoval(
1146 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1147 continue;
1148 }
1149
1150 // C++11 [expr.prim.lambda]p10:
1151 // The identifiers in a capture-list are looked up using the usual
1152 // rules for unqualified name lookup (3.4.1)
1153 DeclarationNameInfo Name(C->Id, C->Loc);
1154 LookupResult R(*this, Name, LookupOrdinaryName);
1155 LookupName(R, CurScope);
1156 if (R.isAmbiguous())
1157 continue;
1158 if (R.empty()) {
1159 // FIXME: Disable corrections that would add qualification?
1160 CXXScopeSpec ScopeSpec;
1161 DeclFilterCCC<VarDecl> Validator{};
1162 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
1163 continue;
1164 }
1165
1166 Var = R.getAsSingle<VarDecl>();
1167 if (Var && DiagnoseUseOfDecl(Var, C->Loc))
1168 continue;
1169 }
1170
1171 // C++11 [expr.prim.lambda]p8:
1172 // An identifier or this shall not appear more than once in a
1173 // lambda-capture.
1174 if (!CaptureNames.insert(C->Id).second) {
1175 if (Var && LSI->isCaptured(Var)) {
1176 Diag(C->Loc, diag::err_capture_more_than_once)
1177 << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
1178 << FixItHint::CreateRemoval(
1179 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1180 } else
1181 // Previous capture captured something different (one or both was
1182 // an init-cpature): no fixit.
1183 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
1184 continue;
1185 }
1186
1187 // C++11 [expr.prim.lambda]p10:
1188 // [...] each such lookup shall find a variable with automatic storage
1189 // duration declared in the reaching scope of the local lambda expression.
1190 // Note that the 'reaching scope' check happens in tryCaptureVariable().
1191 if (!Var) {
1192 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
1193 continue;
1194 }
1195
1196 // Ignore invalid decls; they'll just confuse the code later.
1197 if (Var->isInvalidDecl())
1198 continue;
1199
1200 if (!Var->hasLocalStorage()) {
1201 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
1202 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
1203 continue;
1204 }
1205
1206 // C++11 [expr.prim.lambda]p23:
1207 // A capture followed by an ellipsis is a pack expansion (14.5.3).
1208 SourceLocation EllipsisLoc;
1209 if (C->EllipsisLoc.isValid()) {
1210 if (Var->isParameterPack()) {
1211 EllipsisLoc = C->EllipsisLoc;
1212 } else {
1213 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1214 << (C->Init.isUsable() ? C->Init.get()->getSourceRange()
1215 : SourceRange(C->Loc));
1216
1217 // Just ignore the ellipsis.
1218 }
1219 } else if (Var->isParameterPack()) {
1220 ContainsUnexpandedParameterPack = true;
1221 }
1222
1223 if (C->Init.isUsable()) {
1224 addInitCapture(LSI, Var);
1225 } else {
1226 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
1227 TryCapture_ExplicitByVal;
1228 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
1229 }
1230 if (!LSI->Captures.empty())
1231 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1232 }
1233 finishLambdaExplicitCaptures(LSI);
1234
1235 LSI->ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
1236
1237 // Add lambda parameters into scope.
1238 addLambdaParameters(Intro.Captures, Method, CurScope);
1239
1240 // Enter a new evaluation context to insulate the lambda from any
1241 // cleanups from the enclosing full-expression.
1242 PushExpressionEvaluationContext(
1243 LSI->CallOperator->isConsteval()
1244 ? ExpressionEvaluationContext::ConstantEvaluated
1245 : ExpressionEvaluationContext::PotentiallyEvaluated);
1246 }
1247
ActOnLambdaError(SourceLocation StartLoc,Scope * CurScope,bool IsInstantiation)1248 void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
1249 bool IsInstantiation) {
1250 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(FunctionScopes.back());
1251
1252 // Leave the expression-evaluation context.
1253 DiscardCleanupsInEvaluationContext();
1254 PopExpressionEvaluationContext();
1255
1256 // Leave the context of the lambda.
1257 if (!IsInstantiation)
1258 PopDeclContext();
1259
1260 // Finalize the lambda.
1261 CXXRecordDecl *Class = LSI->Lambda;
1262 Class->setInvalidDecl();
1263 SmallVector<Decl*, 4> Fields(Class->fields());
1264 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
1265 SourceLocation(), ParsedAttributesView());
1266 CheckCompletedCXXClass(nullptr, Class);
1267
1268 PopFunctionScopeInfo();
1269 }
1270
1271 template <typename Func>
repeatForLambdaConversionFunctionCallingConvs(Sema & S,const FunctionProtoType & CallOpProto,Func F)1272 static void repeatForLambdaConversionFunctionCallingConvs(
1273 Sema &S, const FunctionProtoType &CallOpProto, Func F) {
1274 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
1275 CallOpProto.isVariadic(), /*IsCXXMethod=*/false);
1276 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
1277 CallOpProto.isVariadic(), /*IsCXXMethod=*/true);
1278 CallingConv CallOpCC = CallOpProto.getCallConv();
1279
1280 /// Implement emitting a version of the operator for many of the calling
1281 /// conventions for MSVC, as described here:
1282 /// https://devblogs.microsoft.com/oldnewthing/20150220-00/?p=44623.
1283 /// Experimentally, we determined that cdecl, stdcall, fastcall, and
1284 /// vectorcall are generated by MSVC when it is supported by the target.
1285 /// Additionally, we are ensuring that the default-free/default-member and
1286 /// call-operator calling convention are generated as well.
1287 /// NOTE: We intentionally generate a 'thiscall' on Win32 implicitly from the
1288 /// 'member default', despite MSVC not doing so. We do this in order to ensure
1289 /// that someone who intentionally places 'thiscall' on the lambda call
1290 /// operator will still get that overload, since we don't have the a way of
1291 /// detecting the attribute by the time we get here.
1292 if (S.getLangOpts().MSVCCompat) {
1293 CallingConv Convs[] = {
1294 CC_C, CC_X86StdCall, CC_X86FastCall, CC_X86VectorCall,
1295 DefaultFree, DefaultMember, CallOpCC};
1296 llvm::sort(Convs);
1297 llvm::iterator_range<CallingConv *> Range(
1298 std::begin(Convs), std::unique(std::begin(Convs), std::end(Convs)));
1299 const TargetInfo &TI = S.getASTContext().getTargetInfo();
1300
1301 for (CallingConv C : Range) {
1302 if (TI.checkCallingConvention(C) == TargetInfo::CCCR_OK)
1303 F(C);
1304 }
1305 return;
1306 }
1307
1308 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree) {
1309 F(DefaultFree);
1310 F(DefaultMember);
1311 } else {
1312 F(CallOpCC);
1313 }
1314 }
1315
1316 // Returns the 'standard' calling convention to be used for the lambda
1317 // conversion function, that is, the 'free' function calling convention unless
1318 // it is overridden by a non-default calling convention attribute.
1319 static CallingConv
getLambdaConversionFunctionCallConv(Sema & S,const FunctionProtoType * CallOpProto)1320 getLambdaConversionFunctionCallConv(Sema &S,
1321 const FunctionProtoType *CallOpProto) {
1322 CallingConv DefaultFree = S.Context.getDefaultCallingConvention(
1323 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
1324 CallingConv DefaultMember = S.Context.getDefaultCallingConvention(
1325 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
1326 CallingConv CallOpCC = CallOpProto->getCallConv();
1327
1328 // If the call-operator hasn't been changed, return both the 'free' and
1329 // 'member' function calling convention.
1330 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree)
1331 return DefaultFree;
1332 return CallOpCC;
1333 }
1334
getLambdaConversionFunctionResultType(const FunctionProtoType * CallOpProto,CallingConv CC)1335 QualType Sema::getLambdaConversionFunctionResultType(
1336 const FunctionProtoType *CallOpProto, CallingConv CC) {
1337 const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
1338 CallOpProto->getExtProtoInfo();
1339 FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
1340 InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
1341 InvokerExtInfo.TypeQuals = Qualifiers();
1342 assert(InvokerExtInfo.RefQualifier == RQ_None &&
1343 "Lambda's call operator should not have a reference qualifier");
1344 return Context.getFunctionType(CallOpProto->getReturnType(),
1345 CallOpProto->getParamTypes(), InvokerExtInfo);
1346 }
1347
1348 /// Add a lambda's conversion to function pointer, as described in
1349 /// C++11 [expr.prim.lambda]p6.
addFunctionPointerConversion(Sema & S,SourceRange IntroducerRange,CXXRecordDecl * Class,CXXMethodDecl * CallOperator,QualType InvokerFunctionTy)1350 static void addFunctionPointerConversion(Sema &S, SourceRange IntroducerRange,
1351 CXXRecordDecl *Class,
1352 CXXMethodDecl *CallOperator,
1353 QualType InvokerFunctionTy) {
1354 // This conversion is explicitly disabled if the lambda's function has
1355 // pass_object_size attributes on any of its parameters.
1356 auto HasPassObjectSizeAttr = [](const ParmVarDecl *P) {
1357 return P->hasAttr<PassObjectSizeAttr>();
1358 };
1359 if (llvm::any_of(CallOperator->parameters(), HasPassObjectSizeAttr))
1360 return;
1361
1362 // Add the conversion to function pointer.
1363 QualType PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
1364
1365 // Create the type of the conversion function.
1366 FunctionProtoType::ExtProtoInfo ConvExtInfo(
1367 S.Context.getDefaultCallingConvention(
1368 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1369 // The conversion function is always const and noexcept.
1370 ConvExtInfo.TypeQuals = Qualifiers();
1371 ConvExtInfo.TypeQuals.addConst();
1372 ConvExtInfo.ExceptionSpec.Type = EST_BasicNoexcept;
1373 QualType ConvTy =
1374 S.Context.getFunctionType(PtrToFunctionTy, None, ConvExtInfo);
1375
1376 SourceLocation Loc = IntroducerRange.getBegin();
1377 DeclarationName ConversionName
1378 = S.Context.DeclarationNames.getCXXConversionFunctionName(
1379 S.Context.getCanonicalType(PtrToFunctionTy));
1380 // Construct a TypeSourceInfo for the conversion function, and wire
1381 // all the parameters appropriately for the FunctionProtoTypeLoc
1382 // so that everything works during transformation/instantiation of
1383 // generic lambdas.
1384 // The main reason for wiring up the parameters of the conversion
1385 // function with that of the call operator is so that constructs
1386 // like the following work:
1387 // auto L = [](auto b) { <-- 1
1388 // return [](auto a) -> decltype(a) { <-- 2
1389 // return a;
1390 // };
1391 // };
1392 // int (*fp)(int) = L(5);
1393 // Because the trailing return type can contain DeclRefExprs that refer
1394 // to the original call operator's variables, we hijack the call
1395 // operators ParmVarDecls below.
1396 TypeSourceInfo *ConvNamePtrToFunctionTSI =
1397 S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
1398 DeclarationNameLoc ConvNameLoc =
1399 DeclarationNameLoc::makeNamedTypeLoc(ConvNamePtrToFunctionTSI);
1400
1401 // The conversion function is a conversion to a pointer-to-function.
1402 TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
1403 FunctionProtoTypeLoc ConvTL =
1404 ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
1405 // Get the result of the conversion function which is a pointer-to-function.
1406 PointerTypeLoc PtrToFunctionTL =
1407 ConvTL.getReturnLoc().getAs<PointerTypeLoc>();
1408 // Do the same for the TypeSourceInfo that is used to name the conversion
1409 // operator.
1410 PointerTypeLoc ConvNamePtrToFunctionTL =
1411 ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
1412
1413 // Get the underlying function types that the conversion function will
1414 // be converting to (should match the type of the call operator).
1415 FunctionProtoTypeLoc CallOpConvTL =
1416 PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1417 FunctionProtoTypeLoc CallOpConvNameTL =
1418 ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1419
1420 // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
1421 // These parameter's are essentially used to transform the name and
1422 // the type of the conversion operator. By using the same parameters
1423 // as the call operator's we don't have to fix any back references that
1424 // the trailing return type of the call operator's uses (such as
1425 // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
1426 // - we can simply use the return type of the call operator, and
1427 // everything should work.
1428 SmallVector<ParmVarDecl *, 4> InvokerParams;
1429 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1430 ParmVarDecl *From = CallOperator->getParamDecl(I);
1431
1432 InvokerParams.push_back(ParmVarDecl::Create(
1433 S.Context,
1434 // Temporarily add to the TU. This is set to the invoker below.
1435 S.Context.getTranslationUnitDecl(), From->getBeginLoc(),
1436 From->getLocation(), From->getIdentifier(), From->getType(),
1437 From->getTypeSourceInfo(), From->getStorageClass(),
1438 /*DefArg=*/nullptr));
1439 CallOpConvTL.setParam(I, From);
1440 CallOpConvNameTL.setParam(I, From);
1441 }
1442
1443 CXXConversionDecl *Conversion = CXXConversionDecl::Create(
1444 S.Context, Class, Loc,
1445 DeclarationNameInfo(ConversionName, Loc, ConvNameLoc), ConvTy, ConvTSI,
1446 /*isInline=*/true, ExplicitSpecifier(),
1447 S.getLangOpts().CPlusPlus17 ? ConstexprSpecKind::Constexpr
1448 : ConstexprSpecKind::Unspecified,
1449 CallOperator->getBody()->getEndLoc());
1450 Conversion->setAccess(AS_public);
1451 Conversion->setImplicit(true);
1452
1453 if (Class->isGenericLambda()) {
1454 // Create a template version of the conversion operator, using the template
1455 // parameter list of the function call operator.
1456 FunctionTemplateDecl *TemplateCallOperator =
1457 CallOperator->getDescribedFunctionTemplate();
1458 FunctionTemplateDecl *ConversionTemplate =
1459 FunctionTemplateDecl::Create(S.Context, Class,
1460 Loc, ConversionName,
1461 TemplateCallOperator->getTemplateParameters(),
1462 Conversion);
1463 ConversionTemplate->setAccess(AS_public);
1464 ConversionTemplate->setImplicit(true);
1465 Conversion->setDescribedFunctionTemplate(ConversionTemplate);
1466 Class->addDecl(ConversionTemplate);
1467 } else
1468 Class->addDecl(Conversion);
1469 // Add a non-static member function that will be the result of
1470 // the conversion with a certain unique ID.
1471 DeclarationName InvokerName = &S.Context.Idents.get(
1472 getLambdaStaticInvokerName());
1473 // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
1474 // we should get a prebuilt TrivialTypeSourceInfo from Context
1475 // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
1476 // then rewire the parameters accordingly, by hoisting up the InvokeParams
1477 // loop below and then use its Params to set Invoke->setParams(...) below.
1478 // This would avoid the 'const' qualifier of the calloperator from
1479 // contaminating the type of the invoker, which is currently adjusted
1480 // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the
1481 // trailing return type of the invoker would require a visitor to rebuild
1482 // the trailing return type and adjusting all back DeclRefExpr's to refer
1483 // to the new static invoker parameters - not the call operator's.
1484 CXXMethodDecl *Invoke = CXXMethodDecl::Create(
1485 S.Context, Class, Loc, DeclarationNameInfo(InvokerName, Loc),
1486 InvokerFunctionTy, CallOperator->getTypeSourceInfo(), SC_Static,
1487 /*isInline=*/true, ConstexprSpecKind::Unspecified,
1488 CallOperator->getBody()->getEndLoc());
1489 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
1490 InvokerParams[I]->setOwningFunction(Invoke);
1491 Invoke->setParams(InvokerParams);
1492 Invoke->setAccess(AS_private);
1493 Invoke->setImplicit(true);
1494 if (Class->isGenericLambda()) {
1495 FunctionTemplateDecl *TemplateCallOperator =
1496 CallOperator->getDescribedFunctionTemplate();
1497 FunctionTemplateDecl *StaticInvokerTemplate = FunctionTemplateDecl::Create(
1498 S.Context, Class, Loc, InvokerName,
1499 TemplateCallOperator->getTemplateParameters(),
1500 Invoke);
1501 StaticInvokerTemplate->setAccess(AS_private);
1502 StaticInvokerTemplate->setImplicit(true);
1503 Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
1504 Class->addDecl(StaticInvokerTemplate);
1505 } else
1506 Class->addDecl(Invoke);
1507 }
1508
1509 /// Add a lambda's conversion to function pointers, as described in
1510 /// C++11 [expr.prim.lambda]p6. Note that in most cases, this should emit only a
1511 /// single pointer conversion. In the event that the default calling convention
1512 /// for free and member functions is different, it will emit both conventions.
addFunctionPointerConversions(Sema & S,SourceRange IntroducerRange,CXXRecordDecl * Class,CXXMethodDecl * CallOperator)1513 static void addFunctionPointerConversions(Sema &S, SourceRange IntroducerRange,
1514 CXXRecordDecl *Class,
1515 CXXMethodDecl *CallOperator) {
1516 const FunctionProtoType *CallOpProto =
1517 CallOperator->getType()->castAs<FunctionProtoType>();
1518
1519 repeatForLambdaConversionFunctionCallingConvs(
1520 S, *CallOpProto, [&](CallingConv CC) {
1521 QualType InvokerFunctionTy =
1522 S.getLambdaConversionFunctionResultType(CallOpProto, CC);
1523 addFunctionPointerConversion(S, IntroducerRange, Class, CallOperator,
1524 InvokerFunctionTy);
1525 });
1526 }
1527
1528 /// Add a lambda's conversion to block pointer.
addBlockPointerConversion(Sema & S,SourceRange IntroducerRange,CXXRecordDecl * Class,CXXMethodDecl * CallOperator)1529 static void addBlockPointerConversion(Sema &S,
1530 SourceRange IntroducerRange,
1531 CXXRecordDecl *Class,
1532 CXXMethodDecl *CallOperator) {
1533 const FunctionProtoType *CallOpProto =
1534 CallOperator->getType()->castAs<FunctionProtoType>();
1535 QualType FunctionTy = S.getLambdaConversionFunctionResultType(
1536 CallOpProto, getLambdaConversionFunctionCallConv(S, CallOpProto));
1537 QualType BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
1538
1539 FunctionProtoType::ExtProtoInfo ConversionEPI(
1540 S.Context.getDefaultCallingConvention(
1541 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1542 ConversionEPI.TypeQuals = Qualifiers();
1543 ConversionEPI.TypeQuals.addConst();
1544 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ConversionEPI);
1545
1546 SourceLocation Loc = IntroducerRange.getBegin();
1547 DeclarationName Name
1548 = S.Context.DeclarationNames.getCXXConversionFunctionName(
1549 S.Context.getCanonicalType(BlockPtrTy));
1550 DeclarationNameLoc NameLoc = DeclarationNameLoc::makeNamedTypeLoc(
1551 S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc));
1552 CXXConversionDecl *Conversion = CXXConversionDecl::Create(
1553 S.Context, Class, Loc, DeclarationNameInfo(Name, Loc, NameLoc), ConvTy,
1554 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
1555 /*isInline=*/true, ExplicitSpecifier(), ConstexprSpecKind::Unspecified,
1556 CallOperator->getBody()->getEndLoc());
1557 Conversion->setAccess(AS_public);
1558 Conversion->setImplicit(true);
1559 Class->addDecl(Conversion);
1560 }
1561
BuildCaptureInit(const Capture & Cap,SourceLocation ImplicitCaptureLoc,bool IsOpenMPMapping)1562 ExprResult Sema::BuildCaptureInit(const Capture &Cap,
1563 SourceLocation ImplicitCaptureLoc,
1564 bool IsOpenMPMapping) {
1565 // VLA captures don't have a stored initialization expression.
1566 if (Cap.isVLATypeCapture())
1567 return ExprResult();
1568
1569 // An init-capture is initialized directly from its stored initializer.
1570 if (Cap.isInitCapture())
1571 return Cap.getVariable()->getInit();
1572
1573 // For anything else, build an initialization expression. For an implicit
1574 // capture, the capture notionally happens at the capture-default, so use
1575 // that location here.
1576 SourceLocation Loc =
1577 ImplicitCaptureLoc.isValid() ? ImplicitCaptureLoc : Cap.getLocation();
1578
1579 // C++11 [expr.prim.lambda]p21:
1580 // When the lambda-expression is evaluated, the entities that
1581 // are captured by copy are used to direct-initialize each
1582 // corresponding non-static data member of the resulting closure
1583 // object. (For array members, the array elements are
1584 // direct-initialized in increasing subscript order.) These
1585 // initializations are performed in the (unspecified) order in
1586 // which the non-static data members are declared.
1587
1588 // C++ [expr.prim.lambda]p12:
1589 // An entity captured by a lambda-expression is odr-used (3.2) in
1590 // the scope containing the lambda-expression.
1591 ExprResult Init;
1592 IdentifierInfo *Name = nullptr;
1593 if (Cap.isThisCapture()) {
1594 QualType ThisTy = getCurrentThisType();
1595 Expr *This = BuildCXXThisExpr(Loc, ThisTy, ImplicitCaptureLoc.isValid());
1596 if (Cap.isCopyCapture())
1597 Init = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
1598 else
1599 Init = This;
1600 } else {
1601 assert(Cap.isVariableCapture() && "unknown kind of capture");
1602 VarDecl *Var = Cap.getVariable();
1603 Name = Var->getIdentifier();
1604 Init = BuildDeclarationNameExpr(
1605 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
1606 }
1607
1608 // In OpenMP, the capture kind doesn't actually describe how to capture:
1609 // variables are "mapped" onto the device in a process that does not formally
1610 // make a copy, even for a "copy capture".
1611 if (IsOpenMPMapping)
1612 return Init;
1613
1614 if (Init.isInvalid())
1615 return ExprError();
1616
1617 Expr *InitExpr = Init.get();
1618 InitializedEntity Entity = InitializedEntity::InitializeLambdaCapture(
1619 Name, Cap.getCaptureType(), Loc);
1620 InitializationKind InitKind =
1621 InitializationKind::CreateDirect(Loc, Loc, Loc);
1622 InitializationSequence InitSeq(*this, Entity, InitKind, InitExpr);
1623 return InitSeq.Perform(*this, Entity, InitKind, InitExpr);
1624 }
1625
ActOnLambdaExpr(SourceLocation StartLoc,Stmt * Body,Scope * CurScope)1626 ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
1627 Scope *CurScope) {
1628 LambdaScopeInfo LSI = *cast<LambdaScopeInfo>(FunctionScopes.back());
1629 ActOnFinishFunctionBody(LSI.CallOperator, Body);
1630 return BuildLambdaExpr(StartLoc, Body->getEndLoc(), &LSI);
1631 }
1632
1633 static LambdaCaptureDefault
mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS)1634 mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS) {
1635 switch (ICS) {
1636 case CapturingScopeInfo::ImpCap_None:
1637 return LCD_None;
1638 case CapturingScopeInfo::ImpCap_LambdaByval:
1639 return LCD_ByCopy;
1640 case CapturingScopeInfo::ImpCap_CapturedRegion:
1641 case CapturingScopeInfo::ImpCap_LambdaByref:
1642 return LCD_ByRef;
1643 case CapturingScopeInfo::ImpCap_Block:
1644 llvm_unreachable("block capture in lambda");
1645 }
1646 llvm_unreachable("Unknown implicit capture style");
1647 }
1648
CaptureHasSideEffects(const Capture & From)1649 bool Sema::CaptureHasSideEffects(const Capture &From) {
1650 if (From.isInitCapture()) {
1651 Expr *Init = From.getVariable()->getInit();
1652 if (Init && Init->HasSideEffects(Context))
1653 return true;
1654 }
1655
1656 if (!From.isCopyCapture())
1657 return false;
1658
1659 const QualType T = From.isThisCapture()
1660 ? getCurrentThisType()->getPointeeType()
1661 : From.getCaptureType();
1662
1663 if (T.isVolatileQualified())
1664 return true;
1665
1666 const Type *BaseT = T->getBaseElementTypeUnsafe();
1667 if (const CXXRecordDecl *RD = BaseT->getAsCXXRecordDecl())
1668 return !RD->isCompleteDefinition() || !RD->hasTrivialCopyConstructor() ||
1669 !RD->hasTrivialDestructor();
1670
1671 return false;
1672 }
1673
DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,const Capture & From)1674 bool Sema::DiagnoseUnusedLambdaCapture(SourceRange CaptureRange,
1675 const Capture &From) {
1676 if (CaptureHasSideEffects(From))
1677 return false;
1678
1679 if (From.isVLATypeCapture())
1680 return false;
1681
1682 auto diag = Diag(From.getLocation(), diag::warn_unused_lambda_capture);
1683 if (From.isThisCapture())
1684 diag << "'this'";
1685 else
1686 diag << From.getVariable();
1687 diag << From.isNonODRUsed();
1688 diag << FixItHint::CreateRemoval(CaptureRange);
1689 return true;
1690 }
1691
1692 /// Create a field within the lambda class or captured statement record for the
1693 /// given capture.
BuildCaptureField(RecordDecl * RD,const sema::Capture & Capture)1694 FieldDecl *Sema::BuildCaptureField(RecordDecl *RD,
1695 const sema::Capture &Capture) {
1696 SourceLocation Loc = Capture.getLocation();
1697 QualType FieldType = Capture.getCaptureType();
1698
1699 TypeSourceInfo *TSI = nullptr;
1700 if (Capture.isVariableCapture()) {
1701 auto *Var = Capture.getVariable();
1702 if (Var->isInitCapture())
1703 TSI = Capture.getVariable()->getTypeSourceInfo();
1704 }
1705
1706 // FIXME: Should we really be doing this? A null TypeSourceInfo seems more
1707 // appropriate, at least for an implicit capture.
1708 if (!TSI)
1709 TSI = Context.getTrivialTypeSourceInfo(FieldType, Loc);
1710
1711 // Build the non-static data member.
1712 FieldDecl *Field =
1713 FieldDecl::Create(Context, RD, /*StartLoc=*/Loc, /*IdLoc=*/Loc,
1714 /*Id=*/nullptr, FieldType, TSI, /*BW=*/nullptr,
1715 /*Mutable=*/false, ICIS_NoInit);
1716 // If the variable being captured has an invalid type, mark the class as
1717 // invalid as well.
1718 if (!FieldType->isDependentType()) {
1719 if (RequireCompleteSizedType(Loc, FieldType,
1720 diag::err_field_incomplete_or_sizeless)) {
1721 RD->setInvalidDecl();
1722 Field->setInvalidDecl();
1723 } else {
1724 NamedDecl *Def;
1725 FieldType->isIncompleteType(&Def);
1726 if (Def && Def->isInvalidDecl()) {
1727 RD->setInvalidDecl();
1728 Field->setInvalidDecl();
1729 }
1730 }
1731 }
1732 Field->setImplicit(true);
1733 Field->setAccess(AS_private);
1734 RD->addDecl(Field);
1735
1736 if (Capture.isVLATypeCapture())
1737 Field->setCapturedVLAType(Capture.getCapturedVLAType());
1738
1739 return Field;
1740 }
1741
BuildLambdaExpr(SourceLocation StartLoc,SourceLocation EndLoc,LambdaScopeInfo * LSI)1742 ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
1743 LambdaScopeInfo *LSI) {
1744 // Collect information from the lambda scope.
1745 SmallVector<LambdaCapture, 4> Captures;
1746 SmallVector<Expr *, 4> CaptureInits;
1747 SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc;
1748 LambdaCaptureDefault CaptureDefault =
1749 mapImplicitCaptureStyle(LSI->ImpCaptureStyle);
1750 CXXRecordDecl *Class;
1751 CXXMethodDecl *CallOperator;
1752 SourceRange IntroducerRange;
1753 bool ExplicitParams;
1754 bool ExplicitResultType;
1755 CleanupInfo LambdaCleanup;
1756 bool ContainsUnexpandedParameterPack;
1757 bool IsGenericLambda;
1758 {
1759 CallOperator = LSI->CallOperator;
1760 Class = LSI->Lambda;
1761 IntroducerRange = LSI->IntroducerRange;
1762 ExplicitParams = LSI->ExplicitParams;
1763 ExplicitResultType = !LSI->HasImplicitReturnType;
1764 LambdaCleanup = LSI->Cleanup;
1765 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
1766 IsGenericLambda = Class->isGenericLambda();
1767
1768 CallOperator->setLexicalDeclContext(Class);
1769 Decl *TemplateOrNonTemplateCallOperatorDecl =
1770 CallOperator->getDescribedFunctionTemplate()
1771 ? CallOperator->getDescribedFunctionTemplate()
1772 : cast<Decl>(CallOperator);
1773
1774 // FIXME: Is this really the best choice? Keeping the lexical decl context
1775 // set as CurContext seems more faithful to the source.
1776 TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
1777
1778 PopExpressionEvaluationContext();
1779
1780 // True if the current capture has a used capture or default before it.
1781 bool CurHasPreviousCapture = CaptureDefault != LCD_None;
1782 SourceLocation PrevCaptureLoc = CurHasPreviousCapture ?
1783 CaptureDefaultLoc : IntroducerRange.getBegin();
1784
1785 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
1786 const Capture &From = LSI->Captures[I];
1787
1788 if (From.isInvalid())
1789 return ExprError();
1790
1791 assert(!From.isBlockCapture() && "Cannot capture __block variables");
1792 bool IsImplicit = I >= LSI->NumExplicitCaptures;
1793 SourceLocation ImplicitCaptureLoc =
1794 IsImplicit ? CaptureDefaultLoc : SourceLocation();
1795
1796 // Use source ranges of explicit captures for fixits where available.
1797 SourceRange CaptureRange = LSI->ExplicitCaptureRanges[I];
1798
1799 // Warn about unused explicit captures.
1800 bool IsCaptureUsed = true;
1801 if (!CurContext->isDependentContext() && !IsImplicit &&
1802 !From.isODRUsed()) {
1803 // Initialized captures that are non-ODR used may not be eliminated.
1804 // FIXME: Where did the IsGenericLambda here come from?
1805 bool NonODRUsedInitCapture =
1806 IsGenericLambda && From.isNonODRUsed() && From.isInitCapture();
1807 if (!NonODRUsedInitCapture) {
1808 bool IsLast = (I + 1) == LSI->NumExplicitCaptures;
1809 SourceRange FixItRange;
1810 if (CaptureRange.isValid()) {
1811 if (!CurHasPreviousCapture && !IsLast) {
1812 // If there are no captures preceding this capture, remove the
1813 // following comma.
1814 FixItRange = SourceRange(CaptureRange.getBegin(),
1815 getLocForEndOfToken(CaptureRange.getEnd()));
1816 } else {
1817 // Otherwise, remove the comma since the last used capture.
1818 FixItRange = SourceRange(getLocForEndOfToken(PrevCaptureLoc),
1819 CaptureRange.getEnd());
1820 }
1821 }
1822
1823 IsCaptureUsed = !DiagnoseUnusedLambdaCapture(FixItRange, From);
1824 }
1825 }
1826
1827 if (CaptureRange.isValid()) {
1828 CurHasPreviousCapture |= IsCaptureUsed;
1829 PrevCaptureLoc = CaptureRange.getEnd();
1830 }
1831
1832 // Map the capture to our AST representation.
1833 LambdaCapture Capture = [&] {
1834 if (From.isThisCapture()) {
1835 // Capturing 'this' implicitly with a default of '[=]' is deprecated,
1836 // because it results in a reference capture. Don't warn prior to
1837 // C++2a; there's nothing that can be done about it before then.
1838 if (getLangOpts().CPlusPlus20 && IsImplicit &&
1839 CaptureDefault == LCD_ByCopy) {
1840 Diag(From.getLocation(), diag::warn_deprecated_this_capture);
1841 Diag(CaptureDefaultLoc, diag::note_deprecated_this_capture)
1842 << FixItHint::CreateInsertion(
1843 getLocForEndOfToken(CaptureDefaultLoc), ", this");
1844 }
1845 return LambdaCapture(From.getLocation(), IsImplicit,
1846 From.isCopyCapture() ? LCK_StarThis : LCK_This);
1847 } else if (From.isVLATypeCapture()) {
1848 return LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType);
1849 } else {
1850 assert(From.isVariableCapture() && "unknown kind of capture");
1851 VarDecl *Var = From.getVariable();
1852 LambdaCaptureKind Kind =
1853 From.isCopyCapture() ? LCK_ByCopy : LCK_ByRef;
1854 return LambdaCapture(From.getLocation(), IsImplicit, Kind, Var,
1855 From.getEllipsisLoc());
1856 }
1857 }();
1858
1859 // Form the initializer for the capture field.
1860 ExprResult Init = BuildCaptureInit(From, ImplicitCaptureLoc);
1861
1862 // FIXME: Skip this capture if the capture is not used, the initializer
1863 // has no side-effects, the type of the capture is trivial, and the
1864 // lambda is not externally visible.
1865
1866 // Add a FieldDecl for the capture and form its initializer.
1867 BuildCaptureField(Class, From);
1868 Captures.push_back(Capture);
1869 CaptureInits.push_back(Init.get());
1870
1871 if (LangOpts.CUDA)
1872 CUDACheckLambdaCapture(CallOperator, From);
1873 }
1874
1875 Class->setCaptures(Context, Captures);
1876
1877 // C++11 [expr.prim.lambda]p6:
1878 // The closure type for a lambda-expression with no lambda-capture
1879 // has a public non-virtual non-explicit const conversion function
1880 // to pointer to function having the same parameter and return
1881 // types as the closure type's function call operator.
1882 if (Captures.empty() && CaptureDefault == LCD_None)
1883 addFunctionPointerConversions(*this, IntroducerRange, Class,
1884 CallOperator);
1885
1886 // Objective-C++:
1887 // The closure type for a lambda-expression has a public non-virtual
1888 // non-explicit const conversion function to a block pointer having the
1889 // same parameter and return types as the closure type's function call
1890 // operator.
1891 // FIXME: Fix generic lambda to block conversions.
1892 if (getLangOpts().Blocks && getLangOpts().ObjC && !IsGenericLambda)
1893 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
1894
1895 // Finalize the lambda class.
1896 SmallVector<Decl*, 4> Fields(Class->fields());
1897 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
1898 SourceLocation(), ParsedAttributesView());
1899 CheckCompletedCXXClass(nullptr, Class);
1900 }
1901
1902 Cleanup.mergeFrom(LambdaCleanup);
1903
1904 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
1905 CaptureDefault, CaptureDefaultLoc,
1906 ExplicitParams, ExplicitResultType,
1907 CaptureInits, EndLoc,
1908 ContainsUnexpandedParameterPack);
1909 // If the lambda expression's call operator is not explicitly marked constexpr
1910 // and we are not in a dependent context, analyze the call operator to infer
1911 // its constexpr-ness, suppressing diagnostics while doing so.
1912 if (getLangOpts().CPlusPlus17 && !CallOperator->isInvalidDecl() &&
1913 !CallOperator->isConstexpr() &&
1914 !isa<CoroutineBodyStmt>(CallOperator->getBody()) &&
1915 !Class->getDeclContext()->isDependentContext()) {
1916 CallOperator->setConstexprKind(
1917 CheckConstexprFunctionDefinition(CallOperator,
1918 CheckConstexprKind::CheckValid)
1919 ? ConstexprSpecKind::Constexpr
1920 : ConstexprSpecKind::Unspecified);
1921 }
1922
1923 // Emit delayed shadowing warnings now that the full capture list is known.
1924 DiagnoseShadowingLambdaDecls(LSI);
1925
1926 if (!CurContext->isDependentContext()) {
1927 switch (ExprEvalContexts.back().Context) {
1928 // C++11 [expr.prim.lambda]p2:
1929 // A lambda-expression shall not appear in an unevaluated operand
1930 // (Clause 5).
1931 case ExpressionEvaluationContext::Unevaluated:
1932 case ExpressionEvaluationContext::UnevaluatedList:
1933 case ExpressionEvaluationContext::UnevaluatedAbstract:
1934 // C++1y [expr.const]p2:
1935 // A conditional-expression e is a core constant expression unless the
1936 // evaluation of e, following the rules of the abstract machine, would
1937 // evaluate [...] a lambda-expression.
1938 //
1939 // This is technically incorrect, there are some constant evaluated contexts
1940 // where this should be allowed. We should probably fix this when DR1607 is
1941 // ratified, it lays out the exact set of conditions where we shouldn't
1942 // allow a lambda-expression.
1943 case ExpressionEvaluationContext::ConstantEvaluated:
1944 // We don't actually diagnose this case immediately, because we
1945 // could be within a context where we might find out later that
1946 // the expression is potentially evaluated (e.g., for typeid).
1947 ExprEvalContexts.back().Lambdas.push_back(Lambda);
1948 break;
1949
1950 case ExpressionEvaluationContext::DiscardedStatement:
1951 case ExpressionEvaluationContext::PotentiallyEvaluated:
1952 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
1953 break;
1954 }
1955 }
1956
1957 return MaybeBindToTemporary(Lambda);
1958 }
1959
BuildBlockForLambdaConversion(SourceLocation CurrentLocation,SourceLocation ConvLocation,CXXConversionDecl * Conv,Expr * Src)1960 ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
1961 SourceLocation ConvLocation,
1962 CXXConversionDecl *Conv,
1963 Expr *Src) {
1964 // Make sure that the lambda call operator is marked used.
1965 CXXRecordDecl *Lambda = Conv->getParent();
1966 CXXMethodDecl *CallOperator
1967 = cast<CXXMethodDecl>(
1968 Lambda->lookup(
1969 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
1970 CallOperator->setReferenced();
1971 CallOperator->markUsed(Context);
1972
1973 ExprResult Init = PerformCopyInitialization(
1974 InitializedEntity::InitializeLambdaToBlock(ConvLocation, Src->getType(),
1975 /*NRVO=*/false),
1976 CurrentLocation, Src);
1977 if (!Init.isInvalid())
1978 Init = ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
1979
1980 if (Init.isInvalid())
1981 return ExprError();
1982
1983 // Create the new block to be returned.
1984 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
1985
1986 // Set the type information.
1987 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
1988 Block->setIsVariadic(CallOperator->isVariadic());
1989 Block->setBlockMissingReturnType(false);
1990
1991 // Add parameters.
1992 SmallVector<ParmVarDecl *, 4> BlockParams;
1993 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1994 ParmVarDecl *From = CallOperator->getParamDecl(I);
1995 BlockParams.push_back(ParmVarDecl::Create(
1996 Context, Block, From->getBeginLoc(), From->getLocation(),
1997 From->getIdentifier(), From->getType(), From->getTypeSourceInfo(),
1998 From->getStorageClass(),
1999 /*DefArg=*/nullptr));
2000 }
2001 Block->setParams(BlockParams);
2002
2003 Block->setIsConversionFromLambda(true);
2004
2005 // Add capture. The capture uses a fake variable, which doesn't correspond
2006 // to any actual memory location. However, the initializer copy-initializes
2007 // the lambda object.
2008 TypeSourceInfo *CapVarTSI =
2009 Context.getTrivialTypeSourceInfo(Src->getType());
2010 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
2011 ConvLocation, nullptr,
2012 Src->getType(), CapVarTSI,
2013 SC_None);
2014 BlockDecl::Capture Capture(/*variable=*/CapVar, /*byRef=*/false,
2015 /*nested=*/false, /*copy=*/Init.get());
2016 Block->setCaptures(Context, Capture, /*CapturesCXXThis=*/false);
2017
2018 // Add a fake function body to the block. IR generation is responsible
2019 // for filling in the actual body, which cannot be expressed as an AST.
2020 Block->setBody(new (Context) CompoundStmt(ConvLocation));
2021
2022 // Create the block literal expression.
2023 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
2024 ExprCleanupObjects.push_back(Block);
2025 Cleanup.setExprNeedsCleanups(true);
2026
2027 return BuildBlock;
2028 }
2029