1 //===--- SemaLambda.cpp - Semantic Analysis for C++11 Lambdas -------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements semantic analysis for C++ lambda expressions.
12 //===----------------------------------------------------------------------===//
13 #include "clang/Sema/DeclSpec.h"
14 #include "clang/AST/ExprCXX.h"
15 #include "clang/Lex/Preprocessor.h"
16 #include "clang/Sema/Initialization.h"
17 #include "clang/Sema/Lookup.h"
18 #include "clang/Sema/Scope.h"
19 #include "clang/Sema/ScopeInfo.h"
20 #include "clang/Sema/SemaInternal.h"
21 using namespace clang;
24 CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
26 bool KnownDependent) {
27 DeclContext *DC = CurContext;
28 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
31 // Start constructing the lambda class.
32 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info,
33 IntroducerRange.getBegin(),
40 /// \brief Determine whether the given context is or is enclosed in an inline
42 static bool isInInlineFunction(const DeclContext *DC) {
43 while (!DC->isFileContext()) {
44 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
48 DC = DC->getLexicalParent();
54 CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
55 SourceRange IntroducerRange,
56 TypeSourceInfo *MethodType,
57 SourceLocation EndLoc,
58 ArrayRef<ParmVarDecl *> Params) {
59 // C++11 [expr.prim.lambda]p5:
60 // The closure type for a lambda-expression has a public inline function
61 // call operator (13.5.4) whose parameters and return type are described by
62 // the lambda-expression's parameter-declaration-clause and
63 // trailing-return-type respectively.
64 DeclarationName MethodName
65 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
66 DeclarationNameLoc MethodNameLoc;
67 MethodNameLoc.CXXOperatorName.BeginOpNameLoc
68 = IntroducerRange.getBegin().getRawEncoding();
69 MethodNameLoc.CXXOperatorName.EndOpNameLoc
70 = IntroducerRange.getEnd().getRawEncoding();
72 = CXXMethodDecl::Create(Context, Class, EndLoc,
73 DeclarationNameInfo(MethodName,
74 IntroducerRange.getBegin(),
76 MethodType->getType(), MethodType,
79 /*isConstExpr=*/false,
81 Method->setAccess(AS_public);
83 // Temporarily set the lexical declaration context to the current
84 // context, so that the Scope stack matches the lexical nesting.
85 Method->setLexicalDeclContext(CurContext);
88 if (!Params.empty()) {
89 Method->setParams(Params);
90 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
91 const_cast<ParmVarDecl **>(Params.end()),
92 /*CheckParameterNames=*/false);
94 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
95 PEnd = Method->param_end();
97 (*P)->setOwningFunction(Method);
100 // Allocate a mangling number for this lambda expression, if the ABI
102 Decl *ContextDecl = ExprEvalContexts.back().LambdaContextDecl;
111 // Default arguments of member function parameters that appear in a class
112 // definition, as well as the initializers of data members, receive special
113 // treatment. Identify them.
115 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ContextDecl)) {
116 if (const DeclContext *LexicalDC
117 = Param->getDeclContext()->getLexicalParent())
118 if (LexicalDC->isRecord())
119 Kind = DefaultArgument;
120 } else if (VarDecl *Var = dyn_cast<VarDecl>(ContextDecl)) {
121 if (Var->getDeclContext()->isRecord())
122 Kind = StaticDataMember;
123 } else if (isa<FieldDecl>(ContextDecl)) {
128 // Itanium ABI [5.1.7]:
129 // In the following contexts [...] the one-definition rule requires closure
130 // types in different translation units to "correspond":
131 bool IsInNonspecializedTemplate =
132 !ActiveTemplateInstantiations.empty() || CurContext->isDependentContext();
133 unsigned ManglingNumber;
136 // -- the bodies of non-exported nonspecialized template functions
137 // -- the bodies of inline functions
138 if ((IsInNonspecializedTemplate &&
139 !(ContextDecl && isa<ParmVarDecl>(ContextDecl))) ||
140 isInInlineFunction(CurContext))
141 ManglingNumber = Context.getLambdaManglingNumber(Method);
145 // There is no special context for this lambda.
149 case StaticDataMember:
150 // -- the initializers of nonspecialized static members of template classes
151 if (!IsInNonspecializedTemplate) {
156 // Fall through to assign a mangling number.
159 // -- the in-class initializers of class members
160 case DefaultArgument:
161 // -- default arguments appearing in class definitions
162 ManglingNumber = ExprEvalContexts.back().getLambdaMangleContext()
163 .getManglingNumber(Method);
167 Class->setLambdaMangling(ManglingNumber, ContextDecl);
172 LambdaScopeInfo *Sema::enterLambdaScope(CXXMethodDecl *CallOperator,
173 SourceRange IntroducerRange,
174 LambdaCaptureDefault CaptureDefault,
176 bool ExplicitResultType,
178 PushLambdaScope(CallOperator->getParent(), CallOperator);
179 LambdaScopeInfo *LSI = getCurLambda();
180 if (CaptureDefault == LCD_ByCopy)
181 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
182 else if (CaptureDefault == LCD_ByRef)
183 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
184 LSI->IntroducerRange = IntroducerRange;
185 LSI->ExplicitParams = ExplicitParams;
186 LSI->Mutable = Mutable;
188 if (ExplicitResultType) {
189 LSI->ReturnType = CallOperator->getResultType();
191 if (!LSI->ReturnType->isDependentType() &&
192 !LSI->ReturnType->isVoidType()) {
193 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
194 diag::err_lambda_incomplete_result)) {
196 } else if (LSI->ReturnType->isObjCObjectOrInterfaceType()) {
197 Diag(CallOperator->getLocStart(), diag::err_lambda_objc_object_result)
202 LSI->HasImplicitReturnType = true;
208 void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
209 LSI->finishedExplicitCaptures();
212 void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
213 // Introduce our parameters into the function scope
214 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
215 p < NumParams; ++p) {
216 ParmVarDecl *Param = CallOperator->getParamDecl(p);
218 // If this has an identifier, add it to the scope stack.
219 if (CurScope && Param->getIdentifier()) {
220 CheckShadow(CurScope, Param);
222 PushOnScopeChains(Param, CurScope);
227 /// If this expression is an enumerator-like expression of some type
228 /// T, return the type T; otherwise, return null.
230 /// Pointer comparisons on the result here should always work because
231 /// it's derived from either the parent of an EnumConstantDecl
232 /// (i.e. the definition) or the declaration returned by
233 /// EnumType::getDecl() (i.e. the definition).
234 static EnumDecl *findEnumForBlockReturn(Expr *E) {
235 // An expression is an enumerator-like expression of type T if,
236 // ignoring parens and parens-like expressions:
237 E = E->IgnoreParens();
239 // - it is an enumerator whose enum type is T or
240 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
241 if (EnumConstantDecl *D
242 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
243 return cast<EnumDecl>(D->getDeclContext());
248 // - it is a comma expression whose RHS is an enumerator-like
249 // expression of type T or
250 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
251 if (BO->getOpcode() == BO_Comma)
252 return findEnumForBlockReturn(BO->getRHS());
256 // - it is a statement-expression whose value expression is an
257 // enumerator-like expression of type T or
258 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
259 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
260 return findEnumForBlockReturn(last);
264 // - it is a ternary conditional operator (not the GNU ?:
265 // extension) whose second and third operands are
266 // enumerator-like expressions of type T or
267 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
268 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
269 if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
275 // - it is an implicit integral conversion applied to an
276 // enumerator-like expression of type T or
277 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
278 // We can only see integral conversions in valid enumerator-like
280 if (ICE->getCastKind() == CK_IntegralCast)
281 return findEnumForBlockReturn(ICE->getSubExpr());
285 // - it is an expression of that formal enum type.
286 if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
287 return ET->getDecl();
294 /// Attempt to find a type T for which the returned expression of the
295 /// given statement is an enumerator-like expression of that type.
296 static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
297 if (Expr *retValue = ret->getRetValue())
298 return findEnumForBlockReturn(retValue);
302 /// Attempt to find a common type T for which all of the returned
303 /// expressions in a block are enumerator-like expressions of that
305 static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
306 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
308 // Try to find one for the first return.
309 EnumDecl *ED = findEnumForBlockReturn(*i);
312 // Check that the rest of the returns have the same enum.
313 for (++i; i != e; ++i) {
314 if (findEnumForBlockReturn(*i) != ED)
318 // Never infer an anonymous enum type.
319 if (!ED->hasNameForLinkage()) return 0;
324 /// Adjust the given return statements so that they formally return
325 /// the given type. It should require, at most, an IntegralCast.
326 static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
327 QualType returnType) {
328 for (ArrayRef<ReturnStmt*>::iterator
329 i = returns.begin(), e = returns.end(); i != e; ++i) {
330 ReturnStmt *ret = *i;
331 Expr *retValue = ret->getRetValue();
332 if (S.Context.hasSameType(retValue->getType(), returnType))
335 // Right now we only support integral fixup casts.
336 assert(returnType->isIntegralOrUnscopedEnumerationType());
337 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
339 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
341 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
342 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast,
343 E, /*base path*/ 0, VK_RValue);
345 cleanups->setSubExpr(E);
352 void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
353 assert(CSI.HasImplicitReturnType);
355 // C++ Core Issue #975, proposed resolution:
356 // If a lambda-expression does not include a trailing-return-type,
357 // it is as if the trailing-return-type denotes the following type:
358 // - if there are no return statements in the compound-statement,
359 // or all return statements return either an expression of type
360 // void or no expression or braced-init-list, the type void;
361 // - otherwise, if all return statements return an expression
362 // and the types of the returned expressions after
363 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
364 // array-to-pointer conversion (4.2 [conv.array]), and
365 // function-to-pointer conversion (4.3 [conv.func]) are the
366 // same, that common type;
367 // - otherwise, the program is ill-formed.
369 // In addition, in blocks in non-C++ modes, if all of the return
370 // statements are enumerator-like expressions of some type T, where
371 // T has a name for linkage, then we infer the return type of the
372 // block to be that type.
374 // First case: no return statements, implicit void return type.
375 ASTContext &Ctx = getASTContext();
376 if (CSI.Returns.empty()) {
377 // It's possible there were simply no /valid/ return statements.
378 // In this case, the first one we found may have at least given us a type.
379 if (CSI.ReturnType.isNull())
380 CSI.ReturnType = Ctx.VoidTy;
384 // Second case: at least one return statement has dependent type.
385 // Delay type checking until instantiation.
386 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
387 if (CSI.ReturnType->isDependentType())
390 // Try to apply the enum-fuzz rule.
391 if (!getLangOpts().CPlusPlus) {
392 assert(isa<BlockScopeInfo>(CSI));
393 const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
395 CSI.ReturnType = Context.getTypeDeclType(ED);
396 adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
401 // Third case: only one return statement. Don't bother doing extra work!
402 SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
403 E = CSI.Returns.end();
407 // General case: many return statements.
408 // Check that they all have compatible return types.
410 // We require the return types to strictly match here.
411 // Note that we've already done the required promotions as part of
412 // processing the return statement.
413 for (; I != E; ++I) {
414 const ReturnStmt *RS = *I;
415 const Expr *RetE = RS->getRetValue();
417 QualType ReturnType = (RetE ? RetE->getType() : Context.VoidTy);
418 if (Context.hasSameType(ReturnType, CSI.ReturnType))
421 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
422 // TODO: It's possible that the *first* return is the divergent one.
423 Diag(RS->getLocStart(),
424 diag::err_typecheck_missing_return_type_incompatible)
425 << ReturnType << CSI.ReturnType
426 << isa<LambdaScopeInfo>(CSI);
427 // Continue iterating so that we keep emitting diagnostics.
431 void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
432 Declarator &ParamInfo,
434 // Determine if we're within a context where we know that the lambda will
435 // be dependent, because there are template parameters in scope.
436 bool KnownDependent = false;
437 if (Scope *TmplScope = CurScope->getTemplateParamParent())
438 if (!TmplScope->decl_empty())
439 KnownDependent = true;
441 // Determine the signature of the call operator.
442 TypeSourceInfo *MethodTyInfo;
443 bool ExplicitParams = true;
444 bool ExplicitResultType = true;
445 bool ContainsUnexpandedParameterPack = false;
446 SourceLocation EndLoc;
447 SmallVector<ParmVarDecl *, 8> Params;
448 if (ParamInfo.getNumTypeObjects() == 0) {
449 // C++11 [expr.prim.lambda]p4:
450 // If a lambda-expression does not include a lambda-declarator, it is as
451 // if the lambda-declarator were ().
452 FunctionProtoType::ExtProtoInfo EPI;
453 EPI.HasTrailingReturn = true;
454 EPI.TypeQuals |= DeclSpec::TQ_const;
455 QualType MethodTy = Context.getFunctionType(Context.DependentTy, None,
457 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
458 ExplicitParams = false;
459 ExplicitResultType = false;
460 EndLoc = Intro.Range.getEnd();
462 assert(ParamInfo.isFunctionDeclarator() &&
463 "lambda-declarator is a function");
464 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
466 // C++11 [expr.prim.lambda]p5:
467 // This function call operator is declared const (9.3.1) if and only if
468 // the lambda-expression's parameter-declaration-clause is not followed
469 // by mutable. It is neither virtual nor declared volatile. [...]
470 if (!FTI.hasMutableQualifier())
471 FTI.TypeQuals |= DeclSpec::TQ_const;
473 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
474 assert(MethodTyInfo && "no type from lambda-declarator");
475 EndLoc = ParamInfo.getSourceRange().getEnd();
478 = MethodTyInfo->getType()->getAs<FunctionType>()->getResultType()
479 != Context.DependentTy;
481 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
482 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
483 // Empty arg list, don't push any params.
484 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
486 Params.reserve(FTI.NumArgs);
487 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
488 Params.push_back(cast<ParmVarDecl>(FTI.ArgInfo[i].Param));
491 // Check for unexpanded parameter packs in the method type.
492 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
493 ContainsUnexpandedParameterPack = true;
496 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
499 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
500 MethodTyInfo, EndLoc, Params);
503 CheckCXXDefaultArguments(Method);
505 // Attributes on the lambda apply to the method.
506 ProcessDeclAttributes(CurScope, Method, ParamInfo);
508 // Introduce the function call operator as the current declaration context.
509 PushDeclContext(CurScope, Method);
511 // Introduce the lambda scope.
513 = enterLambdaScope(Method, Intro.Range, Intro.Default, ExplicitParams,
517 // Handle explicit captures.
518 SourceLocation PrevCaptureLoc
519 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
520 for (SmallVector<LambdaCapture, 4>::const_iterator
521 C = Intro.Captures.begin(),
522 E = Intro.Captures.end();
524 PrevCaptureLoc = C->Loc, ++C) {
525 if (C->Kind == LCK_This) {
526 // C++11 [expr.prim.lambda]p8:
527 // An identifier or this shall not appear more than once in a
529 if (LSI->isCXXThisCaptured()) {
530 Diag(C->Loc, diag::err_capture_more_than_once)
532 << SourceRange(LSI->getCXXThisCapture().getLocation())
533 << FixItHint::CreateRemoval(
534 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
538 // C++11 [expr.prim.lambda]p8:
539 // If a lambda-capture includes a capture-default that is =, the
540 // lambda-capture shall not contain this [...].
541 if (Intro.Default == LCD_ByCopy) {
542 Diag(C->Loc, diag::err_this_capture_with_copy_default)
543 << FixItHint::CreateRemoval(
544 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
548 // C++11 [expr.prim.lambda]p12:
549 // If this is captured by a local lambda expression, its nearest
550 // enclosing function shall be a non-static member function.
551 QualType ThisCaptureType = getCurrentThisType();
552 if (ThisCaptureType.isNull()) {
553 Diag(C->Loc, diag::err_this_capture) << true;
557 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
561 assert(C->Id && "missing identifier for capture");
563 // C++11 [expr.prim.lambda]p8:
564 // If a lambda-capture includes a capture-default that is &, the
565 // identifiers in the lambda-capture shall not be preceded by &.
566 // If a lambda-capture includes a capture-default that is =, [...]
567 // each identifier it contains shall be preceded by &.
568 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
569 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
570 << FixItHint::CreateRemoval(
571 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
573 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
574 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
575 << FixItHint::CreateRemoval(
576 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
580 DeclarationNameInfo Name(C->Id, C->Loc);
581 LookupResult R(*this, Name, LookupOrdinaryName);
582 LookupName(R, CurScope);
586 // FIXME: Disable corrections that would add qualification?
587 CXXScopeSpec ScopeSpec;
588 DeclFilterCCC<VarDecl> Validator;
589 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
593 // C++11 [expr.prim.lambda]p10:
594 // The identifiers in a capture-list are looked up using the usual rules
595 // for unqualified name lookup (3.4.1); each such lookup shall find a
596 // variable with automatic storage duration declared in the reaching
597 // scope of the local lambda expression.
599 // Note that the 'reaching scope' check happens in tryCaptureVariable().
600 VarDecl *Var = R.getAsSingle<VarDecl>();
602 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
606 // Ignore invalid decls; they'll just confuse the code later.
607 if (Var->isInvalidDecl())
610 if (!Var->hasLocalStorage()) {
611 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
612 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
616 // C++11 [expr.prim.lambda]p8:
617 // An identifier or this shall not appear more than once in a
619 if (LSI->isCaptured(Var)) {
620 Diag(C->Loc, diag::err_capture_more_than_once)
622 << SourceRange(LSI->getCapture(Var).getLocation())
623 << FixItHint::CreateRemoval(
624 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
628 // C++11 [expr.prim.lambda]p23:
629 // A capture followed by an ellipsis is a pack expansion (14.5.3).
630 SourceLocation EllipsisLoc;
631 if (C->EllipsisLoc.isValid()) {
632 if (Var->isParameterPack()) {
633 EllipsisLoc = C->EllipsisLoc;
635 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
636 << SourceRange(C->Loc);
638 // Just ignore the ellipsis.
640 } else if (Var->isParameterPack()) {
641 ContainsUnexpandedParameterPack = true;
644 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
645 TryCapture_ExplicitByVal;
646 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
648 finishLambdaExplicitCaptures(LSI);
650 LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
652 // Add lambda parameters into scope.
653 addLambdaParameters(Method, CurScope);
655 // Enter a new evaluation context to insulate the lambda from any
656 // cleanups from the enclosing full-expression.
657 PushExpressionEvaluationContext(PotentiallyEvaluated);
660 void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
661 bool IsInstantiation) {
662 // Leave the expression-evaluation context.
663 DiscardCleanupsInEvaluationContext();
664 PopExpressionEvaluationContext();
666 // Leave the context of the lambda.
667 if (!IsInstantiation)
670 // Finalize the lambda.
671 LambdaScopeInfo *LSI = getCurLambda();
672 CXXRecordDecl *Class = LSI->Lambda;
673 Class->setInvalidDecl();
674 SmallVector<Decl*, 4> Fields;
675 for (RecordDecl::field_iterator i = Class->field_begin(),
676 e = Class->field_end(); i != e; ++i)
677 Fields.push_back(*i);
678 ActOnFields(0, Class->getLocation(), Class, Fields,
679 SourceLocation(), SourceLocation(), 0);
680 CheckCompletedCXXClass(Class);
682 PopFunctionScopeInfo();
685 /// \brief Add a lambda's conversion to function pointer, as described in
686 /// C++11 [expr.prim.lambda]p6.
687 static void addFunctionPointerConversion(Sema &S,
688 SourceRange IntroducerRange,
689 CXXRecordDecl *Class,
690 CXXMethodDecl *CallOperator) {
691 // Add the conversion to function pointer.
692 const FunctionProtoType *Proto
693 = CallOperator->getType()->getAs<FunctionProtoType>();
694 QualType FunctionPtrTy;
697 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
698 ExtInfo.TypeQuals = 0;
700 S.Context.getFunctionType(Proto->getResultType(),
701 ArrayRef<QualType>(Proto->arg_type_begin(),
702 Proto->getNumArgs()),
704 FunctionPtrTy = S.Context.getPointerType(FunctionTy);
707 FunctionProtoType::ExtProtoInfo ExtInfo;
708 ExtInfo.TypeQuals = Qualifiers::Const;
710 S.Context.getFunctionType(FunctionPtrTy, None, ExtInfo);
712 SourceLocation Loc = IntroducerRange.getBegin();
714 = S.Context.DeclarationNames.getCXXConversionFunctionName(
715 S.Context.getCanonicalType(FunctionPtrTy));
716 DeclarationNameLoc NameLoc;
717 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
719 CXXConversionDecl *Conversion
720 = CXXConversionDecl::Create(S.Context, Class, Loc,
721 DeclarationNameInfo(Name, Loc, NameLoc),
723 S.Context.getTrivialTypeSourceInfo(ConvTy,
725 /*isInline=*/false, /*isExplicit=*/false,
726 /*isConstexpr=*/false,
727 CallOperator->getBody()->getLocEnd());
728 Conversion->setAccess(AS_public);
729 Conversion->setImplicit(true);
730 Class->addDecl(Conversion);
732 // Add a non-static member function "__invoke" that will be the result of
734 Name = &S.Context.Idents.get("__invoke");
735 CXXMethodDecl *Invoke
736 = CXXMethodDecl::Create(S.Context, Class, Loc,
737 DeclarationNameInfo(Name, Loc), FunctionTy,
738 CallOperator->getTypeSourceInfo(),
739 SC_Static, /*IsInline=*/true,
740 /*IsConstexpr=*/false,
741 CallOperator->getBody()->getLocEnd());
742 SmallVector<ParmVarDecl *, 4> InvokeParams;
743 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
744 ParmVarDecl *From = CallOperator->getParamDecl(I);
745 InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
748 From->getIdentifier(),
750 From->getTypeSourceInfo(),
751 From->getStorageClass(),
754 Invoke->setParams(InvokeParams);
755 Invoke->setAccess(AS_private);
756 Invoke->setImplicit(true);
757 Class->addDecl(Invoke);
760 /// \brief Add a lambda's conversion to block pointer.
761 static void addBlockPointerConversion(Sema &S,
762 SourceRange IntroducerRange,
763 CXXRecordDecl *Class,
764 CXXMethodDecl *CallOperator) {
765 const FunctionProtoType *Proto
766 = CallOperator->getType()->getAs<FunctionProtoType>();
769 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
770 ExtInfo.TypeQuals = 0;
772 = S.Context.getFunctionType(Proto->getResultType(),
773 ArrayRef<QualType>(Proto->arg_type_begin(),
774 Proto->getNumArgs()),
776 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
779 FunctionProtoType::ExtProtoInfo ExtInfo;
780 ExtInfo.TypeQuals = Qualifiers::Const;
781 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ExtInfo);
783 SourceLocation Loc = IntroducerRange.getBegin();
785 = S.Context.DeclarationNames.getCXXConversionFunctionName(
786 S.Context.getCanonicalType(BlockPtrTy));
787 DeclarationNameLoc NameLoc;
788 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
789 CXXConversionDecl *Conversion
790 = CXXConversionDecl::Create(S.Context, Class, Loc,
791 DeclarationNameInfo(Name, Loc, NameLoc),
793 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
794 /*isInline=*/false, /*isExplicit=*/false,
795 /*isConstexpr=*/false,
796 CallOperator->getBody()->getLocEnd());
797 Conversion->setAccess(AS_public);
798 Conversion->setImplicit(true);
799 Class->addDecl(Conversion);
802 ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
804 bool IsInstantiation) {
805 // Collect information from the lambda scope.
806 SmallVector<LambdaExpr::Capture, 4> Captures;
807 SmallVector<Expr *, 4> CaptureInits;
808 LambdaCaptureDefault CaptureDefault;
809 CXXRecordDecl *Class;
810 CXXMethodDecl *CallOperator;
811 SourceRange IntroducerRange;
813 bool ExplicitResultType;
814 bool LambdaExprNeedsCleanups;
815 bool ContainsUnexpandedParameterPack;
816 SmallVector<VarDecl *, 4> ArrayIndexVars;
817 SmallVector<unsigned, 4> ArrayIndexStarts;
819 LambdaScopeInfo *LSI = getCurLambda();
820 CallOperator = LSI->CallOperator;
822 IntroducerRange = LSI->IntroducerRange;
823 ExplicitParams = LSI->ExplicitParams;
824 ExplicitResultType = !LSI->HasImplicitReturnType;
825 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
826 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
827 ArrayIndexVars.swap(LSI->ArrayIndexVars);
828 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
830 // Translate captures.
831 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
832 LambdaScopeInfo::Capture From = LSI->Captures[I];
833 assert(!From.isBlockCapture() && "Cannot capture __block variables");
834 bool IsImplicit = I >= LSI->NumExplicitCaptures;
836 // Handle 'this' capture.
837 if (From.isThisCapture()) {
838 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
841 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
842 getCurrentThisType(),
843 /*isImplicit=*/true));
847 VarDecl *Var = From.getVariable();
848 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
849 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
850 Kind, Var, From.getEllipsisLoc()));
851 CaptureInits.push_back(From.getCopyExpr());
854 switch (LSI->ImpCaptureStyle) {
855 case CapturingScopeInfo::ImpCap_None:
856 CaptureDefault = LCD_None;
859 case CapturingScopeInfo::ImpCap_LambdaByval:
860 CaptureDefault = LCD_ByCopy;
863 case CapturingScopeInfo::ImpCap_CapturedRegion:
864 case CapturingScopeInfo::ImpCap_LambdaByref:
865 CaptureDefault = LCD_ByRef;
868 case CapturingScopeInfo::ImpCap_Block:
869 llvm_unreachable("block capture in lambda");
873 // C++11 [expr.prim.lambda]p4:
874 // If a lambda-expression does not include a
875 // trailing-return-type, it is as if the trailing-return-type
876 // denotes the following type:
877 // FIXME: Assumes current resolution to core issue 975.
878 if (LSI->HasImplicitReturnType) {
879 deduceClosureReturnType(*LSI);
881 // - if there are no return statements in the
882 // compound-statement, or all return statements return
883 // either an expression of type void or no expression or
884 // braced-init-list, the type void;
885 if (LSI->ReturnType.isNull()) {
886 LSI->ReturnType = Context.VoidTy;
889 // Create a function type with the inferred return type.
890 const FunctionProtoType *Proto
891 = CallOperator->getType()->getAs<FunctionProtoType>();
893 = Context.getFunctionType(LSI->ReturnType,
894 ArrayRef<QualType>(Proto->arg_type_begin(),
895 Proto->getNumArgs()),
896 Proto->getExtProtoInfo());
897 CallOperator->setType(FunctionTy);
900 // C++ [expr.prim.lambda]p7:
901 // The lambda-expression's compound-statement yields the
902 // function-body (8.4) of the function call operator [...].
903 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
904 CallOperator->setLexicalDeclContext(Class);
905 Class->addDecl(CallOperator);
906 PopExpressionEvaluationContext();
908 // C++11 [expr.prim.lambda]p6:
909 // The closure type for a lambda-expression with no lambda-capture
910 // has a public non-virtual non-explicit const conversion function
911 // to pointer to function having the same parameter and return
912 // types as the closure type's function call operator.
913 if (Captures.empty() && CaptureDefault == LCD_None)
914 addFunctionPointerConversion(*this, IntroducerRange, Class,
918 // The closure type for a lambda-expression has a public non-virtual
919 // non-explicit const conversion function to a block pointer having the
920 // same parameter and return types as the closure type's function call
922 if (getLangOpts().Blocks && getLangOpts().ObjC1)
923 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
925 // Finalize the lambda class.
926 SmallVector<Decl*, 4> Fields;
927 for (RecordDecl::field_iterator i = Class->field_begin(),
928 e = Class->field_end(); i != e; ++i)
929 Fields.push_back(*i);
930 ActOnFields(0, Class->getLocation(), Class, Fields,
931 SourceLocation(), SourceLocation(), 0);
932 CheckCompletedCXXClass(Class);
935 if (LambdaExprNeedsCleanups)
936 ExprNeedsCleanups = true;
938 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
939 CaptureDefault, Captures,
940 ExplicitParams, ExplicitResultType,
941 CaptureInits, ArrayIndexVars,
942 ArrayIndexStarts, Body->getLocEnd(),
943 ContainsUnexpandedParameterPack);
945 // C++11 [expr.prim.lambda]p2:
946 // A lambda-expression shall not appear in an unevaluated operand
948 if (!CurContext->isDependentContext()) {
949 switch (ExprEvalContexts.back().Context) {
951 case UnevaluatedAbstract:
952 // We don't actually diagnose this case immediately, because we
953 // could be within a context where we might find out later that
954 // the expression is potentially evaluated (e.g., for typeid).
955 ExprEvalContexts.back().Lambdas.push_back(Lambda);
958 case ConstantEvaluated:
959 case PotentiallyEvaluated:
960 case PotentiallyEvaluatedIfUsed:
965 return MaybeBindToTemporary(Lambda);
968 ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
969 SourceLocation ConvLocation,
970 CXXConversionDecl *Conv,
972 // Make sure that the lambda call operator is marked used.
973 CXXRecordDecl *Lambda = Conv->getParent();
974 CXXMethodDecl *CallOperator
975 = cast<CXXMethodDecl>(
977 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
978 CallOperator->setReferenced();
979 CallOperator->setUsed();
981 ExprResult Init = PerformCopyInitialization(
982 InitializedEntity::InitializeBlock(ConvLocation,
985 CurrentLocation, Src);
986 if (!Init.isInvalid())
987 Init = ActOnFinishFullExpr(Init.take());
989 if (Init.isInvalid())
992 // Create the new block to be returned.
993 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
995 // Set the type information.
996 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
997 Block->setIsVariadic(CallOperator->isVariadic());
998 Block->setBlockMissingReturnType(false);
1001 SmallVector<ParmVarDecl *, 4> BlockParams;
1002 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1003 ParmVarDecl *From = CallOperator->getParamDecl(I);
1004 BlockParams.push_back(ParmVarDecl::Create(Context, Block,
1005 From->getLocStart(),
1006 From->getLocation(),
1007 From->getIdentifier(),
1009 From->getTypeSourceInfo(),
1010 From->getStorageClass(),
1013 Block->setParams(BlockParams);
1015 Block->setIsConversionFromLambda(true);
1017 // Add capture. The capture uses a fake variable, which doesn't correspond
1018 // to any actual memory location. However, the initializer copy-initializes
1019 // the lambda object.
1020 TypeSourceInfo *CapVarTSI =
1021 Context.getTrivialTypeSourceInfo(Src->getType());
1022 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1024 Src->getType(), CapVarTSI,
1026 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
1027 /*Nested=*/false, /*Copy=*/Init.take());
1028 Block->setCaptures(Context, &Capture, &Capture + 1,
1029 /*CapturesCXXThis=*/false);
1031 // Add a fake function body to the block. IR generation is responsible
1032 // for filling in the actual body, which cannot be expressed as an AST.
1033 Block->setBody(new (Context) CompoundStmt(ConvLocation));
1035 // Create the block literal expression.
1036 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1037 ExprCleanupObjects.push_back(Block);
1038 ExprNeedsCleanups = true;