SemaLambda.cpp revision 04fa7a33279808dc3e5117c41b5f84c40eeb7362
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/AST/ASTLambda.h"
15#include "clang/AST/ExprCXX.h"
16#include "clang/Basic/TargetInfo.h"
17#include "clang/Lex/Preprocessor.h"
18#include "clang/Sema/Initialization.h"
19#include "clang/Sema/Lookup.h"
20#include "clang/Sema/Scope.h"
21#include "clang/Sema/ScopeInfo.h"
22#include "clang/Sema/SemaInternal.h"
23#include "TypeLocBuilder.h"
24using namespace clang;
25using namespace sema;
26
27CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
28                                             TypeSourceInfo *Info,
29                                             bool KnownDependent) {
30  DeclContext *DC = CurContext;
31  while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
32    DC = DC->getParent();
33
34  // Start constructing the lambda class.
35  CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info,
36                                                     IntroducerRange.getBegin(),
37                                                     KnownDependent);
38  DC->addDecl(Class);
39
40  return Class;
41}
42
43/// \brief Determine whether the given context is or is enclosed in an inline
44/// function.
45static bool isInInlineFunction(const DeclContext *DC) {
46  while (!DC->isFileContext()) {
47    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
48      if (FD->isInlined())
49        return true;
50
51    DC = DC->getLexicalParent();
52  }
53
54  return false;
55}
56
57MangleNumberingContext *
58Sema::getCurrentMangleNumberContext(const DeclContext *DC,
59                                    Decl *&ManglingContextDecl) {
60  // Compute the context for allocating mangling numbers in the current
61  // expression, if the ABI requires them.
62  ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
63
64  enum ContextKind {
65    Normal,
66    DefaultArgument,
67    DataMember,
68    StaticDataMember
69  } Kind = Normal;
70
71  // Default arguments of member function parameters that appear in a class
72  // definition, as well as the initializers of data members, receive special
73  // treatment. Identify them.
74  if (ManglingContextDecl) {
75    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
76      if (const DeclContext *LexicalDC
77          = Param->getDeclContext()->getLexicalParent())
78        if (LexicalDC->isRecord())
79          Kind = DefaultArgument;
80    } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
81      if (Var->getDeclContext()->isRecord())
82        Kind = StaticDataMember;
83    } else if (isa<FieldDecl>(ManglingContextDecl)) {
84      Kind = DataMember;
85    }
86  }
87
88  // Itanium ABI [5.1.7]:
89  //   In the following contexts [...] the one-definition rule requires closure
90  //   types in different translation units to "correspond":
91  bool IsInNonspecializedTemplate =
92    !ActiveTemplateInstantiations.empty() || CurContext->isDependentContext();
93  switch (Kind) {
94  case Normal:
95    //  -- the bodies of non-exported nonspecialized template functions
96    //  -- the bodies of inline functions
97    if ((IsInNonspecializedTemplate &&
98         !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
99        isInInlineFunction(CurContext)) {
100      ManglingContextDecl = 0;
101      return &Context.getManglingNumberContext(DC);
102    }
103
104    ManglingContextDecl = 0;
105    return 0;
106
107  case StaticDataMember:
108    //  -- the initializers of nonspecialized static members of template classes
109    if (!IsInNonspecializedTemplate) {
110      ManglingContextDecl = 0;
111      return 0;
112    }
113    // Fall through to get the current context.
114
115  case DataMember:
116    //  -- the in-class initializers of class members
117  case DefaultArgument:
118    //  -- default arguments appearing in class definitions
119    return &ExprEvalContexts.back().getMangleNumberingContext(Context);
120  }
121
122  llvm_unreachable("unexpected context");
123}
124
125MangleNumberingContext &
126Sema::ExpressionEvaluationContextRecord::getMangleNumberingContext(
127    ASTContext &Ctx) {
128  assert(ManglingContextDecl && "Need to have a context declaration");
129  if (!MangleNumbering)
130    MangleNumbering = Ctx.createMangleNumberingContext();
131  return *MangleNumbering;
132}
133
134static inline TemplateParameterList *
135getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) {
136  if (LSI->GLTemplateParameterList)
137    return LSI->GLTemplateParameterList;
138  else if (LSI->AutoTemplateParams.size()) {
139    SourceRange IntroRange = LSI->IntroducerRange;
140    SourceLocation LAngleLoc = IntroRange.getBegin();
141    SourceLocation RAngleLoc = IntroRange.getEnd();
142    LSI->GLTemplateParameterList =
143          TemplateParameterList::Create(SemaRef.Context,
144            /* Template kw loc */ SourceLocation(),
145            LAngleLoc,
146            (NamedDecl**)LSI->AutoTemplateParams.data(),
147            LSI->AutoTemplateParams.size(), RAngleLoc);
148  }
149  return LSI->GLTemplateParameterList;
150}
151
152
153CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
154                                           SourceRange IntroducerRange,
155                                           TypeSourceInfo *MethodTypeInfo,
156                                           SourceLocation EndLoc,
157                                           ArrayRef<ParmVarDecl *> Params) {
158  QualType MethodType = MethodTypeInfo->getType();
159  TemplateParameterList *TemplateParams =
160            getGenericLambdaTemplateParameterList(getCurLambda(), *this);
161  // If a lambda appears in a dependent context or is a generic lambda (has
162  // template parameters) and has an 'auto' return type, deduce it to a
163  // dependent type.
164  if (Class->isDependentContext() || TemplateParams) {
165    const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
166    QualType Result = FPT->getResultType();
167    if (Result->isUndeducedType()) {
168      Result = SubstAutoType(Result, Context.DependentTy);
169      MethodType = Context.getFunctionType(Result, FPT->getArgTypes(),
170                                           FPT->getExtProtoInfo());
171    }
172  }
173
174  // C++11 [expr.prim.lambda]p5:
175  //   The closure type for a lambda-expression has a public inline function
176  //   call operator (13.5.4) whose parameters and return type are described by
177  //   the lambda-expression's parameter-declaration-clause and
178  //   trailing-return-type respectively.
179  DeclarationName MethodName
180    = Context.DeclarationNames.getCXXOperatorName(OO_Call);
181  DeclarationNameLoc MethodNameLoc;
182  MethodNameLoc.CXXOperatorName.BeginOpNameLoc
183    = IntroducerRange.getBegin().getRawEncoding();
184  MethodNameLoc.CXXOperatorName.EndOpNameLoc
185    = IntroducerRange.getEnd().getRawEncoding();
186  CXXMethodDecl *Method
187    = CXXMethodDecl::Create(Context, Class, EndLoc,
188                            DeclarationNameInfo(MethodName,
189                                                IntroducerRange.getBegin(),
190                                                MethodNameLoc),
191                            MethodType, MethodTypeInfo,
192                            SC_None,
193                            /*isInline=*/true,
194                            /*isConstExpr=*/false,
195                            EndLoc);
196  Method->setAccess(AS_public);
197
198  // Temporarily set the lexical declaration context to the current
199  // context, so that the Scope stack matches the lexical nesting.
200  Method->setLexicalDeclContext(CurContext);
201  // Create a function template if we have a template parameter list
202  FunctionTemplateDecl *const TemplateMethod = TemplateParams ?
203            FunctionTemplateDecl::Create(Context, Class,
204                                         Method->getLocation(), MethodName,
205                                         TemplateParams,
206                                         Method) : 0;
207  if (TemplateMethod) {
208    TemplateMethod->setLexicalDeclContext(CurContext);
209    TemplateMethod->setAccess(AS_public);
210    Method->setDescribedFunctionTemplate(TemplateMethod);
211  }
212
213  // Add parameters.
214  if (!Params.empty()) {
215    Method->setParams(Params);
216    CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
217                             const_cast<ParmVarDecl **>(Params.end()),
218                             /*CheckParameterNames=*/false);
219
220    for (CXXMethodDecl::param_iterator P = Method->param_begin(),
221                                    PEnd = Method->param_end();
222         P != PEnd; ++P)
223      (*P)->setOwningFunction(Method);
224  }
225
226  Decl *ManglingContextDecl;
227  if (MangleNumberingContext *MCtx =
228          getCurrentMangleNumberContext(Class->getDeclContext(),
229                                        ManglingContextDecl)) {
230    unsigned ManglingNumber = MCtx->getManglingNumber(Method);
231    Class->setLambdaMangling(ManglingNumber, ManglingContextDecl);
232  }
233
234  return Method;
235}
236
237void Sema::buildLambdaScope(LambdaScopeInfo *LSI,
238                                        CXXMethodDecl *CallOperator,
239                                        SourceRange IntroducerRange,
240                                        LambdaCaptureDefault CaptureDefault,
241                                        SourceLocation CaptureDefaultLoc,
242                                        bool ExplicitParams,
243                                        bool ExplicitResultType,
244                                        bool Mutable) {
245  LSI->CallOperator = CallOperator;
246  LSI->Lambda = CallOperator->getParent();
247  if (CaptureDefault == LCD_ByCopy)
248    LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
249  else if (CaptureDefault == LCD_ByRef)
250    LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
251  LSI->CaptureDefaultLoc = CaptureDefaultLoc;
252  LSI->IntroducerRange = IntroducerRange;
253  LSI->ExplicitParams = ExplicitParams;
254  LSI->Mutable = Mutable;
255
256  if (ExplicitResultType) {
257    LSI->ReturnType = CallOperator->getResultType();
258
259    if (!LSI->ReturnType->isDependentType() &&
260        !LSI->ReturnType->isVoidType()) {
261      if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
262                              diag::err_lambda_incomplete_result)) {
263        // Do nothing.
264      }
265    }
266  } else {
267    LSI->HasImplicitReturnType = true;
268  }
269}
270
271void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
272  LSI->finishedExplicitCaptures();
273}
274
275void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
276  // Introduce our parameters into the function scope
277  for (unsigned p = 0, NumParams = CallOperator->getNumParams();
278       p < NumParams; ++p) {
279    ParmVarDecl *Param = CallOperator->getParamDecl(p);
280
281    // If this has an identifier, add it to the scope stack.
282    if (CurScope && Param->getIdentifier()) {
283      CheckShadow(CurScope, Param);
284
285      PushOnScopeChains(Param, CurScope);
286    }
287  }
288}
289
290/// If this expression is an enumerator-like expression of some type
291/// T, return the type T; otherwise, return null.
292///
293/// Pointer comparisons on the result here should always work because
294/// it's derived from either the parent of an EnumConstantDecl
295/// (i.e. the definition) or the declaration returned by
296/// EnumType::getDecl() (i.e. the definition).
297static EnumDecl *findEnumForBlockReturn(Expr *E) {
298  // An expression is an enumerator-like expression of type T if,
299  // ignoring parens and parens-like expressions:
300  E = E->IgnoreParens();
301
302  //  - it is an enumerator whose enum type is T or
303  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
304    if (EnumConstantDecl *D
305          = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
306      return cast<EnumDecl>(D->getDeclContext());
307    }
308    return 0;
309  }
310
311  //  - it is a comma expression whose RHS is an enumerator-like
312  //    expression of type T or
313  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
314    if (BO->getOpcode() == BO_Comma)
315      return findEnumForBlockReturn(BO->getRHS());
316    return 0;
317  }
318
319  //  - it is a statement-expression whose value expression is an
320  //    enumerator-like expression of type T or
321  if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
322    if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
323      return findEnumForBlockReturn(last);
324    return 0;
325  }
326
327  //   - it is a ternary conditional operator (not the GNU ?:
328  //     extension) whose second and third operands are
329  //     enumerator-like expressions of type T or
330  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
331    if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
332      if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
333        return ED;
334    return 0;
335  }
336
337  // (implicitly:)
338  //   - it is an implicit integral conversion applied to an
339  //     enumerator-like expression of type T or
340  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
341    // We can sometimes see integral conversions in valid
342    // enumerator-like expressions.
343    if (ICE->getCastKind() == CK_IntegralCast)
344      return findEnumForBlockReturn(ICE->getSubExpr());
345
346    // Otherwise, just rely on the type.
347  }
348
349  //   - it is an expression of that formal enum type.
350  if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
351    return ET->getDecl();
352  }
353
354  // Otherwise, nope.
355  return 0;
356}
357
358/// Attempt to find a type T for which the returned expression of the
359/// given statement is an enumerator-like expression of that type.
360static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
361  if (Expr *retValue = ret->getRetValue())
362    return findEnumForBlockReturn(retValue);
363  return 0;
364}
365
366/// Attempt to find a common type T for which all of the returned
367/// expressions in a block are enumerator-like expressions of that
368/// type.
369static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
370  ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
371
372  // Try to find one for the first return.
373  EnumDecl *ED = findEnumForBlockReturn(*i);
374  if (!ED) return 0;
375
376  // Check that the rest of the returns have the same enum.
377  for (++i; i != e; ++i) {
378    if (findEnumForBlockReturn(*i) != ED)
379      return 0;
380  }
381
382  // Never infer an anonymous enum type.
383  if (!ED->hasNameForLinkage()) return 0;
384
385  return ED;
386}
387
388/// Adjust the given return statements so that they formally return
389/// the given type.  It should require, at most, an IntegralCast.
390static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
391                                     QualType returnType) {
392  for (ArrayRef<ReturnStmt*>::iterator
393         i = returns.begin(), e = returns.end(); i != e; ++i) {
394    ReturnStmt *ret = *i;
395    Expr *retValue = ret->getRetValue();
396    if (S.Context.hasSameType(retValue->getType(), returnType))
397      continue;
398
399    // Right now we only support integral fixup casts.
400    assert(returnType->isIntegralOrUnscopedEnumerationType());
401    assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
402
403    ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
404
405    Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
406    E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast,
407                                 E, /*base path*/ 0, VK_RValue);
408    if (cleanups) {
409      cleanups->setSubExpr(E);
410    } else {
411      ret->setRetValue(E);
412    }
413  }
414}
415
416void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
417  assert(CSI.HasImplicitReturnType);
418  // If it was ever a placeholder, it had to been deduced to DependentTy.
419  assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
420
421  // C++ Core Issue #975, proposed resolution:
422  //   If a lambda-expression does not include a trailing-return-type,
423  //   it is as if the trailing-return-type denotes the following type:
424  //     - if there are no return statements in the compound-statement,
425  //       or all return statements return either an expression of type
426  //       void or no expression or braced-init-list, the type void;
427  //     - otherwise, if all return statements return an expression
428  //       and the types of the returned expressions after
429  //       lvalue-to-rvalue conversion (4.1 [conv.lval]),
430  //       array-to-pointer conversion (4.2 [conv.array]), and
431  //       function-to-pointer conversion (4.3 [conv.func]) are the
432  //       same, that common type;
433  //     - otherwise, the program is ill-formed.
434  //
435  // In addition, in blocks in non-C++ modes, if all of the return
436  // statements are enumerator-like expressions of some type T, where
437  // T has a name for linkage, then we infer the return type of the
438  // block to be that type.
439
440  // First case: no return statements, implicit void return type.
441  ASTContext &Ctx = getASTContext();
442  if (CSI.Returns.empty()) {
443    // It's possible there were simply no /valid/ return statements.
444    // In this case, the first one we found may have at least given us a type.
445    if (CSI.ReturnType.isNull())
446      CSI.ReturnType = Ctx.VoidTy;
447    return;
448  }
449
450  // Second case: at least one return statement has dependent type.
451  // Delay type checking until instantiation.
452  assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
453  if (CSI.ReturnType->isDependentType())
454    return;
455
456  // Try to apply the enum-fuzz rule.
457  if (!getLangOpts().CPlusPlus) {
458    assert(isa<BlockScopeInfo>(CSI));
459    const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
460    if (ED) {
461      CSI.ReturnType = Context.getTypeDeclType(ED);
462      adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
463      return;
464    }
465  }
466
467  // Third case: only one return statement. Don't bother doing extra work!
468  SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
469                                         E = CSI.Returns.end();
470  if (I+1 == E)
471    return;
472
473  // General case: many return statements.
474  // Check that they all have compatible return types.
475
476  // We require the return types to strictly match here.
477  // Note that we've already done the required promotions as part of
478  // processing the return statement.
479  for (; I != E; ++I) {
480    const ReturnStmt *RS = *I;
481    const Expr *RetE = RS->getRetValue();
482
483    QualType ReturnType = (RetE ? RetE->getType() : Context.VoidTy);
484    if (Context.hasSameType(ReturnType, CSI.ReturnType))
485      continue;
486
487    // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
488    // TODO: It's possible that the *first* return is the divergent one.
489    Diag(RS->getLocStart(),
490         diag::err_typecheck_missing_return_type_incompatible)
491      << ReturnType << CSI.ReturnType
492      << isa<LambdaScopeInfo>(CSI);
493    // Continue iterating so that we keep emitting diagnostics.
494  }
495}
496
497VarDecl *Sema::checkInitCapture(SourceLocation Loc, bool ByRef,
498                                IdentifierInfo *Id, Expr *Init) {
499  // C++1y [expr.prim.lambda]p11:
500  //   An init-capture behaves as if it declares and explicitly captures
501  //   a variable of the form
502  //     "auto init-capture;"
503  QualType DeductType = Context.getAutoDeductType();
504  TypeLocBuilder TLB;
505  TLB.pushTypeSpec(DeductType).setNameLoc(Loc);
506  if (ByRef) {
507    DeductType = BuildReferenceType(DeductType, true, Loc, Id);
508    assert(!DeductType.isNull() && "can't build reference to auto");
509    TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
510  }
511  TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
512
513  // Create a dummy variable representing the init-capture. This is not actually
514  // used as a variable, and only exists as a way to name and refer to the
515  // init-capture.
516  // FIXME: Pass in separate source locations for '&' and identifier.
517  VarDecl *NewVD = VarDecl::Create(Context, CurContext->getLexicalParent(), Loc,
518                                   Loc, Id, TSI->getType(), TSI, SC_Auto);
519  NewVD->setInitCapture(true);
520  NewVD->setReferenced(true);
521  NewVD->markUsed(Context);
522
523  // We do not need to distinguish between direct-list-initialization
524  // and copy-list-initialization here, because we will always deduce
525  // std::initializer_list<T>, and direct- and copy-list-initialization
526  // always behave the same for such a type.
527  // FIXME: We should model whether an '=' was present.
528  bool DirectInit = isa<ParenListExpr>(Init) || isa<InitListExpr>(Init);
529  AddInitializerToDecl(NewVD, Init, DirectInit, /*ContainsAuto*/true);
530  return NewVD;
531}
532
533FieldDecl *Sema::buildInitCaptureField(LambdaScopeInfo *LSI, VarDecl *Var) {
534  FieldDecl *Field = FieldDecl::Create(
535      Context, LSI->Lambda, Var->getLocation(), Var->getLocation(),
536      0, Var->getType(), Var->getTypeSourceInfo(), 0, false, ICIS_NoInit);
537  Field->setImplicit(true);
538  Field->setAccess(AS_private);
539  LSI->Lambda->addDecl(Field);
540
541  LSI->addCapture(Var, /*isBlock*/false, Var->getType()->isReferenceType(),
542                  /*isNested*/false, Var->getLocation(), SourceLocation(),
543                  Var->getType(), Var->getInit());
544  return Field;
545}
546
547void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
548                  Declarator &ParamInfo, Scope *CurScope) {
549  // Determine if we're within a context where we know that the lambda will
550  // be dependent, because there are template parameters in scope.
551  bool KnownDependent = false;
552  LambdaScopeInfo *const LSI = getCurLambda();
553  assert(LSI && "LambdaScopeInfo should be on stack!");
554  TemplateParameterList *TemplateParams =
555            getGenericLambdaTemplateParameterList(LSI, *this);
556
557  if (Scope *TmplScope = CurScope->getTemplateParamParent()) {
558    // Since we have our own TemplateParams, so check if an outer scope
559    // has template params, only then are we in a dependent scope.
560    if (TemplateParams)  {
561      TmplScope = TmplScope->getParent();
562      TmplScope = TmplScope ? TmplScope->getTemplateParamParent() : 0;
563    }
564    if (TmplScope && !TmplScope->decl_empty())
565      KnownDependent = true;
566  }
567  // Determine the signature of the call operator.
568  TypeSourceInfo *MethodTyInfo;
569  bool ExplicitParams = true;
570  bool ExplicitResultType = true;
571  bool ContainsUnexpandedParameterPack = false;
572  SourceLocation EndLoc;
573  SmallVector<ParmVarDecl *, 8> Params;
574  if (ParamInfo.getNumTypeObjects() == 0) {
575    // C++11 [expr.prim.lambda]p4:
576    //   If a lambda-expression does not include a lambda-declarator, it is as
577    //   if the lambda-declarator were ().
578    FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
579        /*IsVariadic=*/false, /*IsCXXMethod=*/true));
580    EPI.HasTrailingReturn = true;
581    EPI.TypeQuals |= DeclSpec::TQ_const;
582    // C++1y [expr.prim.lambda]:
583    //   The lambda return type is 'auto', which is replaced by the
584    //   trailing-return type if provided and/or deduced from 'return'
585    //   statements
586    // We don't do this before C++1y, because we don't support deduced return
587    // types there.
588    QualType DefaultTypeForNoTrailingReturn =
589        getLangOpts().CPlusPlus1y ? Context.getAutoDeductType()
590                                  : Context.DependentTy;
591    QualType MethodTy =
592        Context.getFunctionType(DefaultTypeForNoTrailingReturn, None, EPI);
593    MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
594    ExplicitParams = false;
595    ExplicitResultType = false;
596    EndLoc = Intro.Range.getEnd();
597  } else {
598    assert(ParamInfo.isFunctionDeclarator() &&
599           "lambda-declarator is a function");
600    DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
601
602    // C++11 [expr.prim.lambda]p5:
603    //   This function call operator is declared const (9.3.1) if and only if
604    //   the lambda-expression's parameter-declaration-clause is not followed
605    //   by mutable. It is neither virtual nor declared volatile. [...]
606    if (!FTI.hasMutableQualifier())
607      FTI.TypeQuals |= DeclSpec::TQ_const;
608
609    MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
610    assert(MethodTyInfo && "no type from lambda-declarator");
611    EndLoc = ParamInfo.getSourceRange().getEnd();
612
613    ExplicitResultType = FTI.hasTrailingReturnType();
614
615    if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
616        cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
617      // Empty arg list, don't push any params.
618      checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
619    } else {
620      Params.reserve(FTI.NumArgs);
621      for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
622        Params.push_back(cast<ParmVarDecl>(FTI.ArgInfo[i].Param));
623    }
624
625    // Check for unexpanded parameter packs in the method type.
626    if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
627      ContainsUnexpandedParameterPack = true;
628  }
629
630  CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
631                                                 KnownDependent);
632
633  CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
634                                                MethodTyInfo, EndLoc, Params);
635  if (ExplicitParams)
636    CheckCXXDefaultArguments(Method);
637
638  // Attributes on the lambda apply to the method.
639  ProcessDeclAttributes(CurScope, Method, ParamInfo);
640
641  // Introduce the function call operator as the current declaration context.
642  PushDeclContext(CurScope, Method);
643
644  // Build the lambda scope.
645  buildLambdaScope(LSI, Method,
646                       Intro.Range,
647                       Intro.Default, Intro.DefaultLoc,
648                       ExplicitParams,
649                       ExplicitResultType,
650                       !Method->isConst());
651
652  // Distinct capture names, for diagnostics.
653  llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
654
655  // Handle explicit captures.
656  SourceLocation PrevCaptureLoc
657    = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
658  for (SmallVectorImpl<LambdaCapture>::const_iterator
659         C = Intro.Captures.begin(),
660         E = Intro.Captures.end();
661       C != E;
662       PrevCaptureLoc = C->Loc, ++C) {
663    if (C->Kind == LCK_This) {
664      // C++11 [expr.prim.lambda]p8:
665      //   An identifier or this shall not appear more than once in a
666      //   lambda-capture.
667      if (LSI->isCXXThisCaptured()) {
668        Diag(C->Loc, diag::err_capture_more_than_once)
669          << "'this'"
670          << SourceRange(LSI->getCXXThisCapture().getLocation())
671          << FixItHint::CreateRemoval(
672               SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
673        continue;
674      }
675
676      // C++11 [expr.prim.lambda]p8:
677      //   If a lambda-capture includes a capture-default that is =, the
678      //   lambda-capture shall not contain this [...].
679      if (Intro.Default == LCD_ByCopy) {
680        Diag(C->Loc, diag::err_this_capture_with_copy_default)
681          << FixItHint::CreateRemoval(
682               SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
683        continue;
684      }
685
686      // C++11 [expr.prim.lambda]p12:
687      //   If this is captured by a local lambda expression, its nearest
688      //   enclosing function shall be a non-static member function.
689      QualType ThisCaptureType = getCurrentThisType();
690      if (ThisCaptureType.isNull()) {
691        Diag(C->Loc, diag::err_this_capture) << true;
692        continue;
693      }
694
695      CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
696      continue;
697    }
698
699    assert(C->Id && "missing identifier for capture");
700
701    if (C->Init.isInvalid())
702      continue;
703
704    VarDecl *Var;
705    if (C->Init.isUsable()) {
706      if (C->Init.get()->containsUnexpandedParameterPack())
707        ContainsUnexpandedParameterPack = true;
708
709      Var = checkInitCapture(C->Loc, C->Kind == LCK_ByRef,
710                             C->Id, C->Init.take());
711      // C++1y [expr.prim.lambda]p11:
712      //   An init-capture behaves as if it declares and explicitly
713      //   captures a variable [...] whose declarative region is the
714      //   lambda-expression's compound-statement
715      if (Var)
716        PushOnScopeChains(Var, CurScope, false);
717    } else {
718      // C++11 [expr.prim.lambda]p8:
719      //   If a lambda-capture includes a capture-default that is &, the
720      //   identifiers in the lambda-capture shall not be preceded by &.
721      //   If a lambda-capture includes a capture-default that is =, [...]
722      //   each identifier it contains shall be preceded by &.
723      if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
724        Diag(C->Loc, diag::err_reference_capture_with_reference_default)
725          << FixItHint::CreateRemoval(
726               SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
727        continue;
728      } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
729        Diag(C->Loc, diag::err_copy_capture_with_copy_default)
730          << FixItHint::CreateRemoval(
731               SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
732        continue;
733      }
734
735      // C++11 [expr.prim.lambda]p10:
736      //   The identifiers in a capture-list are looked up using the usual
737      //   rules for unqualified name lookup (3.4.1)
738      DeclarationNameInfo Name(C->Id, C->Loc);
739      LookupResult R(*this, Name, LookupOrdinaryName);
740      LookupName(R, CurScope);
741      if (R.isAmbiguous())
742        continue;
743      if (R.empty()) {
744        // FIXME: Disable corrections that would add qualification?
745        CXXScopeSpec ScopeSpec;
746        DeclFilterCCC<VarDecl> Validator;
747        if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
748          continue;
749      }
750
751      Var = R.getAsSingle<VarDecl>();
752    }
753
754    // C++11 [expr.prim.lambda]p8:
755    //   An identifier or this shall not appear more than once in a
756    //   lambda-capture.
757    if (!CaptureNames.insert(C->Id)) {
758      if (Var && LSI->isCaptured(Var)) {
759        Diag(C->Loc, diag::err_capture_more_than_once)
760          << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
761          << FixItHint::CreateRemoval(
762               SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
763      } else
764        // Previous capture captured something different (one or both was
765        // an init-cpature): no fixit.
766        Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
767      continue;
768    }
769
770    // C++11 [expr.prim.lambda]p10:
771    //   [...] each such lookup shall find a variable with automatic storage
772    //   duration declared in the reaching scope of the local lambda expression.
773    // Note that the 'reaching scope' check happens in tryCaptureVariable().
774    if (!Var) {
775      Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
776      continue;
777    }
778
779    // Ignore invalid decls; they'll just confuse the code later.
780    if (Var->isInvalidDecl())
781      continue;
782
783    if (!Var->hasLocalStorage()) {
784      Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
785      Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
786      continue;
787    }
788
789    // C++11 [expr.prim.lambda]p23:
790    //   A capture followed by an ellipsis is a pack expansion (14.5.3).
791    SourceLocation EllipsisLoc;
792    if (C->EllipsisLoc.isValid()) {
793      if (Var->isParameterPack()) {
794        EllipsisLoc = C->EllipsisLoc;
795      } else {
796        Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
797          << SourceRange(C->Loc);
798
799        // Just ignore the ellipsis.
800      }
801    } else if (Var->isParameterPack()) {
802      ContainsUnexpandedParameterPack = true;
803    }
804
805    if (C->Init.isUsable()) {
806      buildInitCaptureField(LSI, Var);
807    } else {
808      TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
809                                                   TryCapture_ExplicitByVal;
810      tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
811    }
812  }
813  finishLambdaExplicitCaptures(LSI);
814
815  LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
816
817  // Add lambda parameters into scope.
818  addLambdaParameters(Method, CurScope);
819
820  // Enter a new evaluation context to insulate the lambda from any
821  // cleanups from the enclosing full-expression.
822  PushExpressionEvaluationContext(PotentiallyEvaluated);
823}
824
825void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
826                            bool IsInstantiation) {
827  // Leave the expression-evaluation context.
828  DiscardCleanupsInEvaluationContext();
829  PopExpressionEvaluationContext();
830
831  // Leave the context of the lambda.
832  if (!IsInstantiation)
833    PopDeclContext();
834
835  // Finalize the lambda.
836  LambdaScopeInfo *LSI = getCurLambda();
837  CXXRecordDecl *Class = LSI->Lambda;
838  Class->setInvalidDecl();
839  SmallVector<Decl*, 4> Fields;
840  for (RecordDecl::field_iterator i = Class->field_begin(),
841                                  e = Class->field_end(); i != e; ++i)
842    Fields.push_back(*i);
843  ActOnFields(0, Class->getLocation(), Class, Fields,
844              SourceLocation(), SourceLocation(), 0);
845  CheckCompletedCXXClass(Class);
846
847  PopFunctionScopeInfo();
848}
849
850/// \brief Add a lambda's conversion to function pointer, as described in
851/// C++11 [expr.prim.lambda]p6.
852static void addFunctionPointerConversion(Sema &S,
853                                         SourceRange IntroducerRange,
854                                         CXXRecordDecl *Class,
855                                         CXXMethodDecl *CallOperator) {
856  // FIXME: The conversion operator needs to be fixed for generic lambdas.
857  if (Class->isGenericLambda()) return;
858  // Add the conversion to function pointer.
859  const FunctionProtoType *Proto
860    = CallOperator->getType()->getAs<FunctionProtoType>();
861  QualType FunctionPtrTy;
862  QualType FunctionTy;
863  {
864    FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
865    CallingConv CC = S.Context.getDefaultCallingConvention(
866        Proto->isVariadic(), /*IsCXXMethod=*/false);
867    ExtInfo.ExtInfo = ExtInfo.ExtInfo.withCallingConv(CC);
868    ExtInfo.TypeQuals = 0;
869    FunctionTy = S.Context.getFunctionType(Proto->getResultType(),
870                                           Proto->getArgTypes(), ExtInfo);
871    FunctionPtrTy = S.Context.getPointerType(FunctionTy);
872  }
873
874  FunctionProtoType::ExtProtoInfo ExtInfo(S.Context.getDefaultCallingConvention(
875      /*IsVariadic=*/false, /*IsCXXMethod=*/true));
876  ExtInfo.TypeQuals = Qualifiers::Const;
877  QualType ConvTy = S.Context.getFunctionType(FunctionPtrTy, None, ExtInfo);
878
879  SourceLocation Loc = IntroducerRange.getBegin();
880  DeclarationName Name
881    = S.Context.DeclarationNames.getCXXConversionFunctionName(
882        S.Context.getCanonicalType(FunctionPtrTy));
883  DeclarationNameLoc NameLoc;
884  NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
885                                                               Loc);
886  CXXConversionDecl *Conversion
887    = CXXConversionDecl::Create(S.Context, Class, Loc,
888                                DeclarationNameInfo(Name, Loc, NameLoc),
889                                ConvTy,
890                                S.Context.getTrivialTypeSourceInfo(ConvTy,
891                                                                   Loc),
892                                /*isInline=*/true, /*isExplicit=*/false,
893                                /*isConstexpr=*/false,
894                                CallOperator->getBody()->getLocEnd());
895  Conversion->setAccess(AS_public);
896  Conversion->setImplicit(true);
897  Class->addDecl(Conversion);
898  // Add a non-static member function that will be the result of
899  // the conversion with a certain unique ID.
900  Name = &S.Context.Idents.get(getLambdaStaticInvokerName());
901  CXXMethodDecl *Invoke
902    = CXXMethodDecl::Create(S.Context, Class, Loc,
903                            DeclarationNameInfo(Name, Loc), FunctionTy,
904                            CallOperator->getTypeSourceInfo(),
905                            SC_Static, /*IsInline=*/true,
906                            /*IsConstexpr=*/false,
907                            CallOperator->getBody()->getLocEnd());
908  SmallVector<ParmVarDecl *, 4> InvokeParams;
909  for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
910    ParmVarDecl *From = CallOperator->getParamDecl(I);
911    InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
912                                               From->getLocStart(),
913                                               From->getLocation(),
914                                               From->getIdentifier(),
915                                               From->getType(),
916                                               From->getTypeSourceInfo(),
917                                               From->getStorageClass(),
918                                               /*DefaultArg=*/0));
919  }
920  Invoke->setParams(InvokeParams);
921  Invoke->setAccess(AS_private);
922  Invoke->setImplicit(true);
923  Class->addDecl(Invoke);
924}
925
926/// \brief Add a lambda's conversion to block pointer.
927static void addBlockPointerConversion(Sema &S,
928                                      SourceRange IntroducerRange,
929                                      CXXRecordDecl *Class,
930                                      CXXMethodDecl *CallOperator) {
931  const FunctionProtoType *Proto
932    = CallOperator->getType()->getAs<FunctionProtoType>();
933  QualType BlockPtrTy;
934  {
935    FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
936    ExtInfo.TypeQuals = 0;
937    QualType FunctionTy = S.Context.getFunctionType(
938        Proto->getResultType(), Proto->getArgTypes(), ExtInfo);
939    BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
940  }
941
942  FunctionProtoType::ExtProtoInfo ExtInfo(S.Context.getDefaultCallingConvention(
943      /*IsVariadic=*/false, /*IsCXXMethod=*/true));
944  ExtInfo.TypeQuals = Qualifiers::Const;
945  QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ExtInfo);
946
947  SourceLocation Loc = IntroducerRange.getBegin();
948  DeclarationName Name
949    = S.Context.DeclarationNames.getCXXConversionFunctionName(
950        S.Context.getCanonicalType(BlockPtrTy));
951  DeclarationNameLoc NameLoc;
952  NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
953  CXXConversionDecl *Conversion
954    = CXXConversionDecl::Create(S.Context, Class, Loc,
955                                DeclarationNameInfo(Name, Loc, NameLoc),
956                                ConvTy,
957                                S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
958                                /*isInline=*/true, /*isExplicit=*/false,
959                                /*isConstexpr=*/false,
960                                CallOperator->getBody()->getLocEnd());
961  Conversion->setAccess(AS_public);
962  Conversion->setImplicit(true);
963  Class->addDecl(Conversion);
964}
965
966ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
967                                 Scope *CurScope,
968                                 bool IsInstantiation) {
969  // Collect information from the lambda scope.
970  SmallVector<LambdaExpr::Capture, 4> Captures;
971  SmallVector<Expr *, 4> CaptureInits;
972  LambdaCaptureDefault CaptureDefault;
973  SourceLocation CaptureDefaultLoc;
974  CXXRecordDecl *Class;
975  CXXMethodDecl *CallOperator;
976  SourceRange IntroducerRange;
977  bool ExplicitParams;
978  bool ExplicitResultType;
979  bool LambdaExprNeedsCleanups;
980  bool ContainsUnexpandedParameterPack;
981  SmallVector<VarDecl *, 4> ArrayIndexVars;
982  SmallVector<unsigned, 4> ArrayIndexStarts;
983  {
984    LambdaScopeInfo *LSI = getCurLambda();
985    CallOperator = LSI->CallOperator;
986    Class = LSI->Lambda;
987    IntroducerRange = LSI->IntroducerRange;
988    ExplicitParams = LSI->ExplicitParams;
989    ExplicitResultType = !LSI->HasImplicitReturnType;
990    LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
991    ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
992    ArrayIndexVars.swap(LSI->ArrayIndexVars);
993    ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
994
995    // Translate captures.
996    for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
997      LambdaScopeInfo::Capture From = LSI->Captures[I];
998      assert(!From.isBlockCapture() && "Cannot capture __block variables");
999      bool IsImplicit = I >= LSI->NumExplicitCaptures;
1000
1001      // Handle 'this' capture.
1002      if (From.isThisCapture()) {
1003        Captures.push_back(LambdaExpr::Capture(From.getLocation(),
1004                                               IsImplicit,
1005                                               LCK_This));
1006        CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
1007                                                         getCurrentThisType(),
1008                                                         /*isImplicit=*/true));
1009        continue;
1010      }
1011
1012      VarDecl *Var = From.getVariable();
1013      LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
1014      Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
1015                                             Kind, Var, From.getEllipsisLoc()));
1016      CaptureInits.push_back(From.getInitExpr());
1017    }
1018
1019    switch (LSI->ImpCaptureStyle) {
1020    case CapturingScopeInfo::ImpCap_None:
1021      CaptureDefault = LCD_None;
1022      break;
1023
1024    case CapturingScopeInfo::ImpCap_LambdaByval:
1025      CaptureDefault = LCD_ByCopy;
1026      break;
1027
1028    case CapturingScopeInfo::ImpCap_CapturedRegion:
1029    case CapturingScopeInfo::ImpCap_LambdaByref:
1030      CaptureDefault = LCD_ByRef;
1031      break;
1032
1033    case CapturingScopeInfo::ImpCap_Block:
1034      llvm_unreachable("block capture in lambda");
1035      break;
1036    }
1037    CaptureDefaultLoc = LSI->CaptureDefaultLoc;
1038
1039    // C++11 [expr.prim.lambda]p4:
1040    //   If a lambda-expression does not include a
1041    //   trailing-return-type, it is as if the trailing-return-type
1042    //   denotes the following type:
1043    //
1044    // Skip for C++1y return type deduction semantics which uses
1045    // different machinery.
1046    // FIXME: Refactor and Merge the return type deduction machinery.
1047    // FIXME: Assumes current resolution to core issue 975.
1048    if (LSI->HasImplicitReturnType && !getLangOpts().CPlusPlus1y) {
1049      deduceClosureReturnType(*LSI);
1050
1051      //   - if there are no return statements in the
1052      //     compound-statement, or all return statements return
1053      //     either an expression of type void or no expression or
1054      //     braced-init-list, the type void;
1055      if (LSI->ReturnType.isNull()) {
1056        LSI->ReturnType = Context.VoidTy;
1057      }
1058
1059      // Create a function type with the inferred return type.
1060      const FunctionProtoType *Proto
1061        = CallOperator->getType()->getAs<FunctionProtoType>();
1062      QualType FunctionTy = Context.getFunctionType(
1063          LSI->ReturnType, Proto->getArgTypes(), Proto->getExtProtoInfo());
1064      CallOperator->setType(FunctionTy);
1065    }
1066    // C++ [expr.prim.lambda]p7:
1067    //   The lambda-expression's compound-statement yields the
1068    //   function-body (8.4) of the function call operator [...].
1069    ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
1070    CallOperator->setLexicalDeclContext(Class);
1071    Decl *TemplateOrNonTemplateCallOperatorDecl =
1072        CallOperator->getDescribedFunctionTemplate()
1073        ? CallOperator->getDescribedFunctionTemplate()
1074        : cast<Decl>(CallOperator);
1075
1076    TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
1077    Class->addDecl(TemplateOrNonTemplateCallOperatorDecl);
1078
1079    PopExpressionEvaluationContext();
1080
1081    // C++11 [expr.prim.lambda]p6:
1082    //   The closure type for a lambda-expression with no lambda-capture
1083    //   has a public non-virtual non-explicit const conversion function
1084    //   to pointer to function having the same parameter and return
1085    //   types as the closure type's function call operator.
1086    if (Captures.empty() && CaptureDefault == LCD_None)
1087      addFunctionPointerConversion(*this, IntroducerRange, Class,
1088                                   CallOperator);
1089
1090    // Objective-C++:
1091    //   The closure type for a lambda-expression has a public non-virtual
1092    //   non-explicit const conversion function to a block pointer having the
1093    //   same parameter and return types as the closure type's function call
1094    //   operator.
1095    if (getLangOpts().Blocks && getLangOpts().ObjC1)
1096      addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
1097
1098    // Finalize the lambda class.
1099    SmallVector<Decl*, 4> Fields;
1100    for (RecordDecl::field_iterator i = Class->field_begin(),
1101                                    e = Class->field_end(); i != e; ++i)
1102      Fields.push_back(*i);
1103    ActOnFields(0, Class->getLocation(), Class, Fields,
1104                SourceLocation(), SourceLocation(), 0);
1105    CheckCompletedCXXClass(Class);
1106  }
1107
1108  if (LambdaExprNeedsCleanups)
1109    ExprNeedsCleanups = true;
1110
1111  LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
1112                                          CaptureDefault, CaptureDefaultLoc,
1113                                          Captures,
1114                                          ExplicitParams, ExplicitResultType,
1115                                          CaptureInits, ArrayIndexVars,
1116                                          ArrayIndexStarts, Body->getLocEnd(),
1117                                          ContainsUnexpandedParameterPack);
1118  Class->setLambdaExpr(Lambda);
1119  // C++11 [expr.prim.lambda]p2:
1120  //   A lambda-expression shall not appear in an unevaluated operand
1121  //   (Clause 5).
1122  if (!CurContext->isDependentContext()) {
1123    switch (ExprEvalContexts.back().Context) {
1124    case Unevaluated:
1125    case UnevaluatedAbstract:
1126      // We don't actually diagnose this case immediately, because we
1127      // could be within a context where we might find out later that
1128      // the expression is potentially evaluated (e.g., for typeid).
1129      ExprEvalContexts.back().Lambdas.push_back(Lambda);
1130      break;
1131
1132    case ConstantEvaluated:
1133    case PotentiallyEvaluated:
1134    case PotentiallyEvaluatedIfUsed:
1135      break;
1136    }
1137  }
1138  // TODO: Implement capturing.
1139  if (Lambda->isGenericLambda()) {
1140    if (Lambda->getCaptureDefault() != LCD_None) {
1141      Diag(Lambda->getIntroducerRange().getBegin(),
1142        diag::err_glambda_not_fully_implemented)
1143        << " capturing not implemented yet";
1144      return ExprError();
1145    }
1146  }
1147  return MaybeBindToTemporary(Lambda);
1148}
1149
1150ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
1151                                               SourceLocation ConvLocation,
1152                                               CXXConversionDecl *Conv,
1153                                               Expr *Src) {
1154  // Make sure that the lambda call operator is marked used.
1155  CXXRecordDecl *Lambda = Conv->getParent();
1156  CXXMethodDecl *CallOperator
1157    = cast<CXXMethodDecl>(
1158        Lambda->lookup(
1159          Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
1160  CallOperator->setReferenced();
1161  CallOperator->markUsed(Context);
1162
1163  ExprResult Init = PerformCopyInitialization(
1164                      InitializedEntity::InitializeBlock(ConvLocation,
1165                                                         Src->getType(),
1166                                                         /*NRVO=*/false),
1167                      CurrentLocation, Src);
1168  if (!Init.isInvalid())
1169    Init = ActOnFinishFullExpr(Init.take());
1170
1171  if (Init.isInvalid())
1172    return ExprError();
1173
1174  // Create the new block to be returned.
1175  BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
1176
1177  // Set the type information.
1178  Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
1179  Block->setIsVariadic(CallOperator->isVariadic());
1180  Block->setBlockMissingReturnType(false);
1181
1182  // Add parameters.
1183  SmallVector<ParmVarDecl *, 4> BlockParams;
1184  for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1185    ParmVarDecl *From = CallOperator->getParamDecl(I);
1186    BlockParams.push_back(ParmVarDecl::Create(Context, Block,
1187                                              From->getLocStart(),
1188                                              From->getLocation(),
1189                                              From->getIdentifier(),
1190                                              From->getType(),
1191                                              From->getTypeSourceInfo(),
1192                                              From->getStorageClass(),
1193                                              /*DefaultArg=*/0));
1194  }
1195  Block->setParams(BlockParams);
1196
1197  Block->setIsConversionFromLambda(true);
1198
1199  // Add capture. The capture uses a fake variable, which doesn't correspond
1200  // to any actual memory location. However, the initializer copy-initializes
1201  // the lambda object.
1202  TypeSourceInfo *CapVarTSI =
1203      Context.getTrivialTypeSourceInfo(Src->getType());
1204  VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1205                                    ConvLocation, 0,
1206                                    Src->getType(), CapVarTSI,
1207                                    SC_None);
1208  BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
1209                             /*Nested=*/false, /*Copy=*/Init.take());
1210  Block->setCaptures(Context, &Capture, &Capture + 1,
1211                     /*CapturesCXXThis=*/false);
1212
1213  // Add a fake function body to the block. IR generation is responsible
1214  // for filling in the actual body, which cannot be expressed as an AST.
1215  Block->setBody(new (Context) CompoundStmt(ConvLocation));
1216
1217  // Create the block literal expression.
1218  Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1219  ExprCleanupObjects.push_back(Block);
1220  ExprNeedsCleanups = true;
1221
1222  return BuildBlock;
1223}
1224