Home | History | Annotate | Download | only in Sema
      1 //===--- SemaLambda.cpp - Semantic Analysis for C++11 Lambdas -------------===//
      2 //
      3 //                     The LLVM Compiler Infrastructure
      4 //
      5 // This file is distributed under the University of Illinois Open Source
      6 // License. See LICENSE.TXT for details.
      7 //
      8 //===----------------------------------------------------------------------===//
      9 //
     10 //  This file implements semantic analysis for C++ lambda expressions.
     11 //
     12 //===----------------------------------------------------------------------===//
     13 #include "clang/Sema/DeclSpec.h"
     14 #include "clang/Sema/Initialization.h"
     15 #include "clang/Sema/Lookup.h"
     16 #include "clang/Sema/Scope.h"
     17 #include "clang/Sema/ScopeInfo.h"
     18 #include "clang/Sema/SemaInternal.h"
     19 #include "clang/Lex/Preprocessor.h"
     20 #include "clang/AST/ExprCXX.h"
     21 using namespace clang;
     22 using namespace sema;
     23 
     24 CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
     25                                              bool KnownDependent) {
     26   DeclContext *DC = CurContext;
     27   while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
     28     DC = DC->getParent();
     29 
     30   // Start constructing the lambda class.
     31   CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC,
     32                                                      IntroducerRange.getBegin(),
     33                                                      KnownDependent);
     34   DC->addDecl(Class);
     35 
     36   return Class;
     37 }
     38 
     39 /// \brief Determine whether the given context is or is enclosed in an inline
     40 /// function.
     41 static bool isInInlineFunction(const DeclContext *DC) {
     42   while (!DC->isFileContext()) {
     43     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
     44       if (FD->isInlined())
     45         return true;
     46 
     47     DC = DC->getLexicalParent();
     48   }
     49 
     50   return false;
     51 }
     52 
     53 CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
     54                  SourceRange IntroducerRange,
     55                  TypeSourceInfo *MethodType,
     56                  SourceLocation EndLoc,
     57                  llvm::ArrayRef<ParmVarDecl *> Params) {
     58   // C++11 [expr.prim.lambda]p5:
     59   //   The closure type for a lambda-expression has a public inline function
     60   //   call operator (13.5.4) whose parameters and return type are described by
     61   //   the lambda-expression's parameter-declaration-clause and
     62   //   trailing-return-type respectively.
     63   DeclarationName MethodName
     64     = Context.DeclarationNames.getCXXOperatorName(OO_Call);
     65   DeclarationNameLoc MethodNameLoc;
     66   MethodNameLoc.CXXOperatorName.BeginOpNameLoc
     67     = IntroducerRange.getBegin().getRawEncoding();
     68   MethodNameLoc.CXXOperatorName.EndOpNameLoc
     69     = IntroducerRange.getEnd().getRawEncoding();
     70   CXXMethodDecl *Method
     71     = CXXMethodDecl::Create(Context, Class, EndLoc,
     72                             DeclarationNameInfo(MethodName,
     73                                                 IntroducerRange.getBegin(),
     74                                                 MethodNameLoc),
     75                             MethodType->getType(), MethodType,
     76                             /*isStatic=*/false,
     77                             SC_None,
     78                             /*isInline=*/true,
     79                             /*isConstExpr=*/false,
     80                             EndLoc);
     81   Method->setAccess(AS_public);
     82 
     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);
     86 
     87   // Add parameters.
     88   if (!Params.empty()) {
     89     Method->setParams(Params);
     90     CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
     91                              const_cast<ParmVarDecl **>(Params.end()),
     92                              /*CheckParameterNames=*/false);
     93 
     94     for (CXXMethodDecl::param_iterator P = Method->param_begin(),
     95                                     PEnd = Method->param_end();
     96          P != PEnd; ++P)
     97       (*P)->setOwningFunction(Method);
     98   }
     99 
    100   // Allocate a mangling number for this lambda expression, if the ABI
    101   // requires one.
    102   Decl *ContextDecl = ExprEvalContexts.back().LambdaContextDecl;
    103 
    104   enum ContextKind {
    105     Normal,
    106     DefaultArgument,
    107     DataMember,
    108     StaticDataMember
    109   } Kind = Normal;
    110 
    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.
    114   if (ContextDecl) {
    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)) {
    124       Kind = DataMember;
    125     }
    126   }
    127 
    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;
    134   switch (Kind) {
    135   case Normal:
    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);
    142     else
    143       ManglingNumber = 0;
    144 
    145     // There is no special context for this lambda.
    146     ContextDecl = 0;
    147     break;
    148 
    149   case StaticDataMember:
    150     //  -- the initializers of nonspecialized static members of template classes
    151     if (!IsInNonspecializedTemplate) {
    152       ManglingNumber = 0;
    153       ContextDecl = 0;
    154       break;
    155     }
    156     // Fall through to assign a mangling number.
    157 
    158   case DataMember:
    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);
    164     break;
    165   }
    166 
    167   Class->setLambdaMangling(ManglingNumber, ContextDecl);
    168 
    169   return Method;
    170 }
    171 
    172 LambdaScopeInfo *Sema::enterLambdaScope(CXXMethodDecl *CallOperator,
    173                                         SourceRange IntroducerRange,
    174                                         LambdaCaptureDefault CaptureDefault,
    175                                         bool ExplicitParams,
    176                                         bool ExplicitResultType,
    177                                         bool Mutable) {
    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;
    187 
    188   if (ExplicitResultType) {
    189     LSI->ReturnType = CallOperator->getResultType();
    190 
    191     if (!LSI->ReturnType->isDependentType() &&
    192         !LSI->ReturnType->isVoidType()) {
    193       if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
    194                               diag::err_lambda_incomplete_result)) {
    195         // Do nothing.
    196       } else if (LSI->ReturnType->isObjCObjectOrInterfaceType()) {
    197         Diag(CallOperator->getLocStart(), diag::err_lambda_objc_object_result)
    198           << LSI->ReturnType;
    199       }
    200     }
    201   } else {
    202     LSI->HasImplicitReturnType = true;
    203   }
    204 
    205   return LSI;
    206 }
    207 
    208 void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
    209   LSI->finishedExplicitCaptures();
    210 }
    211 
    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);
    217 
    218     // If this has an identifier, add it to the scope stack.
    219     if (CurScope && Param->getIdentifier()) {
    220       CheckShadow(CurScope, Param);
    221 
    222       PushOnScopeChains(Param, CurScope);
    223     }
    224   }
    225 }
    226 
    227 static bool checkReturnValueType(const ASTContext &Ctx, const Expr *E,
    228                                  QualType &DeducedType,
    229                                  QualType &AlternateType) {
    230   // Handle ReturnStmts with no expressions.
    231   if (!E) {
    232     if (AlternateType.isNull())
    233       AlternateType = Ctx.VoidTy;
    234 
    235     return Ctx.hasSameType(DeducedType, Ctx.VoidTy);
    236   }
    237 
    238   QualType StrictType = E->getType();
    239   QualType LooseType = StrictType;
    240 
    241   // In C, enum constants have the type of their underlying integer type,
    242   // not the enum. When inferring block return types, we should allow
    243   // the enum type if an enum constant is used, unless the enum is
    244   // anonymous (in which case there can be no variables of its type).
    245   if (!Ctx.getLangOpts().CPlusPlus) {
    246     const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E->IgnoreParenImpCasts());
    247     if (DRE) {
    248       const Decl *D = DRE->getDecl();
    249       if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
    250         const EnumDecl *Enum = cast<EnumDecl>(ECD->getDeclContext());
    251         if (Enum->getDeclName() || Enum->getTypedefNameForAnonDecl())
    252           LooseType = Ctx.getTypeDeclType(Enum);
    253       }
    254     }
    255   }
    256 
    257   // Special case for the first return statement we find.
    258   // The return type has already been tentatively set, but we might still
    259   // have an alternate type we should prefer.
    260   if (AlternateType.isNull())
    261     AlternateType = LooseType;
    262 
    263   if (Ctx.hasSameType(DeducedType, StrictType)) {
    264     // FIXME: The loose type is different when there are constants from two
    265     // different enums. We could consider warning here.
    266     if (AlternateType != Ctx.DependentTy)
    267       if (!Ctx.hasSameType(AlternateType, LooseType))
    268         AlternateType = Ctx.VoidTy;
    269     return true;
    270   }
    271 
    272   if (Ctx.hasSameType(DeducedType, LooseType)) {
    273     // Use DependentTy to signal that we're using an alternate type and may
    274     // need to add casts somewhere.
    275     AlternateType = Ctx.DependentTy;
    276     return true;
    277   }
    278 
    279   if (Ctx.hasSameType(AlternateType, StrictType) ||
    280       Ctx.hasSameType(AlternateType, LooseType)) {
    281     DeducedType = AlternateType;
    282     // Use DependentTy to signal that we're using an alternate type and may
    283     // need to add casts somewhere.
    284     AlternateType = Ctx.DependentTy;
    285     return true;
    286   }
    287 
    288   return false;
    289 }
    290 
    291 void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
    292   assert(CSI.HasImplicitReturnType);
    293 
    294   // First case: no return statements, implicit void return type.
    295   ASTContext &Ctx = getASTContext();
    296   if (CSI.Returns.empty()) {
    297     // It's possible there were simply no /valid/ return statements.
    298     // In this case, the first one we found may have at least given us a type.
    299     if (CSI.ReturnType.isNull())
    300       CSI.ReturnType = Ctx.VoidTy;
    301     return;
    302   }
    303 
    304   // Second case: at least one return statement has dependent type.
    305   // Delay type checking until instantiation.
    306   assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
    307   if (CSI.ReturnType->isDependentType())
    308     return;
    309 
    310   // Third case: only one return statement. Don't bother doing extra work!
    311   SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
    312                                          E = CSI.Returns.end();
    313   if (I+1 == E)
    314     return;
    315 
    316   // General case: many return statements.
    317   // Check that they all have compatible return types.
    318   // For now, that means "identical", with an exception for enum constants.
    319   // (In C, enum constants have the type of their underlying integer type,
    320   // not the type of the enum. C++ uses the type of the enum.)
    321   QualType AlternateType;
    322 
    323   // We require the return types to strictly match here.
    324   for (; I != E; ++I) {
    325     const ReturnStmt *RS = *I;
    326     const Expr *RetE = RS->getRetValue();
    327     if (!checkReturnValueType(Ctx, RetE, CSI.ReturnType, AlternateType)) {
    328       // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
    329       Diag(RS->getLocStart(),
    330            diag::err_typecheck_missing_return_type_incompatible)
    331         << (RetE ? RetE->getType() : Ctx.VoidTy) << CSI.ReturnType
    332         << isa<LambdaScopeInfo>(CSI);
    333       // Don't bother fixing up the return statements in the block if some of
    334       // them are unfixable anyway.
    335       AlternateType = Ctx.VoidTy;
    336       // Continue iterating so that we keep emitting diagnostics.
    337     }
    338   }
    339 
    340   // If our return statements turned out to be compatible, but we needed to
    341   // pick a different return type, go through and fix the ones that need it.
    342   if (AlternateType == Ctx.DependentTy) {
    343     for (SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
    344                                                 E = CSI.Returns.end();
    345          I != E; ++I) {
    346       ReturnStmt *RS = *I;
    347       Expr *RetE = RS->getRetValue();
    348       if (RetE->getType() == CSI.ReturnType)
    349         continue;
    350 
    351       // Right now we only support integral fixup casts.
    352       assert(CSI.ReturnType->isIntegralOrUnscopedEnumerationType());
    353       assert(RetE->getType()->isIntegralOrUnscopedEnumerationType());
    354       ExprResult Casted = ImpCastExprToType(RetE, CSI.ReturnType,
    355                                             CK_IntegralCast);
    356       assert(Casted.isUsable());
    357       RS->setRetValue(Casted.take());
    358     }
    359   }
    360 }
    361 
    362 void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
    363                                         Declarator &ParamInfo,
    364                                         Scope *CurScope) {
    365   // Determine if we're within a context where we know that the lambda will
    366   // be dependent, because there are template parameters in scope.
    367   bool KnownDependent = false;
    368   if (Scope *TmplScope = CurScope->getTemplateParamParent())
    369     if (!TmplScope->decl_empty())
    370       KnownDependent = true;
    371 
    372   CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, KnownDependent);
    373 
    374   // Determine the signature of the call operator.
    375   TypeSourceInfo *MethodTyInfo;
    376   bool ExplicitParams = true;
    377   bool ExplicitResultType = true;
    378   bool ContainsUnexpandedParameterPack = false;
    379   SourceLocation EndLoc;
    380   llvm::SmallVector<ParmVarDecl *, 8> Params;
    381   if (ParamInfo.getNumTypeObjects() == 0) {
    382     // C++11 [expr.prim.lambda]p4:
    383     //   If a lambda-expression does not include a lambda-declarator, it is as
    384     //   if the lambda-declarator were ().
    385     FunctionProtoType::ExtProtoInfo EPI;
    386     EPI.HasTrailingReturn = true;
    387     EPI.TypeQuals |= DeclSpec::TQ_const;
    388     QualType MethodTy = Context.getFunctionType(Context.DependentTy,
    389                                                 /*Args=*/0, /*NumArgs=*/0, EPI);
    390     MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
    391     ExplicitParams = false;
    392     ExplicitResultType = false;
    393     EndLoc = Intro.Range.getEnd();
    394   } else {
    395     assert(ParamInfo.isFunctionDeclarator() &&
    396            "lambda-declarator is a function");
    397     DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
    398 
    399     // C++11 [expr.prim.lambda]p5:
    400     //   This function call operator is declared const (9.3.1) if and only if
    401     //   the lambda-expression's parameter-declaration-clause is not followed
    402     //   by mutable. It is neither virtual nor declared volatile. [...]
    403     if (!FTI.hasMutableQualifier())
    404       FTI.TypeQuals |= DeclSpec::TQ_const;
    405 
    406     MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
    407     assert(MethodTyInfo && "no type from lambda-declarator");
    408     EndLoc = ParamInfo.getSourceRange().getEnd();
    409 
    410     ExplicitResultType
    411       = MethodTyInfo->getType()->getAs<FunctionType>()->getResultType()
    412                                                         != Context.DependentTy;
    413 
    414     Params.reserve(FTI.NumArgs);
    415     for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
    416       Params.push_back(cast<ParmVarDecl>(FTI.ArgInfo[i].Param));
    417 
    418     // Check for unexpanded parameter packs in the method type.
    419     if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
    420       ContainsUnexpandedParameterPack = true;
    421   }
    422 
    423   CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
    424                                                 MethodTyInfo, EndLoc, Params);
    425 
    426   if (ExplicitParams)
    427     CheckCXXDefaultArguments(Method);
    428 
    429   // Attributes on the lambda apply to the method.
    430   ProcessDeclAttributes(CurScope, Method, ParamInfo);
    431 
    432   // Introduce the function call operator as the current declaration context.
    433   PushDeclContext(CurScope, Method);
    434 
    435   // Introduce the lambda scope.
    436   LambdaScopeInfo *LSI
    437     = enterLambdaScope(Method, Intro.Range, Intro.Default, ExplicitParams,
    438                        ExplicitResultType,
    439                        !Method->isConst());
    440 
    441   // Handle explicit captures.
    442   SourceLocation PrevCaptureLoc
    443     = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
    444   for (llvm::SmallVector<LambdaCapture, 4>::const_iterator
    445          C = Intro.Captures.begin(),
    446          E = Intro.Captures.end();
    447        C != E;
    448        PrevCaptureLoc = C->Loc, ++C) {
    449     if (C->Kind == LCK_This) {
    450       // C++11 [expr.prim.lambda]p8:
    451       //   An identifier or this shall not appear more than once in a
    452       //   lambda-capture.
    453       if (LSI->isCXXThisCaptured()) {
    454         Diag(C->Loc, diag::err_capture_more_than_once)
    455           << "'this'"
    456           << SourceRange(LSI->getCXXThisCapture().getLocation())
    457           << FixItHint::CreateRemoval(
    458                SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
    459         continue;
    460       }
    461 
    462       // C++11 [expr.prim.lambda]p8:
    463       //   If a lambda-capture includes a capture-default that is =, the
    464       //   lambda-capture shall not contain this [...].
    465       if (Intro.Default == LCD_ByCopy) {
    466         Diag(C->Loc, diag::err_this_capture_with_copy_default)
    467           << FixItHint::CreateRemoval(
    468                SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
    469         continue;
    470       }
    471 
    472       // C++11 [expr.prim.lambda]p12:
    473       //   If this is captured by a local lambda expression, its nearest
    474       //   enclosing function shall be a non-static member function.
    475       QualType ThisCaptureType = getCurrentThisType();
    476       if (ThisCaptureType.isNull()) {
    477         Diag(C->Loc, diag::err_this_capture) << true;
    478         continue;
    479       }
    480 
    481       CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
    482       continue;
    483     }
    484 
    485     assert(C->Id && "missing identifier for capture");
    486 
    487     // C++11 [expr.prim.lambda]p8:
    488     //   If a lambda-capture includes a capture-default that is &, the
    489     //   identifiers in the lambda-capture shall not be preceded by &.
    490     //   If a lambda-capture includes a capture-default that is =, [...]
    491     //   each identifier it contains shall be preceded by &.
    492     if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
    493       Diag(C->Loc, diag::err_reference_capture_with_reference_default)
    494         << FixItHint::CreateRemoval(
    495              SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
    496       continue;
    497     } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
    498       Diag(C->Loc, diag::err_copy_capture_with_copy_default)
    499         << FixItHint::CreateRemoval(
    500              SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
    501       continue;
    502     }
    503 
    504     DeclarationNameInfo Name(C->Id, C->Loc);
    505     LookupResult R(*this, Name, LookupOrdinaryName);
    506     LookupName(R, CurScope);
    507     if (R.isAmbiguous())
    508       continue;
    509     if (R.empty()) {
    510       // FIXME: Disable corrections that would add qualification?
    511       CXXScopeSpec ScopeSpec;
    512       DeclFilterCCC<VarDecl> Validator;
    513       if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
    514         continue;
    515     }
    516 
    517     // C++11 [expr.prim.lambda]p10:
    518     //   The identifiers in a capture-list are looked up using the usual rules
    519     //   for unqualified name lookup (3.4.1); each such lookup shall find a
    520     //   variable with automatic storage duration declared in the reaching
    521     //   scope of the local lambda expression.
    522     //
    523     // Note that the 'reaching scope' check happens in tryCaptureVariable().
    524     VarDecl *Var = R.getAsSingle<VarDecl>();
    525     if (!Var) {
    526       Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
    527       continue;
    528     }
    529 
    530     if (!Var->hasLocalStorage()) {
    531       Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
    532       Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
    533       continue;
    534     }
    535 
    536     // C++11 [expr.prim.lambda]p8:
    537     //   An identifier or this shall not appear more than once in a
    538     //   lambda-capture.
    539     if (LSI->isCaptured(Var)) {
    540       Diag(C->Loc, diag::err_capture_more_than_once)
    541         << C->Id
    542         << SourceRange(LSI->getCapture(Var).getLocation())
    543         << FixItHint::CreateRemoval(
    544              SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
    545       continue;
    546     }
    547 
    548     // C++11 [expr.prim.lambda]p23:
    549     //   A capture followed by an ellipsis is a pack expansion (14.5.3).
    550     SourceLocation EllipsisLoc;
    551     if (C->EllipsisLoc.isValid()) {
    552       if (Var->isParameterPack()) {
    553         EllipsisLoc = C->EllipsisLoc;
    554       } else {
    555         Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
    556           << SourceRange(C->Loc);
    557 
    558         // Just ignore the ellipsis.
    559       }
    560     } else if (Var->isParameterPack()) {
    561       ContainsUnexpandedParameterPack = true;
    562     }
    563 
    564     TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
    565                                                  TryCapture_ExplicitByVal;
    566     tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
    567   }
    568   finishLambdaExplicitCaptures(LSI);
    569 
    570   LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
    571 
    572   // Add lambda parameters into scope.
    573   addLambdaParameters(Method, CurScope);
    574 
    575   // Enter a new evaluation context to insulate the lambda from any
    576   // cleanups from the enclosing full-expression.
    577   PushExpressionEvaluationContext(PotentiallyEvaluated);
    578 }
    579 
    580 void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
    581                             bool IsInstantiation) {
    582   // Leave the expression-evaluation context.
    583   DiscardCleanupsInEvaluationContext();
    584   PopExpressionEvaluationContext();
    585 
    586   // Leave the context of the lambda.
    587   if (!IsInstantiation)
    588     PopDeclContext();
    589 
    590   // Finalize the lambda.
    591   LambdaScopeInfo *LSI = getCurLambda();
    592   CXXRecordDecl *Class = LSI->Lambda;
    593   Class->setInvalidDecl();
    594   SmallVector<Decl*, 4> Fields;
    595   for (RecordDecl::field_iterator i = Class->field_begin(),
    596                                   e = Class->field_end(); i != e; ++i)
    597     Fields.push_back(*i);
    598   ActOnFields(0, Class->getLocation(), Class, Fields,
    599               SourceLocation(), SourceLocation(), 0);
    600   CheckCompletedCXXClass(Class);
    601 
    602   PopFunctionScopeInfo();
    603 }
    604 
    605 /// \brief Add a lambda's conversion to function pointer, as described in
    606 /// C++11 [expr.prim.lambda]p6.
    607 static void addFunctionPointerConversion(Sema &S,
    608                                          SourceRange IntroducerRange,
    609                                          CXXRecordDecl *Class,
    610                                          CXXMethodDecl *CallOperator) {
    611   // Add the conversion to function pointer.
    612   const FunctionProtoType *Proto
    613     = CallOperator->getType()->getAs<FunctionProtoType>();
    614   QualType FunctionPtrTy;
    615   QualType FunctionTy;
    616   {
    617     FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
    618     ExtInfo.TypeQuals = 0;
    619     FunctionTy = S.Context.getFunctionType(Proto->getResultType(),
    620                                            Proto->arg_type_begin(),
    621                                            Proto->getNumArgs(),
    622                                            ExtInfo);
    623     FunctionPtrTy = S.Context.getPointerType(FunctionTy);
    624   }
    625 
    626   FunctionProtoType::ExtProtoInfo ExtInfo;
    627   ExtInfo.TypeQuals = Qualifiers::Const;
    628   QualType ConvTy = S.Context.getFunctionType(FunctionPtrTy, 0, 0, ExtInfo);
    629 
    630   SourceLocation Loc = IntroducerRange.getBegin();
    631   DeclarationName Name
    632     = S.Context.DeclarationNames.getCXXConversionFunctionName(
    633         S.Context.getCanonicalType(FunctionPtrTy));
    634   DeclarationNameLoc NameLoc;
    635   NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
    636                                                                Loc);
    637   CXXConversionDecl *Conversion
    638     = CXXConversionDecl::Create(S.Context, Class, Loc,
    639                                 DeclarationNameInfo(Name, Loc, NameLoc),
    640                                 ConvTy,
    641                                 S.Context.getTrivialTypeSourceInfo(ConvTy,
    642                                                                    Loc),
    643                                 /*isInline=*/false, /*isExplicit=*/false,
    644                                 /*isConstexpr=*/false,
    645                                 CallOperator->getBody()->getLocEnd());
    646   Conversion->setAccess(AS_public);
    647   Conversion->setImplicit(true);
    648   Class->addDecl(Conversion);
    649 
    650   // Add a non-static member function "__invoke" that will be the result of
    651   // the conversion.
    652   Name = &S.Context.Idents.get("__invoke");
    653   CXXMethodDecl *Invoke
    654     = CXXMethodDecl::Create(S.Context, Class, Loc,
    655                             DeclarationNameInfo(Name, Loc), FunctionTy,
    656                             CallOperator->getTypeSourceInfo(),
    657                             /*IsStatic=*/true, SC_Static, /*IsInline=*/true,
    658                             /*IsConstexpr=*/false,
    659                             CallOperator->getBody()->getLocEnd());
    660   SmallVector<ParmVarDecl *, 4> InvokeParams;
    661   for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
    662     ParmVarDecl *From = CallOperator->getParamDecl(I);
    663     InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
    664                                                From->getLocStart(),
    665                                                From->getLocation(),
    666                                                From->getIdentifier(),
    667                                                From->getType(),
    668                                                From->getTypeSourceInfo(),
    669                                                From->getStorageClass(),
    670                                                From->getStorageClassAsWritten(),
    671                                                /*DefaultArg=*/0));
    672   }
    673   Invoke->setParams(InvokeParams);
    674   Invoke->setAccess(AS_private);
    675   Invoke->setImplicit(true);
    676   Class->addDecl(Invoke);
    677 }
    678 
    679 /// \brief Add a lambda's conversion to block pointer.
    680 static void addBlockPointerConversion(Sema &S,
    681                                       SourceRange IntroducerRange,
    682                                       CXXRecordDecl *Class,
    683                                       CXXMethodDecl *CallOperator) {
    684   const FunctionProtoType *Proto
    685     = CallOperator->getType()->getAs<FunctionProtoType>();
    686   QualType BlockPtrTy;
    687   {
    688     FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
    689     ExtInfo.TypeQuals = 0;
    690     QualType FunctionTy
    691       = S.Context.getFunctionType(Proto->getResultType(),
    692                                   Proto->arg_type_begin(),
    693                                   Proto->getNumArgs(),
    694                                   ExtInfo);
    695     BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
    696   }
    697 
    698   FunctionProtoType::ExtProtoInfo ExtInfo;
    699   ExtInfo.TypeQuals = Qualifiers::Const;
    700   QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, 0, 0, ExtInfo);
    701 
    702   SourceLocation Loc = IntroducerRange.getBegin();
    703   DeclarationName Name
    704     = S.Context.DeclarationNames.getCXXConversionFunctionName(
    705         S.Context.getCanonicalType(BlockPtrTy));
    706   DeclarationNameLoc NameLoc;
    707   NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
    708   CXXConversionDecl *Conversion
    709     = CXXConversionDecl::Create(S.Context, Class, Loc,
    710                                 DeclarationNameInfo(Name, Loc, NameLoc),
    711                                 ConvTy,
    712                                 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
    713                                 /*isInline=*/false, /*isExplicit=*/false,
    714                                 /*isConstexpr=*/false,
    715                                 CallOperator->getBody()->getLocEnd());
    716   Conversion->setAccess(AS_public);
    717   Conversion->setImplicit(true);
    718   Class->addDecl(Conversion);
    719 }
    720 
    721 ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
    722                                  Scope *CurScope,
    723                                  bool IsInstantiation) {
    724   // Collect information from the lambda scope.
    725   llvm::SmallVector<LambdaExpr::Capture, 4> Captures;
    726   llvm::SmallVector<Expr *, 4> CaptureInits;
    727   LambdaCaptureDefault CaptureDefault;
    728   CXXRecordDecl *Class;
    729   CXXMethodDecl *CallOperator;
    730   SourceRange IntroducerRange;
    731   bool ExplicitParams;
    732   bool ExplicitResultType;
    733   bool LambdaExprNeedsCleanups;
    734   bool ContainsUnexpandedParameterPack;
    735   llvm::SmallVector<VarDecl *, 4> ArrayIndexVars;
    736   llvm::SmallVector<unsigned, 4> ArrayIndexStarts;
    737   {
    738     LambdaScopeInfo *LSI = getCurLambda();
    739     CallOperator = LSI->CallOperator;
    740     Class = LSI->Lambda;
    741     IntroducerRange = LSI->IntroducerRange;
    742     ExplicitParams = LSI->ExplicitParams;
    743     ExplicitResultType = !LSI->HasImplicitReturnType;
    744     LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
    745     ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
    746     ArrayIndexVars.swap(LSI->ArrayIndexVars);
    747     ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
    748 
    749     // Translate captures.
    750     for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
    751       LambdaScopeInfo::Capture From = LSI->Captures[I];
    752       assert(!From.isBlockCapture() && "Cannot capture __block variables");
    753       bool IsImplicit = I >= LSI->NumExplicitCaptures;
    754 
    755       // Handle 'this' capture.
    756       if (From.isThisCapture()) {
    757         Captures.push_back(LambdaExpr::Capture(From.getLocation(),
    758                                                IsImplicit,
    759                                                LCK_This));
    760         CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
    761                                                          getCurrentThisType(),
    762                                                          /*isImplicit=*/true));
    763         continue;
    764       }
    765 
    766       VarDecl *Var = From.getVariable();
    767       LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
    768       Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
    769                                              Kind, Var, From.getEllipsisLoc()));
    770       CaptureInits.push_back(From.getCopyExpr());
    771     }
    772 
    773     switch (LSI->ImpCaptureStyle) {
    774     case CapturingScopeInfo::ImpCap_None:
    775       CaptureDefault = LCD_None;
    776       break;
    777 
    778     case CapturingScopeInfo::ImpCap_LambdaByval:
    779       CaptureDefault = LCD_ByCopy;
    780       break;
    781 
    782     case CapturingScopeInfo::ImpCap_LambdaByref:
    783       CaptureDefault = LCD_ByRef;
    784       break;
    785 
    786     case CapturingScopeInfo::ImpCap_Block:
    787       llvm_unreachable("block capture in lambda");
    788       break;
    789     }
    790 
    791     // C++11 [expr.prim.lambda]p4:
    792     //   If a lambda-expression does not include a
    793     //   trailing-return-type, it is as if the trailing-return-type
    794     //   denotes the following type:
    795     // FIXME: Assumes current resolution to core issue 975.
    796     if (LSI->HasImplicitReturnType) {
    797       deduceClosureReturnType(*LSI);
    798 
    799       //   - if there are no return statements in the
    800       //     compound-statement, or all return statements return
    801       //     either an expression of type void or no expression or
    802       //     braced-init-list, the type void;
    803       if (LSI->ReturnType.isNull()) {
    804         LSI->ReturnType = Context.VoidTy;
    805       }
    806 
    807       // Create a function type with the inferred return type.
    808       const FunctionProtoType *Proto
    809         = CallOperator->getType()->getAs<FunctionProtoType>();
    810       QualType FunctionTy
    811         = Context.getFunctionType(LSI->ReturnType,
    812                                   Proto->arg_type_begin(),
    813                                   Proto->getNumArgs(),
    814                                   Proto->getExtProtoInfo());
    815       CallOperator->setType(FunctionTy);
    816     }
    817 
    818     // C++ [expr.prim.lambda]p7:
    819     //   The lambda-expression's compound-statement yields the
    820     //   function-body (8.4) of the function call operator [...].
    821     ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
    822     CallOperator->setLexicalDeclContext(Class);
    823     Class->addDecl(CallOperator);
    824     PopExpressionEvaluationContext();
    825 
    826     // C++11 [expr.prim.lambda]p6:
    827     //   The closure type for a lambda-expression with no lambda-capture
    828     //   has a public non-virtual non-explicit const conversion function
    829     //   to pointer to function having the same parameter and return
    830     //   types as the closure type's function call operator.
    831     if (Captures.empty() && CaptureDefault == LCD_None)
    832       addFunctionPointerConversion(*this, IntroducerRange, Class,
    833                                    CallOperator);
    834 
    835     // Objective-C++:
    836     //   The closure type for a lambda-expression has a public non-virtual
    837     //   non-explicit const conversion function to a block pointer having the
    838     //   same parameter and return types as the closure type's function call
    839     //   operator.
    840     if (getLangOpts().Blocks && getLangOpts().ObjC1)
    841       addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
    842 
    843     // Finalize the lambda class.
    844     SmallVector<Decl*, 4> Fields;
    845     for (RecordDecl::field_iterator i = Class->field_begin(),
    846                                     e = Class->field_end(); i != e; ++i)
    847       Fields.push_back(*i);
    848     ActOnFields(0, Class->getLocation(), Class, Fields,
    849                 SourceLocation(), SourceLocation(), 0);
    850     CheckCompletedCXXClass(Class);
    851   }
    852 
    853   if (LambdaExprNeedsCleanups)
    854     ExprNeedsCleanups = true;
    855 
    856   LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
    857                                           CaptureDefault, Captures,
    858                                           ExplicitParams, ExplicitResultType,
    859                                           CaptureInits, ArrayIndexVars,
    860                                           ArrayIndexStarts, Body->getLocEnd(),
    861                                           ContainsUnexpandedParameterPack);
    862 
    863   // C++11 [expr.prim.lambda]p2:
    864   //   A lambda-expression shall not appear in an unevaluated operand
    865   //   (Clause 5).
    866   if (!CurContext->isDependentContext()) {
    867     switch (ExprEvalContexts.back().Context) {
    868     case Unevaluated:
    869       // We don't actually diagnose this case immediately, because we
    870       // could be within a context where we might find out later that
    871       // the expression is potentially evaluated (e.g., for typeid).
    872       ExprEvalContexts.back().Lambdas.push_back(Lambda);
    873       break;
    874 
    875     case ConstantEvaluated:
    876     case PotentiallyEvaluated:
    877     case PotentiallyEvaluatedIfUsed:
    878       break;
    879     }
    880   }
    881 
    882   return MaybeBindToTemporary(Lambda);
    883 }
    884 
    885 ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
    886                                                SourceLocation ConvLocation,
    887                                                CXXConversionDecl *Conv,
    888                                                Expr *Src) {
    889   // Make sure that the lambda call operator is marked used.
    890   CXXRecordDecl *Lambda = Conv->getParent();
    891   CXXMethodDecl *CallOperator
    892     = cast<CXXMethodDecl>(
    893         *Lambda->lookup(
    894           Context.DeclarationNames.getCXXOperatorName(OO_Call)).first);
    895   CallOperator->setReferenced();
    896   CallOperator->setUsed();
    897 
    898   ExprResult Init = PerformCopyInitialization(
    899                       InitializedEntity::InitializeBlock(ConvLocation,
    900                                                          Src->getType(),
    901                                                          /*NRVO=*/false),
    902                       CurrentLocation, Src);
    903   if (!Init.isInvalid())
    904     Init = ActOnFinishFullExpr(Init.take());
    905 
    906   if (Init.isInvalid())
    907     return ExprError();
    908 
    909   // Create the new block to be returned.
    910   BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
    911 
    912   // Set the type information.
    913   Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
    914   Block->setIsVariadic(CallOperator->isVariadic());
    915   Block->setBlockMissingReturnType(false);
    916 
    917   // Add parameters.
    918   SmallVector<ParmVarDecl *, 4> BlockParams;
    919   for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
    920     ParmVarDecl *From = CallOperator->getParamDecl(I);
    921     BlockParams.push_back(ParmVarDecl::Create(Context, Block,
    922                                               From->getLocStart(),
    923                                               From->getLocation(),
    924                                               From->getIdentifier(),
    925                                               From->getType(),
    926                                               From->getTypeSourceInfo(),
    927                                               From->getStorageClass(),
    928                                             From->getStorageClassAsWritten(),
    929                                               /*DefaultArg=*/0));
    930   }
    931   Block->setParams(BlockParams);
    932 
    933   Block->setIsConversionFromLambda(true);
    934 
    935   // Add capture. The capture uses a fake variable, which doesn't correspond
    936   // to any actual memory location. However, the initializer copy-initializes
    937   // the lambda object.
    938   TypeSourceInfo *CapVarTSI =
    939       Context.getTrivialTypeSourceInfo(Src->getType());
    940   VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
    941                                     ConvLocation, 0,
    942                                     Src->getType(), CapVarTSI,
    943                                     SC_None, SC_None);
    944   BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
    945                              /*Nested=*/false, /*Copy=*/Init.take());
    946   Block->setCaptures(Context, &Capture, &Capture + 1,
    947                      /*CapturesCXXThis=*/false);
    948 
    949   // Add a fake function body to the block. IR generation is responsible
    950   // for filling in the actual body, which cannot be expressed as an AST.
    951   Block->setBody(new (Context) CompoundStmt(ConvLocation));
    952 
    953   // Create the block literal expression.
    954   Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
    955   ExprCleanupObjects.push_back(Block);
    956   ExprNeedsCleanups = true;
    957 
    958   return BuildBlock;
    959 }
    960