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