SemaLambda.cpp revision 234287
133965Sjdp//===--- SemaLambda.cpp - Semantic Analysis for C++11 Lambdas -------------===// 238889Sjdp// 333965Sjdp// The LLVM Compiler Infrastructure 433965Sjdp// 533965Sjdp// This file is distributed under the University of Illinois Open Source 633965Sjdp// License. See LICENSE.TXT for details. 733965Sjdp// 833965Sjdp//===----------------------------------------------------------------------===// 933965Sjdp// 1033965Sjdp// This file implements semantic analysis for C++ lambda expressions. 1133965Sjdp// 1233965Sjdp//===----------------------------------------------------------------------===// 1333965Sjdp#include "clang/Sema/DeclSpec.h" 1433965Sjdp#include "clang/Sema/Initialization.h" 1533965Sjdp#include "clang/Sema/Lookup.h" 1633965Sjdp#include "clang/Sema/Scope.h" 1733965Sjdp#include "clang/Sema/ScopeInfo.h" 1833965Sjdp#include "clang/Sema/SemaInternal.h" 1933965Sjdp#include "clang/Lex/Preprocessor.h" 2033965Sjdp#include "clang/AST/ExprCXX.h" 2133965Sjdpusing namespace clang; 2233965Sjdpusing namespace sema; 2333965Sjdp 2433965SjdpCXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange, 2533965Sjdp bool KnownDependent) { 2633965Sjdp DeclContext *DC = CurContext; 2733965Sjdp while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext())) 2833965Sjdp DC = DC->getParent(); 2933965Sjdp 3033965Sjdp // Start constructing the lambda class. 3133965Sjdp CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, 3233965Sjdp IntroducerRange.getBegin(), 3333965Sjdp KnownDependent); 3433965Sjdp DC->addDecl(Class); 3533965Sjdp 3633965Sjdp return Class; 3733965Sjdp} 3833965Sjdp 3933965Sjdp/// \brief Determine whether the given context is or is enclosed in an inline 4033965Sjdp/// function. 4133965Sjdpstatic bool isInInlineFunction(const DeclContext *DC) { 4233965Sjdp while (!DC->isFileContext()) { 4333965Sjdp if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) 4433965Sjdp if (FD->isInlined()) 4533965Sjdp return true; 4633965Sjdp 4733965Sjdp DC = DC->getLexicalParent(); 4833965Sjdp } 4933965Sjdp 5033965Sjdp return false; 5133965Sjdp} 5233965Sjdp 5333965SjdpCXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class, 5433965Sjdp SourceRange IntroducerRange, 5533965Sjdp TypeSourceInfo *MethodType, 5633965Sjdp SourceLocation EndLoc, 5733965Sjdp llvm::ArrayRef<ParmVarDecl *> Params, 5833965Sjdp llvm::Optional<unsigned> ManglingNumber, 5933965Sjdp Decl *ContextDecl) { 6033965Sjdp // C++11 [expr.prim.lambda]p5: 6133965Sjdp // The closure type for a lambda-expression has a public inline function 6233965Sjdp // call operator (13.5.4) whose parameters and return type are described by 6333965Sjdp // the lambda-expression's parameter-declaration-clause and 6433965Sjdp // trailing-return-type respectively. 6533965Sjdp DeclarationName MethodName 6633965Sjdp = Context.DeclarationNames.getCXXOperatorName(OO_Call); 6733965Sjdp DeclarationNameLoc MethodNameLoc; 6833965Sjdp MethodNameLoc.CXXOperatorName.BeginOpNameLoc 6933965Sjdp = IntroducerRange.getBegin().getRawEncoding(); 7033965Sjdp MethodNameLoc.CXXOperatorName.EndOpNameLoc 7133965Sjdp = IntroducerRange.getEnd().getRawEncoding(); 7233965Sjdp CXXMethodDecl *Method 7333965Sjdp = CXXMethodDecl::Create(Context, Class, EndLoc, 7433965Sjdp DeclarationNameInfo(MethodName, 7533965Sjdp IntroducerRange.getBegin(), 7633965Sjdp MethodNameLoc), 7733965Sjdp MethodType->getType(), MethodType, 7833965Sjdp /*isStatic=*/false, 7933965Sjdp SC_None, 8033965Sjdp /*isInline=*/true, 8133965Sjdp /*isConstExpr=*/false, 8233965Sjdp EndLoc); 8333965Sjdp Method->setAccess(AS_public); 8433965Sjdp 8533965Sjdp // Temporarily set the lexical declaration context to the current 8633965Sjdp // context, so that the Scope stack matches the lexical nesting. 8733965Sjdp Method->setLexicalDeclContext(CurContext); 8833965Sjdp 8933965Sjdp // Add parameters. 9033965Sjdp if (!Params.empty()) { 9133965Sjdp Method->setParams(Params); 9233965Sjdp CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()), 9333965Sjdp const_cast<ParmVarDecl **>(Params.end()), 9433965Sjdp /*CheckParameterNames=*/false); 9533965Sjdp 9633965Sjdp for (CXXMethodDecl::param_iterator P = Method->param_begin(), 9733965Sjdp PEnd = Method->param_end(); 9833965Sjdp P != PEnd; ++P) 9933965Sjdp (*P)->setOwningFunction(Method); 10033965Sjdp } 10133965Sjdp 10233965Sjdp // If we don't already have a mangling number for this lambda expression, 10333965Sjdp // allocate one now. 10433965Sjdp if (!ManglingNumber) { 10560484Sobrien ContextDecl = ExprEvalContexts.back().LambdaContextDecl; 10633965Sjdp 10733965Sjdp enum ContextKind { 10833965Sjdp Normal, 10933965Sjdp DefaultArgument, 11033965Sjdp DataMember, 11133965Sjdp StaticDataMember 11233965Sjdp } Kind = Normal; 11333965Sjdp 11433965Sjdp // Default arguments of member function parameters that appear in a class 11533965Sjdp // definition, as well as the initializers of data members, receive special 11633965Sjdp // treatment. Identify them. 11733965Sjdp if (ContextDecl) { 11833965Sjdp if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ContextDecl)) { 11933965Sjdp if (const DeclContext *LexicalDC 12033965Sjdp = Param->getDeclContext()->getLexicalParent()) 12133965Sjdp if (LexicalDC->isRecord()) 12233965Sjdp Kind = DefaultArgument; 12333965Sjdp } else if (VarDecl *Var = dyn_cast<VarDecl>(ContextDecl)) { 12433965Sjdp if (Var->getDeclContext()->isRecord()) 12533965Sjdp Kind = StaticDataMember; 12633965Sjdp } else if (isa<FieldDecl>(ContextDecl)) { 12733965Sjdp Kind = DataMember; 12833965Sjdp } 12933965Sjdp } 13033965Sjdp 13133965Sjdp switch (Kind) { 13233965Sjdp case Normal: 13333965Sjdp if (CurContext->isDependentContext() || isInInlineFunction(CurContext)) 13433965Sjdp ManglingNumber = Context.getLambdaManglingNumber(Method); 13533965Sjdp else 13633965Sjdp ManglingNumber = 0; 13733965Sjdp 13833965Sjdp // There is no special context for this lambda. 13933965Sjdp ContextDecl = 0; 14033965Sjdp break; 14133965Sjdp 14233965Sjdp case StaticDataMember: 14333965Sjdp if (!CurContext->isDependentContext()) { 14433965Sjdp ManglingNumber = 0; 14533965Sjdp ContextDecl = 0; 14633965Sjdp break; 14733965Sjdp } 14833965Sjdp // Fall through to assign a mangling number. 14933965Sjdp 15033965Sjdp case DataMember: 15133965Sjdp case DefaultArgument: 15233965Sjdp ManglingNumber = ExprEvalContexts.back().getLambdaMangleContext() 15333965Sjdp .getManglingNumber(Method); 15433965Sjdp break; 15533965Sjdp } 15633965Sjdp } 15733965Sjdp 15833965Sjdp Class->setLambdaMangling(*ManglingNumber, ContextDecl); 15933965Sjdp return Method; 16033965Sjdp} 16133965Sjdp 16233965SjdpLambdaScopeInfo *Sema::enterLambdaScope(CXXMethodDecl *CallOperator, 16333965Sjdp SourceRange IntroducerRange, 16433965Sjdp LambdaCaptureDefault CaptureDefault, 16533965Sjdp bool ExplicitParams, 16633965Sjdp bool ExplicitResultType, 16733965Sjdp bool Mutable) { 16833965Sjdp PushLambdaScope(CallOperator->getParent(), CallOperator); 16933965Sjdp LambdaScopeInfo *LSI = getCurLambda(); 17033965Sjdp if (CaptureDefault == LCD_ByCopy) 17133965Sjdp LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval; 17233965Sjdp else if (CaptureDefault == LCD_ByRef) 17333965Sjdp LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref; 17433965Sjdp LSI->IntroducerRange = IntroducerRange; 17533965Sjdp LSI->ExplicitParams = ExplicitParams; 17633965Sjdp LSI->Mutable = Mutable; 17733965Sjdp 17833965Sjdp if (ExplicitResultType) { 17933965Sjdp LSI->ReturnType = CallOperator->getResultType(); 18033965Sjdp 18133965Sjdp if (!LSI->ReturnType->isDependentType() && 18233965Sjdp !LSI->ReturnType->isVoidType()) { 18333965Sjdp if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType, 18433965Sjdp diag::err_lambda_incomplete_result)) { 18533965Sjdp // Do nothing. 18633965Sjdp } else if (LSI->ReturnType->isObjCObjectOrInterfaceType()) { 18733965Sjdp Diag(CallOperator->getLocStart(), diag::err_lambda_objc_object_result) 18833965Sjdp << LSI->ReturnType; 18933965Sjdp } 19033965Sjdp } 19133965Sjdp } else { 19233965Sjdp LSI->HasImplicitReturnType = true; 19333965Sjdp } 19433965Sjdp 19533965Sjdp return LSI; 19633965Sjdp} 19733965Sjdp 19833965Sjdpvoid Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) { 19933965Sjdp LSI->finishedExplicitCaptures(); 20033965Sjdp} 20133965Sjdp 20233965Sjdpvoid Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) { 20333965Sjdp // Introduce our parameters into the function scope 20433965Sjdp for (unsigned p = 0, NumParams = CallOperator->getNumParams(); 20533965Sjdp p < NumParams; ++p) { 20633965Sjdp ParmVarDecl *Param = CallOperator->getParamDecl(p); 20733965Sjdp 20833965Sjdp // If this has an identifier, add it to the scope stack. 20933965Sjdp if (CurScope && Param->getIdentifier()) { 21033965Sjdp CheckShadow(CurScope, Param); 21133965Sjdp 21233965Sjdp PushOnScopeChains(Param, CurScope); 21333965Sjdp } 21433965Sjdp } 21533965Sjdp} 21633965Sjdp 21733965Sjdpvoid Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, 21833965Sjdp Declarator &ParamInfo, 21933965Sjdp Scope *CurScope) { 22033965Sjdp // Determine if we're within a context where we know that the lambda will 22133965Sjdp // be dependent, because there are template parameters in scope. 22260484Sobrien bool KnownDependent = false; 22333965Sjdp if (Scope *TmplScope = CurScope->getTemplateParamParent()) 22433965Sjdp if (!TmplScope->decl_empty()) 22533965Sjdp KnownDependent = true; 22633965Sjdp 22733965Sjdp CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, KnownDependent); 22833965Sjdp 22933965Sjdp // Determine the signature of the call operator. 23033965Sjdp TypeSourceInfo *MethodTyInfo; 23133965Sjdp bool ExplicitParams = true; 23233965Sjdp bool ExplicitResultType = true; 23333965Sjdp SourceLocation EndLoc; 23433965Sjdp llvm::ArrayRef<ParmVarDecl *> Params; 23533965Sjdp if (ParamInfo.getNumTypeObjects() == 0) { 23633965Sjdp // C++11 [expr.prim.lambda]p4: 23733965Sjdp // If a lambda-expression does not include a lambda-declarator, it is as 23833965Sjdp // if the lambda-declarator were (). 23933965Sjdp FunctionProtoType::ExtProtoInfo EPI; 24033965Sjdp EPI.HasTrailingReturn = true; 24133965Sjdp EPI.TypeQuals |= DeclSpec::TQ_const; 24233965Sjdp QualType MethodTy = Context.getFunctionType(Context.DependentTy, 24333965Sjdp /*Args=*/0, /*NumArgs=*/0, EPI); 24438889Sjdp MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy); 24533965Sjdp ExplicitParams = false; 24633965Sjdp ExplicitResultType = false; 24733965Sjdp EndLoc = Intro.Range.getEnd(); 24833965Sjdp } else { 24933965Sjdp assert(ParamInfo.isFunctionDeclarator() && 25033965Sjdp "lambda-declarator is a function"); 25133965Sjdp DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo(); 25233965Sjdp 25333965Sjdp // C++11 [expr.prim.lambda]p5: 25433965Sjdp // This function call operator is declared const (9.3.1) if and only if 25533965Sjdp // the lambda-expression's parameter-declaration-clause is not followed 25633965Sjdp // by mutable. It is neither virtual nor declared volatile. [...] 25733965Sjdp if (!FTI.hasMutableQualifier()) 25833965Sjdp FTI.TypeQuals |= DeclSpec::TQ_const; 25933965Sjdp 26033965Sjdp MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope); 26133965Sjdp assert(MethodTyInfo && "no type from lambda-declarator"); 26238889Sjdp EndLoc = ParamInfo.getSourceRange().getEnd(); 26333965Sjdp 26433965Sjdp ExplicitResultType 26533965Sjdp = MethodTyInfo->getType()->getAs<FunctionType>()->getResultType() 26633965Sjdp != Context.DependentTy; 26733965Sjdp 26833965Sjdp TypeLoc TL = MethodTyInfo->getTypeLoc(); 26933965Sjdp FunctionProtoTypeLoc Proto = cast<FunctionProtoTypeLoc>(TL); 27033965Sjdp Params = llvm::ArrayRef<ParmVarDecl *>(Proto.getParmArray(), 27133965Sjdp Proto.getNumArgs()); 27233965Sjdp } 27333965Sjdp 27433965Sjdp CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range, 27533965Sjdp MethodTyInfo, EndLoc, Params); 27633965Sjdp 27733965Sjdp if (ExplicitParams) 27833965Sjdp CheckCXXDefaultArguments(Method); 27933965Sjdp 28033965Sjdp // Attributes on the lambda apply to the method. 28133965Sjdp ProcessDeclAttributes(CurScope, Method, ParamInfo); 28233965Sjdp 28338889Sjdp // Introduce the function call operator as the current declaration context. 28433965Sjdp PushDeclContext(CurScope, Method); 28533965Sjdp 28633965Sjdp // Introduce the lambda scope. 28733965Sjdp LambdaScopeInfo *LSI 28833965Sjdp = enterLambdaScope(Method, Intro.Range, Intro.Default, ExplicitParams, 28933965Sjdp ExplicitResultType, 29033965Sjdp (Method->getTypeQualifiers() & Qualifiers::Const) == 0); 29133965Sjdp 29233965Sjdp // Handle explicit captures. 29333965Sjdp SourceLocation PrevCaptureLoc 29433965Sjdp = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc; 29533965Sjdp for (llvm::SmallVector<LambdaCapture, 4>::const_iterator 29633965Sjdp C = Intro.Captures.begin(), 29733965Sjdp E = Intro.Captures.end(); 29833965Sjdp C != E; 29933965Sjdp PrevCaptureLoc = C->Loc, ++C) { 30033965Sjdp if (C->Kind == LCK_This) { 30133965Sjdp // C++11 [expr.prim.lambda]p8: 30233965Sjdp // An identifier or this shall not appear more than once in a 30338889Sjdp // lambda-capture. 30433965Sjdp if (LSI->isCXXThisCaptured()) { 30533965Sjdp Diag(C->Loc, diag::err_capture_more_than_once) 30633965Sjdp << "'this'" 30733965Sjdp << SourceRange(LSI->getCXXThisCapture().getLocation()) 30833965Sjdp << FixItHint::CreateRemoval( 30933965Sjdp SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 31033965Sjdp continue; 31133965Sjdp } 31233965Sjdp 31333965Sjdp // C++11 [expr.prim.lambda]p8: 31433965Sjdp // If a lambda-capture includes a capture-default that is =, the 31533965Sjdp // lambda-capture shall not contain this [...]. 31633965Sjdp if (Intro.Default == LCD_ByCopy) { 31733965Sjdp Diag(C->Loc, diag::err_this_capture_with_copy_default) 31833965Sjdp << FixItHint::CreateRemoval( 31933965Sjdp SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 32033965Sjdp continue; 32133965Sjdp } 32233965Sjdp 32333965Sjdp // C++11 [expr.prim.lambda]p12: 32433965Sjdp // If this is captured by a local lambda expression, its nearest 32533965Sjdp // enclosing function shall be a non-static member function. 32633965Sjdp QualType ThisCaptureType = getCurrentThisType(); 32733965Sjdp if (ThisCaptureType.isNull()) { 32833965Sjdp Diag(C->Loc, diag::err_this_capture) << true; 32933965Sjdp continue; 33033965Sjdp } 33160484Sobrien 33233965Sjdp CheckCXXThisCapture(C->Loc, /*Explicit=*/true); 33333965Sjdp continue; 33433965Sjdp } 33533965Sjdp 33633965Sjdp assert(C->Id && "missing identifier for capture"); 33733965Sjdp 33833965Sjdp // C++11 [expr.prim.lambda]p8: 33933965Sjdp // If a lambda-capture includes a capture-default that is &, the 34033965Sjdp // identifiers in the lambda-capture shall not be preceded by &. 34133965Sjdp // If a lambda-capture includes a capture-default that is =, [...] 34233965Sjdp // each identifier it contains shall be preceded by &. 34333965Sjdp if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) { 34433965Sjdp Diag(C->Loc, diag::err_reference_capture_with_reference_default) 34533965Sjdp << FixItHint::CreateRemoval( 34633965Sjdp SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 34733965Sjdp continue; 34833965Sjdp } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) { 34933965Sjdp Diag(C->Loc, diag::err_copy_capture_with_copy_default) 35033965Sjdp << FixItHint::CreateRemoval( 35133965Sjdp SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 35233965Sjdp continue; 35338889Sjdp } 35433965Sjdp 35533965Sjdp DeclarationNameInfo Name(C->Id, C->Loc); 35633965Sjdp LookupResult R(*this, Name, LookupOrdinaryName); 35733965Sjdp LookupName(R, CurScope); 35833965Sjdp if (R.isAmbiguous()) 35933965Sjdp continue; 36033965Sjdp if (R.empty()) { 36133965Sjdp // FIXME: Disable corrections that would add qualification? 36233965Sjdp CXXScopeSpec ScopeSpec; 36333965Sjdp DeclFilterCCC<VarDecl> Validator; 36433965Sjdp if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator)) 36533965Sjdp continue; 36633965Sjdp } 36733965Sjdp 36833965Sjdp // C++11 [expr.prim.lambda]p10: 36933965Sjdp // The identifiers in a capture-list are looked up using the usual rules 37038889Sjdp // for unqualified name lookup (3.4.1); each such lookup shall find a 37133965Sjdp // variable with automatic storage duration declared in the reaching 37233965Sjdp // scope of the local lambda expression. 37333965Sjdp // 37433965Sjdp // Note that the 'reaching scope' check happens in tryCaptureVariable(). 37533965Sjdp VarDecl *Var = R.getAsSingle<VarDecl>(); 37633965Sjdp if (!Var) { 37733965Sjdp Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id; 37833965Sjdp continue; 37933965Sjdp } 38033965Sjdp 38133965Sjdp if (!Var->hasLocalStorage()) { 38233965Sjdp Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id; 38333965Sjdp Diag(Var->getLocation(), diag::note_previous_decl) << C->Id; 38433965Sjdp continue; 38533965Sjdp } 38633965Sjdp 38733965Sjdp // C++11 [expr.prim.lambda]p8: 38833965Sjdp // An identifier or this shall not appear more than once in a 38938889Sjdp // lambda-capture. 39033965Sjdp if (LSI->isCaptured(Var)) { 39133965Sjdp Diag(C->Loc, diag::err_capture_more_than_once) 39233965Sjdp << C->Id 39333965Sjdp << SourceRange(LSI->getCapture(Var).getLocation()) 39433965Sjdp << FixItHint::CreateRemoval( 39533965Sjdp SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc)); 39633965Sjdp continue; 39733965Sjdp } 39833965Sjdp 39933965Sjdp // C++11 [expr.prim.lambda]p23: 40033965Sjdp // A capture followed by an ellipsis is a pack expansion (14.5.3). 40133965Sjdp SourceLocation EllipsisLoc; 40233965Sjdp if (C->EllipsisLoc.isValid()) { 40333965Sjdp if (Var->isParameterPack()) { 40433965Sjdp EllipsisLoc = C->EllipsisLoc; 40533965Sjdp } else { 40633965Sjdp Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) 40733965Sjdp << SourceRange(C->Loc); 40838889Sjdp 40933965Sjdp // Just ignore the ellipsis. 41033965Sjdp } 41133965Sjdp } else if (Var->isParameterPack()) { 41233965Sjdp Diag(C->Loc, diag::err_lambda_unexpanded_pack); 41333965Sjdp continue; 41433965Sjdp } 41533965Sjdp 41633965Sjdp TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef : 41733965Sjdp TryCapture_ExplicitByVal; 41833965Sjdp tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc); 41933965Sjdp } 42033965Sjdp finishLambdaExplicitCaptures(LSI); 42133965Sjdp 42233965Sjdp // Add lambda parameters into scope. 42333965Sjdp addLambdaParameters(Method, CurScope); 42433965Sjdp 42533965Sjdp // Enter a new evaluation context to insulate the lambda from any 42633965Sjdp // cleanups from the enclosing full-expression. 42733965Sjdp PushExpressionEvaluationContext(PotentiallyEvaluated); 42833965Sjdp} 42933965Sjdp 43033965Sjdpvoid Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, 43133965Sjdp bool IsInstantiation) { 43233965Sjdp // Leave the expression-evaluation context. 43333965Sjdp DiscardCleanupsInEvaluationContext(); 43433965Sjdp PopExpressionEvaluationContext(); 43560484Sobrien 43633965Sjdp // Leave the context of the lambda. 43733965Sjdp if (!IsInstantiation) 43833965Sjdp PopDeclContext(); 43933965Sjdp 44033965Sjdp // Finalize the lambda. 44133965Sjdp LambdaScopeInfo *LSI = getCurLambda(); 44233965Sjdp CXXRecordDecl *Class = LSI->Lambda; 44333965Sjdp Class->setInvalidDecl(); 44433965Sjdp SmallVector<Decl*, 4> Fields(Class->field_begin(), Class->field_end()); 44533965Sjdp ActOnFields(0, Class->getLocation(), Class, Fields, 44633965Sjdp SourceLocation(), SourceLocation(), 0); 44733965Sjdp CheckCompletedCXXClass(Class); 44833965Sjdp 44933965Sjdp PopFunctionScopeInfo(); 45033965Sjdp} 45133965Sjdp 45260484Sobrien/// \brief Add a lambda's conversion to function pointer, as described in 45333965Sjdp/// C++11 [expr.prim.lambda]p6. 45433965Sjdpstatic void addFunctionPointerConversion(Sema &S, 45533965Sjdp SourceRange IntroducerRange, 45633965Sjdp CXXRecordDecl *Class, 45733965Sjdp CXXMethodDecl *CallOperator) { 45833965Sjdp // Add the conversion to function pointer. 45933965Sjdp const FunctionProtoType *Proto 46033965Sjdp = CallOperator->getType()->getAs<FunctionProtoType>(); 46133965Sjdp QualType FunctionPtrTy; 46233965Sjdp QualType FunctionTy; 46333965Sjdp { 46433965Sjdp FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo(); 46533965Sjdp ExtInfo.TypeQuals = 0; 46633965Sjdp FunctionTy = S.Context.getFunctionType(Proto->getResultType(), 46733965Sjdp Proto->arg_type_begin(), 46833965Sjdp Proto->getNumArgs(), 46933965Sjdp ExtInfo); 47033965Sjdp FunctionPtrTy = S.Context.getPointerType(FunctionTy); 47160484Sobrien } 47233965Sjdp 47360484Sobrien FunctionProtoType::ExtProtoInfo ExtInfo; 47460484Sobrien ExtInfo.TypeQuals = Qualifiers::Const; 47560484Sobrien QualType ConvTy = S.Context.getFunctionType(FunctionPtrTy, 0, 0, ExtInfo); 47660484Sobrien 47760484Sobrien SourceLocation Loc = IntroducerRange.getBegin(); 47833965Sjdp DeclarationName Name 47933965Sjdp = S.Context.DeclarationNames.getCXXConversionFunctionName( 48033965Sjdp S.Context.getCanonicalType(FunctionPtrTy)); 48133965Sjdp DeclarationNameLoc NameLoc; 48233965Sjdp NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy, 48333965Sjdp Loc); 48433965Sjdp CXXConversionDecl *Conversion 48533965Sjdp = CXXConversionDecl::Create(S.Context, Class, Loc, 48633965Sjdp DeclarationNameInfo(Name, Loc, NameLoc), 48733965Sjdp ConvTy, 48833965Sjdp S.Context.getTrivialTypeSourceInfo(ConvTy, 48933965Sjdp Loc), 49060484Sobrien /*isInline=*/false, /*isExplicit=*/false, 49160484Sobrien /*isConstexpr=*/false, 49260484Sobrien CallOperator->getBody()->getLocEnd()); 49360484Sobrien Conversion->setAccess(AS_public); 49460484Sobrien Conversion->setImplicit(true); 49560484Sobrien Class->addDecl(Conversion); 49633965Sjdp 49733965Sjdp // Add a non-static member function "__invoke" that will be the result of 49833965Sjdp // the conversion. 49933965Sjdp Name = &S.Context.Idents.get("__invoke"); 50033965Sjdp CXXMethodDecl *Invoke 50133965Sjdp = CXXMethodDecl::Create(S.Context, Class, Loc, 50233965Sjdp DeclarationNameInfo(Name, Loc), FunctionTy, 50333965Sjdp CallOperator->getTypeSourceInfo(), 50433965Sjdp /*IsStatic=*/true, SC_Static, /*IsInline=*/true, 50533965Sjdp /*IsConstexpr=*/false, 50633965Sjdp CallOperator->getBody()->getLocEnd()); 50733965Sjdp SmallVector<ParmVarDecl *, 4> InvokeParams; 50833965Sjdp for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) { 50933965Sjdp ParmVarDecl *From = CallOperator->getParamDecl(I); 51033965Sjdp InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke, 51133965Sjdp From->getLocStart(), 51233965Sjdp From->getLocation(), 51333965Sjdp From->getIdentifier(), 51433965Sjdp From->getType(), 51533965Sjdp From->getTypeSourceInfo(), 51633965Sjdp From->getStorageClass(), 51733965Sjdp From->getStorageClassAsWritten(), 51833965Sjdp /*DefaultArg=*/0)); 51933965Sjdp } 52033965Sjdp Invoke->setParams(InvokeParams); 52133965Sjdp Invoke->setAccess(AS_private); 52233965Sjdp Invoke->setImplicit(true); 52333965Sjdp Class->addDecl(Invoke); 52433965Sjdp} 52533965Sjdp 52633965Sjdp/// \brief Add a lambda's conversion to block pointer. 52733965Sjdpstatic void addBlockPointerConversion(Sema &S, 52833965Sjdp SourceRange IntroducerRange, 52933965Sjdp CXXRecordDecl *Class, 53033965Sjdp CXXMethodDecl *CallOperator) { 53133965Sjdp const FunctionProtoType *Proto 53233965Sjdp = CallOperator->getType()->getAs<FunctionProtoType>(); 53333965Sjdp QualType BlockPtrTy; 53433965Sjdp { 53533965Sjdp FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo(); 53633965Sjdp ExtInfo.TypeQuals = 0; 53733965Sjdp QualType FunctionTy 53833965Sjdp = S.Context.getFunctionType(Proto->getResultType(), 53933965Sjdp Proto->arg_type_begin(), 54033965Sjdp Proto->getNumArgs(), 54133965Sjdp ExtInfo); 542 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy); 543 } 544 545 FunctionProtoType::ExtProtoInfo ExtInfo; 546 ExtInfo.TypeQuals = Qualifiers::Const; 547 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, 0, 0, ExtInfo); 548 549 SourceLocation Loc = IntroducerRange.getBegin(); 550 DeclarationName Name 551 = S.Context.DeclarationNames.getCXXConversionFunctionName( 552 S.Context.getCanonicalType(BlockPtrTy)); 553 DeclarationNameLoc NameLoc; 554 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc); 555 CXXConversionDecl *Conversion 556 = CXXConversionDecl::Create(S.Context, Class, Loc, 557 DeclarationNameInfo(Name, Loc, NameLoc), 558 ConvTy, 559 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc), 560 /*isInline=*/false, /*isExplicit=*/false, 561 /*isConstexpr=*/false, 562 CallOperator->getBody()->getLocEnd()); 563 Conversion->setAccess(AS_public); 564 Conversion->setImplicit(true); 565 Class->addDecl(Conversion); 566} 567 568ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, 569 Scope *CurScope, 570 bool IsInstantiation) { 571 // Collect information from the lambda scope. 572 llvm::SmallVector<LambdaExpr::Capture, 4> Captures; 573 llvm::SmallVector<Expr *, 4> CaptureInits; 574 LambdaCaptureDefault CaptureDefault; 575 CXXRecordDecl *Class; 576 CXXMethodDecl *CallOperator; 577 SourceRange IntroducerRange; 578 bool ExplicitParams; 579 bool ExplicitResultType; 580 bool LambdaExprNeedsCleanups; 581 llvm::SmallVector<VarDecl *, 4> ArrayIndexVars; 582 llvm::SmallVector<unsigned, 4> ArrayIndexStarts; 583 { 584 LambdaScopeInfo *LSI = getCurLambda(); 585 CallOperator = LSI->CallOperator; 586 Class = LSI->Lambda; 587 IntroducerRange = LSI->IntroducerRange; 588 ExplicitParams = LSI->ExplicitParams; 589 ExplicitResultType = !LSI->HasImplicitReturnType; 590 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups; 591 ArrayIndexVars.swap(LSI->ArrayIndexVars); 592 ArrayIndexStarts.swap(LSI->ArrayIndexStarts); 593 594 // Translate captures. 595 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) { 596 LambdaScopeInfo::Capture From = LSI->Captures[I]; 597 assert(!From.isBlockCapture() && "Cannot capture __block variables"); 598 bool IsImplicit = I >= LSI->NumExplicitCaptures; 599 600 // Handle 'this' capture. 601 if (From.isThisCapture()) { 602 Captures.push_back(LambdaExpr::Capture(From.getLocation(), 603 IsImplicit, 604 LCK_This)); 605 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(), 606 getCurrentThisType(), 607 /*isImplicit=*/true)); 608 continue; 609 } 610 611 VarDecl *Var = From.getVariable(); 612 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef; 613 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit, 614 Kind, Var, From.getEllipsisLoc())); 615 CaptureInits.push_back(From.getCopyExpr()); 616 } 617 618 switch (LSI->ImpCaptureStyle) { 619 case CapturingScopeInfo::ImpCap_None: 620 CaptureDefault = LCD_None; 621 break; 622 623 case CapturingScopeInfo::ImpCap_LambdaByval: 624 CaptureDefault = LCD_ByCopy; 625 break; 626 627 case CapturingScopeInfo::ImpCap_LambdaByref: 628 CaptureDefault = LCD_ByRef; 629 break; 630 631 case CapturingScopeInfo::ImpCap_Block: 632 llvm_unreachable("block capture in lambda"); 633 break; 634 } 635 636 // C++11 [expr.prim.lambda]p4: 637 // If a lambda-expression does not include a 638 // trailing-return-type, it is as if the trailing-return-type 639 // denotes the following type: 640 // FIXME: Assumes current resolution to core issue 975. 641 if (LSI->HasImplicitReturnType) { 642 // - if there are no return statements in the 643 // compound-statement, or all return statements return 644 // either an expression of type void or no expression or 645 // braced-init-list, the type void; 646 if (LSI->ReturnType.isNull()) { 647 LSI->ReturnType = Context.VoidTy; 648 } else { 649 // C++11 [expr.prim.lambda]p4: 650 // - if the compound-statement is of the form 651 // 652 // { attribute-specifier-seq[opt] return expression ; } 653 // 654 // the type of the returned expression after 655 // lvalue-to-rvalue conversion (4.1), array-to-pointer 656 // conver- sion (4.2), and function-to-pointer conversion 657 // (4.3); 658 // 659 // Since we're accepting the resolution to a post-C++11 core 660 // issue with a non-trivial extension, provide a warning (by 661 // default). 662 CompoundStmt *CompoundBody = cast<CompoundStmt>(Body); 663 if (!(CompoundBody->size() == 1 && 664 isa<ReturnStmt>(*CompoundBody->body_begin())) && 665 !Context.hasSameType(LSI->ReturnType, Context.VoidTy)) 666 Diag(IntroducerRange.getBegin(), 667 diag::ext_lambda_implies_void_return); 668 } 669 670 // Create a function type with the inferred return type. 671 const FunctionProtoType *Proto 672 = CallOperator->getType()->getAs<FunctionProtoType>(); 673 QualType FunctionTy 674 = Context.getFunctionType(LSI->ReturnType, 675 Proto->arg_type_begin(), 676 Proto->getNumArgs(), 677 Proto->getExtProtoInfo()); 678 CallOperator->setType(FunctionTy); 679 } 680 681 // C++ [expr.prim.lambda]p7: 682 // The lambda-expression's compound-statement yields the 683 // function-body (8.4) of the function call operator [...]. 684 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation); 685 CallOperator->setLexicalDeclContext(Class); 686 Class->addDecl(CallOperator); 687 PopExpressionEvaluationContext(); 688 689 // C++11 [expr.prim.lambda]p6: 690 // The closure type for a lambda-expression with no lambda-capture 691 // has a public non-virtual non-explicit const conversion function 692 // to pointer to function having the same parameter and return 693 // types as the closure type's function call operator. 694 if (Captures.empty() && CaptureDefault == LCD_None) 695 addFunctionPointerConversion(*this, IntroducerRange, Class, 696 CallOperator); 697 698 // Objective-C++: 699 // The closure type for a lambda-expression has a public non-virtual 700 // non-explicit const conversion function to a block pointer having the 701 // same parameter and return types as the closure type's function call 702 // operator. 703 if (getLangOpts().Blocks && getLangOpts().ObjC1) 704 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator); 705 706 // Finalize the lambda class. 707 SmallVector<Decl*, 4> Fields(Class->field_begin(), Class->field_end()); 708 ActOnFields(0, Class->getLocation(), Class, Fields, 709 SourceLocation(), SourceLocation(), 0); 710 CheckCompletedCXXClass(Class); 711 } 712 713 if (LambdaExprNeedsCleanups) 714 ExprNeedsCleanups = true; 715 716 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange, 717 CaptureDefault, Captures, 718 ExplicitParams, ExplicitResultType, 719 CaptureInits, ArrayIndexVars, 720 ArrayIndexStarts, Body->getLocEnd()); 721 722 // C++11 [expr.prim.lambda]p2: 723 // A lambda-expression shall not appear in an unevaluated operand 724 // (Clause 5). 725 if (!CurContext->isDependentContext()) { 726 switch (ExprEvalContexts.back().Context) { 727 case Unevaluated: 728 // We don't actually diagnose this case immediately, because we 729 // could be within a context where we might find out later that 730 // the expression is potentially evaluated (e.g., for typeid). 731 ExprEvalContexts.back().Lambdas.push_back(Lambda); 732 break; 733 734 case ConstantEvaluated: 735 case PotentiallyEvaluated: 736 case PotentiallyEvaluatedIfUsed: 737 break; 738 } 739 } 740 741 return MaybeBindToTemporary(Lambda); 742} 743 744ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation, 745 SourceLocation ConvLocation, 746 CXXConversionDecl *Conv, 747 Expr *Src) { 748 // Make sure that the lambda call operator is marked used. 749 CXXRecordDecl *Lambda = Conv->getParent(); 750 CXXMethodDecl *CallOperator 751 = cast<CXXMethodDecl>( 752 *Lambda->lookup( 753 Context.DeclarationNames.getCXXOperatorName(OO_Call)).first); 754 CallOperator->setReferenced(); 755 CallOperator->setUsed(); 756 757 ExprResult Init = PerformCopyInitialization( 758 InitializedEntity::InitializeBlock(ConvLocation, 759 Src->getType(), 760 /*NRVO=*/false), 761 CurrentLocation, Src); 762 if (!Init.isInvalid()) 763 Init = ActOnFinishFullExpr(Init.take()); 764 765 if (Init.isInvalid()) 766 return ExprError(); 767 768 // Create the new block to be returned. 769 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation); 770 771 // Set the type information. 772 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo()); 773 Block->setIsVariadic(CallOperator->isVariadic()); 774 Block->setBlockMissingReturnType(false); 775 776 // Add parameters. 777 SmallVector<ParmVarDecl *, 4> BlockParams; 778 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) { 779 ParmVarDecl *From = CallOperator->getParamDecl(I); 780 BlockParams.push_back(ParmVarDecl::Create(Context, Block, 781 From->getLocStart(), 782 From->getLocation(), 783 From->getIdentifier(), 784 From->getType(), 785 From->getTypeSourceInfo(), 786 From->getStorageClass(), 787 From->getStorageClassAsWritten(), 788 /*DefaultArg=*/0)); 789 } 790 Block->setParams(BlockParams); 791 792 Block->setIsConversionFromLambda(true); 793 794 // Add capture. The capture uses a fake variable, which doesn't correspond 795 // to any actual memory location. However, the initializer copy-initializes 796 // the lambda object. 797 TypeSourceInfo *CapVarTSI = 798 Context.getTrivialTypeSourceInfo(Src->getType()); 799 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation, 800 ConvLocation, 0, 801 Src->getType(), CapVarTSI, 802 SC_None, SC_None); 803 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false, 804 /*Nested=*/false, /*Copy=*/Init.take()); 805 Block->setCaptures(Context, &Capture, &Capture + 1, 806 /*CapturesCXXThis=*/false); 807 808 // Add a fake function body to the block. IR generation is responsible 809 // for filling in the actual body, which cannot be expressed as an AST. 810 Block->setBody(new (Context) CompoundStmt(Context, 0, 0, 811 ConvLocation, 812 ConvLocation)); 813 814 // Create the block literal expression. 815 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType()); 816 ExprCleanupObjects.push_back(Block); 817 ExprNeedsCleanups = true; 818 819 return BuildBlock; 820} 821