1234287Sdim//===--- SemaLambda.cpp - Semantic Analysis for C++11 Lambdas -------------===//
2234287Sdim//
3234287Sdim//                     The LLVM Compiler Infrastructure
4234287Sdim//
5234287Sdim// This file is distributed under the University of Illinois Open Source
6234287Sdim// License. See LICENSE.TXT for details.
7234287Sdim//
8234287Sdim//===----------------------------------------------------------------------===//
9234287Sdim//
10234287Sdim//  This file implements semantic analysis for C++ lambda expressions.
11234287Sdim//
12234287Sdim//===----------------------------------------------------------------------===//
13234287Sdim#include "clang/Sema/DeclSpec.h"
14263509Sdim#include "clang/AST/ASTLambda.h"
15252723Sdim#include "clang/AST/ExprCXX.h"
16263509Sdim#include "clang/Basic/TargetInfo.h"
17252723Sdim#include "clang/Lex/Preprocessor.h"
18234287Sdim#include "clang/Sema/Initialization.h"
19234287Sdim#include "clang/Sema/Lookup.h"
20234287Sdim#include "clang/Sema/Scope.h"
21234287Sdim#include "clang/Sema/ScopeInfo.h"
22234287Sdim#include "clang/Sema/SemaInternal.h"
23263509Sdim#include "clang/Sema/SemaLambda.h"
24263509Sdim#include "TypeLocBuilder.h"
25234287Sdimusing namespace clang;
26234287Sdimusing namespace sema;
27234287Sdim
28263509Sdim// returns -1 if none of the lambdas on the scope stack can capture.
29263509Sdim// A lambda 'L' is capture-ready for a certain variable 'V' if,
30263509Sdim//  - its enclosing context is non-dependent
31263509Sdim//  - and if the chain of lambdas between L and the lambda in which
32263509Sdim//    V is potentially used, call all capture or have captured V.
33263509Sdimstatic inline int GetScopeIndexOfNearestCaptureReadyLambda(
34263509Sdim    ArrayRef<clang::sema::FunctionScopeInfo*> FunctionScopes,
35263509Sdim    DeclContext *const CurContext, VarDecl *VD) {
36263509Sdim
37263509Sdim  DeclContext *EnclosingDC = CurContext;
38263509Sdim  // If VD is null, we are attempting to capture 'this'
39263509Sdim  const bool IsCapturingThis = !VD;
40263509Sdim  const bool IsCapturingVariable = !IsCapturingThis;
41263509Sdim  int RetIndex = -1;
42263509Sdim  unsigned CurScopeIndex = FunctionScopes.size() - 1;
43263509Sdim  while (!EnclosingDC->isTranslationUnit() &&
44263509Sdim      EnclosingDC->isDependentContext() && isLambdaCallOperator(EnclosingDC)) {
45263509Sdim    RetIndex = CurScopeIndex;
46263509Sdim    clang::sema::LambdaScopeInfo *LSI =
47263509Sdim          cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]);
48263509Sdim    // We have crawled up to an intervening lambda that contains the
49263509Sdim    // variable declaration - so not only does it not need to capture;
50263509Sdim    // none of the enclosing lambdas need to capture it, and since all
51263509Sdim    // other nested lambdas are dependent (otherwise we wouldn't have
52263509Sdim    // arrived here) - we don't yet have a lambda that can capture the
53263509Sdim    // variable.
54263509Sdim    if (IsCapturingVariable && VD->getDeclContext()->Equals(EnclosingDC))
55263509Sdim      return -1;
56263509Sdim    // All intervening lambda call operators have to be able to capture.
57263509Sdim    // If they do not have a default implicit capture, check to see
58263509Sdim    // if the entity has already been explicitly captured.
59263509Sdim    // If even a single dependent enclosing lambda lacks the capability
60263509Sdim    // to ever capture this variable, there is no further enclosing
61263509Sdim    // non-dependent lambda that can capture this variable.
62263509Sdim    if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) {
63263509Sdim      if (IsCapturingVariable && !LSI->isCaptured(VD))
64263509Sdim        return -1;
65263509Sdim      if (IsCapturingThis && !LSI->isCXXThisCaptured())
66263509Sdim        return -1;
67263509Sdim    }
68263509Sdim    EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC);
69263509Sdim    --CurScopeIndex;
70263509Sdim  }
71263509Sdim  // If the enclosingDC is not dependent, then the immediately nested lambda
72263509Sdim  // is capture-ready.
73263509Sdim  if (!EnclosingDC->isDependentContext())
74263509Sdim    return RetIndex;
75263509Sdim  return -1;
76263509Sdim}
77263509Sdim// Given a lambda's call operator and a variable (or null for 'this'),
78263509Sdim// compute the nearest enclosing lambda that is capture-ready (i.e
79263509Sdim// the enclosing context is not dependent, and all intervening lambdas can
80263509Sdim// either implicitly or explicitly capture Var)
81263509Sdim//
82263509Sdim// The approach is as follows, for the entity VD ('this' if null):
83263509Sdim//   - start with the current lambda
84263509Sdim//     - if it is non-dependent and can capture VD, return it.
85263509Sdim//     - if it is dependent and has an implicit or explicit capture, check its parent
86263509Sdim//       whether the parent is non-depdendent and all its intervening lambdas
87263509Sdim//       can capture, if so return the child.
88263509Sdim//       [Note: When we hit a generic lambda specialization, do not climb up
89263509Sdim//         the scope stack any further since not only do we not need to,
90263509Sdim//         the scope stack will often not be synchronized with any lambdas
91263509Sdim//         enclosing the specialized generic lambda]
92263509Sdim//
93263509Sdim// Return the CallOperator of the capturable lambda and set function scope
94263509Sdim// index to the correct index within the function scope stack to correspond
95263509Sdim// to the capturable lambda.
96263509Sdim// If VarDecl *VD is null, we check for 'this' capture.
97263509SdimCXXMethodDecl* clang::GetInnermostEnclosingCapturableLambda(
98263509Sdim                             ArrayRef<sema::FunctionScopeInfo*> FunctionScopes,
99263509Sdim                             unsigned &FunctionScopeIndex,
100263509Sdim                             DeclContext *const CurContext, VarDecl *VD,
101263509Sdim                             Sema &S) {
102263509Sdim
103263509Sdim  const int IndexOfCaptureReadyLambda =
104263509Sdim      GetScopeIndexOfNearestCaptureReadyLambda(FunctionScopes,CurContext, VD);
105263509Sdim  if (IndexOfCaptureReadyLambda == -1) return 0;
106263509Sdim  assert(IndexOfCaptureReadyLambda >= 0);
107263509Sdim  const unsigned IndexOfCaptureReadyLambdaU =
108263509Sdim      static_cast<unsigned>(IndexOfCaptureReadyLambda);
109263509Sdim  sema::LambdaScopeInfo *const CaptureReadyLambdaLSI =
110263509Sdim      cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambdaU]);
111263509Sdim  // If VD is null, we are attempting to capture 'this'
112263509Sdim  const bool IsCapturingThis = !VD;
113263509Sdim  const bool IsCapturingVariable = !IsCapturingThis;
114263509Sdim
115263509Sdim  if (IsCapturingVariable) {
116263509Sdim    // Now check to see if this lambda can truly capture, and also
117263509Sdim    // if all enclosing lambdas of this lambda allow this capture.
118263509Sdim    QualType CaptureType, DeclRefType;
119263509Sdim    const bool CanCaptureVariable = !S.tryCaptureVariable(VD,
120263509Sdim      /*ExprVarIsUsedInLoc*/SourceLocation(), clang::Sema::TryCapture_Implicit,
121263509Sdim      /*EllipsisLoc*/ SourceLocation(),
122263509Sdim      /*BuildAndDiagnose*/false, CaptureType, DeclRefType,
123263509Sdim      &IndexOfCaptureReadyLambdaU);
124263509Sdim    if (!CanCaptureVariable) return 0;
125263509Sdim  } else {
126263509Sdim    const bool CanCaptureThis = !S.CheckCXXThisCapture(
127263509Sdim        CaptureReadyLambdaLSI->PotentialThisCaptureLocation, false, false,
128263509Sdim        &IndexOfCaptureReadyLambdaU);
129263509Sdim    if (!CanCaptureThis) return 0;
130263509Sdim  } // end 'this' capture test
131263509Sdim  FunctionScopeIndex = IndexOfCaptureReadyLambdaU;
132263509Sdim  return CaptureReadyLambdaLSI->CallOperator;
133263509Sdim}
134263509Sdim
135263509Sdimstatic inline TemplateParameterList *
136263509SdimgetGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) {
137263509Sdim  if (LSI->GLTemplateParameterList)
138263509Sdim    return LSI->GLTemplateParameterList;
139263509Sdim
140263509Sdim  if (LSI->AutoTemplateParams.size()) {
141263509Sdim    SourceRange IntroRange = LSI->IntroducerRange;
142263509Sdim    SourceLocation LAngleLoc = IntroRange.getBegin();
143263509Sdim    SourceLocation RAngleLoc = IntroRange.getEnd();
144263509Sdim    LSI->GLTemplateParameterList = TemplateParameterList::Create(
145263509Sdim                                   SemaRef.Context,
146263509Sdim                                   /*Template kw loc*/SourceLocation(),
147263509Sdim                                   LAngleLoc,
148263509Sdim                                   (NamedDecl**)LSI->AutoTemplateParams.data(),
149263509Sdim                                   LSI->AutoTemplateParams.size(), RAngleLoc);
150263509Sdim  }
151263509Sdim  return LSI->GLTemplateParameterList;
152263509Sdim}
153263509Sdim
154263509Sdim
155263509Sdim
156234287SdimCXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
157245431Sdim                                             TypeSourceInfo *Info,
158263509Sdim                                             bool KnownDependent,
159263509Sdim                                             LambdaCaptureDefault CaptureDefault) {
160234287Sdim  DeclContext *DC = CurContext;
161234287Sdim  while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
162234287Sdim    DC = DC->getParent();
163263509Sdim  bool IsGenericLambda = getGenericLambdaTemplateParameterList(getCurLambda(),
164263509Sdim                                                               *this);
165234287Sdim  // Start constructing the lambda class.
166245431Sdim  CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info,
167234287Sdim                                                     IntroducerRange.getBegin(),
168263509Sdim                                                     KnownDependent,
169263509Sdim                                                     IsGenericLambda,
170263509Sdim                                                     CaptureDefault);
171234287Sdim  DC->addDecl(Class);
172234287Sdim
173234287Sdim  return Class;
174234287Sdim}
175234287Sdim
176234287Sdim/// \brief Determine whether the given context is or is enclosed in an inline
177234287Sdim/// function.
178234287Sdimstatic bool isInInlineFunction(const DeclContext *DC) {
179234287Sdim  while (!DC->isFileContext()) {
180234287Sdim    if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
181234287Sdim      if (FD->isInlined())
182234287Sdim        return true;
183234287Sdim
184234287Sdim    DC = DC->getLexicalParent();
185234287Sdim  }
186234287Sdim
187234287Sdim  return false;
188234287Sdim}
189234287Sdim
190263509SdimMangleNumberingContext *
191263509SdimSema::getCurrentMangleNumberContext(const DeclContext *DC,
192263509Sdim                                    Decl *&ManglingContextDecl) {
193263509Sdim  // Compute the context for allocating mangling numbers in the current
194263509Sdim  // expression, if the ABI requires them.
195263509Sdim  ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
196245431Sdim
197245431Sdim  enum ContextKind {
198245431Sdim    Normal,
199245431Sdim    DefaultArgument,
200245431Sdim    DataMember,
201245431Sdim    StaticDataMember
202245431Sdim  } Kind = Normal;
203245431Sdim
204245431Sdim  // Default arguments of member function parameters that appear in a class
205245431Sdim  // definition, as well as the initializers of data members, receive special
206245431Sdim  // treatment. Identify them.
207263509Sdim  if (ManglingContextDecl) {
208263509Sdim    if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
209245431Sdim      if (const DeclContext *LexicalDC
210245431Sdim          = Param->getDeclContext()->getLexicalParent())
211245431Sdim        if (LexicalDC->isRecord())
212245431Sdim          Kind = DefaultArgument;
213263509Sdim    } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
214245431Sdim      if (Var->getDeclContext()->isRecord())
215245431Sdim        Kind = StaticDataMember;
216263509Sdim    } else if (isa<FieldDecl>(ManglingContextDecl)) {
217245431Sdim      Kind = DataMember;
218234287Sdim    }
219234287Sdim  }
220234287Sdim
221245431Sdim  // Itanium ABI [5.1.7]:
222245431Sdim  //   In the following contexts [...] the one-definition rule requires closure
223245431Sdim  //   types in different translation units to "correspond":
224245431Sdim  bool IsInNonspecializedTemplate =
225245431Sdim    !ActiveTemplateInstantiations.empty() || CurContext->isDependentContext();
226245431Sdim  switch (Kind) {
227245431Sdim  case Normal:
228245431Sdim    //  -- the bodies of non-exported nonspecialized template functions
229245431Sdim    //  -- the bodies of inline functions
230245431Sdim    if ((IsInNonspecializedTemplate &&
231263509Sdim         !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
232263509Sdim        isInInlineFunction(CurContext)) {
233263509Sdim      ManglingContextDecl = 0;
234263509Sdim      return &Context.getManglingNumberContext(DC);
235263509Sdim    }
236245431Sdim
237263509Sdim    ManglingContextDecl = 0;
238263509Sdim    return 0;
239245431Sdim
240245431Sdim  case StaticDataMember:
241245431Sdim    //  -- the initializers of nonspecialized static members of template classes
242245431Sdim    if (!IsInNonspecializedTemplate) {
243263509Sdim      ManglingContextDecl = 0;
244263509Sdim      return 0;
245245431Sdim    }
246263509Sdim    // Fall through to get the current context.
247245431Sdim
248245431Sdim  case DataMember:
249245431Sdim    //  -- the in-class initializers of class members
250245431Sdim  case DefaultArgument:
251245431Sdim    //  -- default arguments appearing in class definitions
252263509Sdim    return &ExprEvalContexts.back().getMangleNumberingContext(Context);
253245431Sdim  }
254245431Sdim
255263509Sdim  llvm_unreachable("unexpected context");
256263509Sdim}
257245431Sdim
258263509SdimMangleNumberingContext &
259263509SdimSema::ExpressionEvaluationContextRecord::getMangleNumberingContext(
260263509Sdim    ASTContext &Ctx) {
261263509Sdim  assert(ManglingContextDecl && "Need to have a context declaration");
262263509Sdim  if (!MangleNumbering)
263263509Sdim    MangleNumbering = Ctx.createMangleNumberingContext();
264263509Sdim  return *MangleNumbering;
265263509Sdim}
266263509Sdim
267263509SdimCXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
268263509Sdim                                           SourceRange IntroducerRange,
269263509Sdim                                           TypeSourceInfo *MethodTypeInfo,
270263509Sdim                                           SourceLocation EndLoc,
271263509Sdim                                           ArrayRef<ParmVarDecl *> Params) {
272263509Sdim  QualType MethodType = MethodTypeInfo->getType();
273263509Sdim  TemplateParameterList *TemplateParams =
274263509Sdim            getGenericLambdaTemplateParameterList(getCurLambda(), *this);
275263509Sdim  // If a lambda appears in a dependent context or is a generic lambda (has
276263509Sdim  // template parameters) and has an 'auto' return type, deduce it to a
277263509Sdim  // dependent type.
278263509Sdim  if (Class->isDependentContext() || TemplateParams) {
279263509Sdim    const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
280263509Sdim    QualType Result = FPT->getResultType();
281263509Sdim    if (Result->isUndeducedType()) {
282263509Sdim      Result = SubstAutoType(Result, Context.DependentTy);
283263509Sdim      MethodType = Context.getFunctionType(Result, FPT->getArgTypes(),
284263509Sdim                                           FPT->getExtProtoInfo());
285263509Sdim    }
286263509Sdim  }
287263509Sdim
288263509Sdim  // C++11 [expr.prim.lambda]p5:
289263509Sdim  //   The closure type for a lambda-expression has a public inline function
290263509Sdim  //   call operator (13.5.4) whose parameters and return type are described by
291263509Sdim  //   the lambda-expression's parameter-declaration-clause and
292263509Sdim  //   trailing-return-type respectively.
293263509Sdim  DeclarationName MethodName
294263509Sdim    = Context.DeclarationNames.getCXXOperatorName(OO_Call);
295263509Sdim  DeclarationNameLoc MethodNameLoc;
296263509Sdim  MethodNameLoc.CXXOperatorName.BeginOpNameLoc
297263509Sdim    = IntroducerRange.getBegin().getRawEncoding();
298263509Sdim  MethodNameLoc.CXXOperatorName.EndOpNameLoc
299263509Sdim    = IntroducerRange.getEnd().getRawEncoding();
300263509Sdim  CXXMethodDecl *Method
301263509Sdim    = CXXMethodDecl::Create(Context, Class, EndLoc,
302263509Sdim                            DeclarationNameInfo(MethodName,
303263509Sdim                                                IntroducerRange.getBegin(),
304263509Sdim                                                MethodNameLoc),
305263509Sdim                            MethodType, MethodTypeInfo,
306263509Sdim                            SC_None,
307263509Sdim                            /*isInline=*/true,
308263509Sdim                            /*isConstExpr=*/false,
309263509Sdim                            EndLoc);
310263509Sdim  Method->setAccess(AS_public);
311263509Sdim
312263509Sdim  // Temporarily set the lexical declaration context to the current
313263509Sdim  // context, so that the Scope stack matches the lexical nesting.
314263509Sdim  Method->setLexicalDeclContext(CurContext);
315263509Sdim  // Create a function template if we have a template parameter list
316263509Sdim  FunctionTemplateDecl *const TemplateMethod = TemplateParams ?
317263509Sdim            FunctionTemplateDecl::Create(Context, Class,
318263509Sdim                                         Method->getLocation(), MethodName,
319263509Sdim                                         TemplateParams,
320263509Sdim                                         Method) : 0;
321263509Sdim  if (TemplateMethod) {
322263509Sdim    TemplateMethod->setLexicalDeclContext(CurContext);
323263509Sdim    TemplateMethod->setAccess(AS_public);
324263509Sdim    Method->setDescribedFunctionTemplate(TemplateMethod);
325263509Sdim  }
326263509Sdim
327263509Sdim  // Add parameters.
328263509Sdim  if (!Params.empty()) {
329263509Sdim    Method->setParams(Params);
330263509Sdim    CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
331263509Sdim                             const_cast<ParmVarDecl **>(Params.end()),
332263509Sdim                             /*CheckParameterNames=*/false);
333263509Sdim
334263509Sdim    for (CXXMethodDecl::param_iterator P = Method->param_begin(),
335263509Sdim                                    PEnd = Method->param_end();
336263509Sdim         P != PEnd; ++P)
337263509Sdim      (*P)->setOwningFunction(Method);
338263509Sdim  }
339263509Sdim
340263509Sdim  Decl *ManglingContextDecl;
341263509Sdim  if (MangleNumberingContext *MCtx =
342263509Sdim          getCurrentMangleNumberContext(Class->getDeclContext(),
343263509Sdim                                        ManglingContextDecl)) {
344263509Sdim    unsigned ManglingNumber = MCtx->getManglingNumber(Method);
345263509Sdim    Class->setLambdaMangling(ManglingNumber, ManglingContextDecl);
346263509Sdim  }
347263509Sdim
348234287Sdim  return Method;
349234287Sdim}
350234287Sdim
351263509Sdimvoid Sema::buildLambdaScope(LambdaScopeInfo *LSI,
352263509Sdim                                        CXXMethodDecl *CallOperator,
353234287Sdim                                        SourceRange IntroducerRange,
354234287Sdim                                        LambdaCaptureDefault CaptureDefault,
355263509Sdim                                        SourceLocation CaptureDefaultLoc,
356234287Sdim                                        bool ExplicitParams,
357234287Sdim                                        bool ExplicitResultType,
358234287Sdim                                        bool Mutable) {
359263509Sdim  LSI->CallOperator = CallOperator;
360263509Sdim  CXXRecordDecl *LambdaClass = CallOperator->getParent();
361263509Sdim  LSI->Lambda = LambdaClass;
362234287Sdim  if (CaptureDefault == LCD_ByCopy)
363234287Sdim    LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
364234287Sdim  else if (CaptureDefault == LCD_ByRef)
365234287Sdim    LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
366263509Sdim  LSI->CaptureDefaultLoc = CaptureDefaultLoc;
367234287Sdim  LSI->IntroducerRange = IntroducerRange;
368234287Sdim  LSI->ExplicitParams = ExplicitParams;
369234287Sdim  LSI->Mutable = Mutable;
370234287Sdim
371234287Sdim  if (ExplicitResultType) {
372234287Sdim    LSI->ReturnType = CallOperator->getResultType();
373234287Sdim
374234287Sdim    if (!LSI->ReturnType->isDependentType() &&
375234287Sdim        !LSI->ReturnType->isVoidType()) {
376234287Sdim      if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
377234287Sdim                              diag::err_lambda_incomplete_result)) {
378234287Sdim        // Do nothing.
379234287Sdim      }
380234287Sdim    }
381234287Sdim  } else {
382234287Sdim    LSI->HasImplicitReturnType = true;
383234287Sdim  }
384234287Sdim}
385234287Sdim
386234287Sdimvoid Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
387234287Sdim  LSI->finishedExplicitCaptures();
388234287Sdim}
389234287Sdim
390234287Sdimvoid Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
391234287Sdim  // Introduce our parameters into the function scope
392234287Sdim  for (unsigned p = 0, NumParams = CallOperator->getNumParams();
393234287Sdim       p < NumParams; ++p) {
394234287Sdim    ParmVarDecl *Param = CallOperator->getParamDecl(p);
395234287Sdim
396234287Sdim    // If this has an identifier, add it to the scope stack.
397234287Sdim    if (CurScope && Param->getIdentifier()) {
398234287Sdim      CheckShadow(CurScope, Param);
399234287Sdim
400234287Sdim      PushOnScopeChains(Param, CurScope);
401234287Sdim    }
402234287Sdim  }
403234287Sdim}
404234287Sdim
405252723Sdim/// If this expression is an enumerator-like expression of some type
406252723Sdim/// T, return the type T; otherwise, return null.
407252723Sdim///
408252723Sdim/// Pointer comparisons on the result here should always work because
409252723Sdim/// it's derived from either the parent of an EnumConstantDecl
410252723Sdim/// (i.e. the definition) or the declaration returned by
411252723Sdim/// EnumType::getDecl() (i.e. the definition).
412252723Sdimstatic EnumDecl *findEnumForBlockReturn(Expr *E) {
413252723Sdim  // An expression is an enumerator-like expression of type T if,
414252723Sdim  // ignoring parens and parens-like expressions:
415252723Sdim  E = E->IgnoreParens();
416245431Sdim
417252723Sdim  //  - it is an enumerator whose enum type is T or
418252723Sdim  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
419252723Sdim    if (EnumConstantDecl *D
420252723Sdim          = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
421252723Sdim      return cast<EnumDecl>(D->getDeclContext());
422252723Sdim    }
423252723Sdim    return 0;
424245431Sdim  }
425245431Sdim
426252723Sdim  //  - it is a comma expression whose RHS is an enumerator-like
427252723Sdim  //    expression of type T or
428252723Sdim  if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
429252723Sdim    if (BO->getOpcode() == BO_Comma)
430252723Sdim      return findEnumForBlockReturn(BO->getRHS());
431252723Sdim    return 0;
432252723Sdim  }
433245431Sdim
434252723Sdim  //  - it is a statement-expression whose value expression is an
435252723Sdim  //    enumerator-like expression of type T or
436252723Sdim  if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
437252723Sdim    if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
438252723Sdim      return findEnumForBlockReturn(last);
439252723Sdim    return 0;
440245431Sdim  }
441245431Sdim
442252723Sdim  //   - it is a ternary conditional operator (not the GNU ?:
443252723Sdim  //     extension) whose second and third operands are
444252723Sdim  //     enumerator-like expressions of type T or
445252723Sdim  if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
446252723Sdim    if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
447252723Sdim      if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
448252723Sdim        return ED;
449252723Sdim    return 0;
450252723Sdim  }
451245431Sdim
452252723Sdim  // (implicitly:)
453252723Sdim  //   - it is an implicit integral conversion applied to an
454252723Sdim  //     enumerator-like expression of type T or
455252723Sdim  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
456263509Sdim    // We can sometimes see integral conversions in valid
457263509Sdim    // enumerator-like expressions.
458252723Sdim    if (ICE->getCastKind() == CK_IntegralCast)
459252723Sdim      return findEnumForBlockReturn(ICE->getSubExpr());
460263509Sdim
461263509Sdim    // Otherwise, just rely on the type.
462245431Sdim  }
463245431Sdim
464252723Sdim  //   - it is an expression of that formal enum type.
465252723Sdim  if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
466252723Sdim    return ET->getDecl();
467245431Sdim  }
468245431Sdim
469252723Sdim  // Otherwise, nope.
470252723Sdim  return 0;
471252723Sdim}
472252723Sdim
473252723Sdim/// Attempt to find a type T for which the returned expression of the
474252723Sdim/// given statement is an enumerator-like expression of that type.
475252723Sdimstatic EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
476252723Sdim  if (Expr *retValue = ret->getRetValue())
477252723Sdim    return findEnumForBlockReturn(retValue);
478252723Sdim  return 0;
479252723Sdim}
480252723Sdim
481252723Sdim/// Attempt to find a common type T for which all of the returned
482252723Sdim/// expressions in a block are enumerator-like expressions of that
483252723Sdim/// type.
484252723Sdimstatic EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
485252723Sdim  ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
486252723Sdim
487252723Sdim  // Try to find one for the first return.
488252723Sdim  EnumDecl *ED = findEnumForBlockReturn(*i);
489252723Sdim  if (!ED) return 0;
490252723Sdim
491252723Sdim  // Check that the rest of the returns have the same enum.
492252723Sdim  for (++i; i != e; ++i) {
493252723Sdim    if (findEnumForBlockReturn(*i) != ED)
494252723Sdim      return 0;
495245431Sdim  }
496245431Sdim
497252723Sdim  // Never infer an anonymous enum type.
498252723Sdim  if (!ED->hasNameForLinkage()) return 0;
499252723Sdim
500252723Sdim  return ED;
501245431Sdim}
502245431Sdim
503252723Sdim/// Adjust the given return statements so that they formally return
504252723Sdim/// the given type.  It should require, at most, an IntegralCast.
505252723Sdimstatic void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
506252723Sdim                                     QualType returnType) {
507252723Sdim  for (ArrayRef<ReturnStmt*>::iterator
508252723Sdim         i = returns.begin(), e = returns.end(); i != e; ++i) {
509252723Sdim    ReturnStmt *ret = *i;
510252723Sdim    Expr *retValue = ret->getRetValue();
511252723Sdim    if (S.Context.hasSameType(retValue->getType(), returnType))
512252723Sdim      continue;
513252723Sdim
514252723Sdim    // Right now we only support integral fixup casts.
515252723Sdim    assert(returnType->isIntegralOrUnscopedEnumerationType());
516252723Sdim    assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
517252723Sdim
518252723Sdim    ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
519252723Sdim
520252723Sdim    Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
521252723Sdim    E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast,
522252723Sdim                                 E, /*base path*/ 0, VK_RValue);
523252723Sdim    if (cleanups) {
524252723Sdim      cleanups->setSubExpr(E);
525252723Sdim    } else {
526252723Sdim      ret->setRetValue(E);
527252723Sdim    }
528252723Sdim  }
529252723Sdim}
530252723Sdim
531245431Sdimvoid Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
532245431Sdim  assert(CSI.HasImplicitReturnType);
533263509Sdim  // If it was ever a placeholder, it had to been deduced to DependentTy.
534263509Sdim  assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
535245431Sdim
536252723Sdim  // C++ Core Issue #975, proposed resolution:
537252723Sdim  //   If a lambda-expression does not include a trailing-return-type,
538252723Sdim  //   it is as if the trailing-return-type denotes the following type:
539252723Sdim  //     - if there are no return statements in the compound-statement,
540252723Sdim  //       or all return statements return either an expression of type
541252723Sdim  //       void or no expression or braced-init-list, the type void;
542252723Sdim  //     - otherwise, if all return statements return an expression
543252723Sdim  //       and the types of the returned expressions after
544252723Sdim  //       lvalue-to-rvalue conversion (4.1 [conv.lval]),
545252723Sdim  //       array-to-pointer conversion (4.2 [conv.array]), and
546252723Sdim  //       function-to-pointer conversion (4.3 [conv.func]) are the
547252723Sdim  //       same, that common type;
548252723Sdim  //     - otherwise, the program is ill-formed.
549252723Sdim  //
550252723Sdim  // In addition, in blocks in non-C++ modes, if all of the return
551252723Sdim  // statements are enumerator-like expressions of some type T, where
552252723Sdim  // T has a name for linkage, then we infer the return type of the
553252723Sdim  // block to be that type.
554252723Sdim
555245431Sdim  // First case: no return statements, implicit void return type.
556245431Sdim  ASTContext &Ctx = getASTContext();
557245431Sdim  if (CSI.Returns.empty()) {
558245431Sdim    // It's possible there were simply no /valid/ return statements.
559245431Sdim    // In this case, the first one we found may have at least given us a type.
560245431Sdim    if (CSI.ReturnType.isNull())
561245431Sdim      CSI.ReturnType = Ctx.VoidTy;
562245431Sdim    return;
563245431Sdim  }
564245431Sdim
565245431Sdim  // Second case: at least one return statement has dependent type.
566245431Sdim  // Delay type checking until instantiation.
567245431Sdim  assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
568245431Sdim  if (CSI.ReturnType->isDependentType())
569245431Sdim    return;
570245431Sdim
571252723Sdim  // Try to apply the enum-fuzz rule.
572252723Sdim  if (!getLangOpts().CPlusPlus) {
573252723Sdim    assert(isa<BlockScopeInfo>(CSI));
574252723Sdim    const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
575252723Sdim    if (ED) {
576252723Sdim      CSI.ReturnType = Context.getTypeDeclType(ED);
577252723Sdim      adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
578252723Sdim      return;
579252723Sdim    }
580252723Sdim  }
581252723Sdim
582245431Sdim  // Third case: only one return statement. Don't bother doing extra work!
583245431Sdim  SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
584245431Sdim                                         E = CSI.Returns.end();
585245431Sdim  if (I+1 == E)
586245431Sdim    return;
587245431Sdim
588245431Sdim  // General case: many return statements.
589245431Sdim  // Check that they all have compatible return types.
590245431Sdim
591245431Sdim  // We require the return types to strictly match here.
592252723Sdim  // Note that we've already done the required promotions as part of
593252723Sdim  // processing the return statement.
594245431Sdim  for (; I != E; ++I) {
595245431Sdim    const ReturnStmt *RS = *I;
596245431Sdim    const Expr *RetE = RS->getRetValue();
597245431Sdim
598252723Sdim    QualType ReturnType = (RetE ? RetE->getType() : Context.VoidTy);
599252723Sdim    if (Context.hasSameType(ReturnType, CSI.ReturnType))
600252723Sdim      continue;
601245431Sdim
602252723Sdim    // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
603252723Sdim    // TODO: It's possible that the *first* return is the divergent one.
604252723Sdim    Diag(RS->getLocStart(),
605252723Sdim         diag::err_typecheck_missing_return_type_incompatible)
606252723Sdim      << ReturnType << CSI.ReturnType
607252723Sdim      << isa<LambdaScopeInfo>(CSI);
608252723Sdim    // Continue iterating so that we keep emitting diagnostics.
609245431Sdim  }
610245431Sdim}
611245431Sdim
612263509SdimQualType Sema::performLambdaInitCaptureInitialization(SourceLocation Loc,
613263509Sdim                                                      bool ByRef,
614263509Sdim                                                      IdentifierInfo *Id,
615263509Sdim                                                      Expr *&Init) {
616263509Sdim
617263509Sdim  // We do not need to distinguish between direct-list-initialization
618263509Sdim  // and copy-list-initialization here, because we will always deduce
619263509Sdim  // std::initializer_list<T>, and direct- and copy-list-initialization
620263509Sdim  // always behave the same for such a type.
621263509Sdim  // FIXME: We should model whether an '=' was present.
622263509Sdim  const bool IsDirectInit = isa<ParenListExpr>(Init) || isa<InitListExpr>(Init);
623263509Sdim
624263509Sdim  // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to
625263509Sdim  // deduce against.
626263509Sdim  QualType DeductType = Context.getAutoDeductType();
627263509Sdim  TypeLocBuilder TLB;
628263509Sdim  TLB.pushTypeSpec(DeductType).setNameLoc(Loc);
629263509Sdim  if (ByRef) {
630263509Sdim    DeductType = BuildReferenceType(DeductType, true, Loc, Id);
631263509Sdim    assert(!DeductType.isNull() && "can't build reference to auto");
632263509Sdim    TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
633263509Sdim  }
634263509Sdim  TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
635263509Sdim
636263509Sdim  // Are we a non-list direct initialization?
637263509Sdim  ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
638263509Sdim
639263509Sdim  Expr *DeduceInit = Init;
640263509Sdim  // Initializer could be a C++ direct-initializer. Deduction only works if it
641263509Sdim  // contains exactly one expression.
642263509Sdim  if (CXXDirectInit) {
643263509Sdim    if (CXXDirectInit->getNumExprs() == 0) {
644263509Sdim      Diag(CXXDirectInit->getLocStart(), diag::err_init_capture_no_expression)
645263509Sdim          << DeclarationName(Id) << TSI->getType() << Loc;
646263509Sdim      return QualType();
647263509Sdim    } else if (CXXDirectInit->getNumExprs() > 1) {
648263509Sdim      Diag(CXXDirectInit->getExpr(1)->getLocStart(),
649263509Sdim           diag::err_init_capture_multiple_expressions)
650263509Sdim          << DeclarationName(Id) << TSI->getType() << Loc;
651263509Sdim      return QualType();
652263509Sdim    } else {
653263509Sdim      DeduceInit = CXXDirectInit->getExpr(0);
654263509Sdim    }
655263509Sdim  }
656263509Sdim
657263509Sdim  // Now deduce against the initialization expression and store the deduced
658263509Sdim  // type below.
659263509Sdim  QualType DeducedType;
660263509Sdim  if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
661263509Sdim    if (isa<InitListExpr>(Init))
662263509Sdim      Diag(Loc, diag::err_init_capture_deduction_failure_from_init_list)
663263509Sdim          << DeclarationName(Id)
664263509Sdim          << (DeduceInit->getType().isNull() ? TSI->getType()
665263509Sdim                                             : DeduceInit->getType())
666263509Sdim          << DeduceInit->getSourceRange();
667263509Sdim    else
668263509Sdim      Diag(Loc, diag::err_init_capture_deduction_failure)
669263509Sdim          << DeclarationName(Id) << TSI->getType()
670263509Sdim          << (DeduceInit->getType().isNull() ? TSI->getType()
671263509Sdim                                             : DeduceInit->getType())
672263509Sdim          << DeduceInit->getSourceRange();
673263509Sdim  }
674263509Sdim  if (DeducedType.isNull())
675263509Sdim    return QualType();
676263509Sdim
677263509Sdim  // Perform initialization analysis and ensure any implicit conversions
678263509Sdim  // (such as lvalue-to-rvalue) are enforced.
679263509Sdim  InitializedEntity Entity =
680263509Sdim      InitializedEntity::InitializeLambdaCapture(Id, DeducedType, Loc);
681263509Sdim  InitializationKind Kind =
682263509Sdim      IsDirectInit
683263509Sdim          ? (CXXDirectInit ? InitializationKind::CreateDirect(
684263509Sdim                                 Loc, Init->getLocStart(), Init->getLocEnd())
685263509Sdim                           : InitializationKind::CreateDirectList(Loc))
686263509Sdim          : InitializationKind::CreateCopy(Loc, Init->getLocStart());
687263509Sdim
688263509Sdim  MultiExprArg Args = Init;
689263509Sdim  if (CXXDirectInit)
690263509Sdim    Args =
691263509Sdim        MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
692263509Sdim  QualType DclT;
693263509Sdim  InitializationSequence InitSeq(*this, Entity, Kind, Args);
694263509Sdim  ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
695263509Sdim
696263509Sdim  if (Result.isInvalid())
697263509Sdim    return QualType();
698263509Sdim  Init = Result.takeAs<Expr>();
699263509Sdim
700263509Sdim  // The init-capture initialization is a full-expression that must be
701263509Sdim  // processed as one before we enter the declcontext of the lambda's
702263509Sdim  // call-operator.
703263509Sdim  Result = ActOnFinishFullExpr(Init, Loc, /*DiscardedValue*/ false,
704263509Sdim                               /*IsConstexpr*/ false,
705263509Sdim                               /*IsLambdaInitCaptureInitalizer*/ true);
706263509Sdim  if (Result.isInvalid())
707263509Sdim    return QualType();
708263509Sdim
709263509Sdim  Init = Result.takeAs<Expr>();
710263509Sdim  return DeducedType;
711263509Sdim}
712263509Sdim
713263509SdimVarDecl *Sema::createLambdaInitCaptureVarDecl(SourceLocation Loc,
714263509Sdim    QualType InitCaptureType, IdentifierInfo *Id, Expr *Init) {
715263509Sdim
716263509Sdim  TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType,
717263509Sdim      Loc);
718263509Sdim  // Create a dummy variable representing the init-capture. This is not actually
719263509Sdim  // used as a variable, and only exists as a way to name and refer to the
720263509Sdim  // init-capture.
721263509Sdim  // FIXME: Pass in separate source locations for '&' and identifier.
722263509Sdim  VarDecl *NewVD = VarDecl::Create(Context, CurContext, Loc,
723263509Sdim                                   Loc, Id, InitCaptureType, TSI, SC_Auto);
724263509Sdim  NewVD->setInitCapture(true);
725263509Sdim  NewVD->setReferenced(true);
726263509Sdim  NewVD->markUsed(Context);
727263509Sdim  NewVD->setInit(Init);
728263509Sdim  return NewVD;
729263509Sdim
730263509Sdim}
731263509Sdim
732263509SdimFieldDecl *Sema::buildInitCaptureField(LambdaScopeInfo *LSI, VarDecl *Var) {
733263509Sdim  FieldDecl *Field = FieldDecl::Create(
734263509Sdim      Context, LSI->Lambda, Var->getLocation(), Var->getLocation(),
735263509Sdim      0, Var->getType(), Var->getTypeSourceInfo(), 0, false, ICIS_NoInit);
736263509Sdim  Field->setImplicit(true);
737263509Sdim  Field->setAccess(AS_private);
738263509Sdim  LSI->Lambda->addDecl(Field);
739263509Sdim
740263509Sdim  LSI->addCapture(Var, /*isBlock*/false, Var->getType()->isReferenceType(),
741263509Sdim                  /*isNested*/false, Var->getLocation(), SourceLocation(),
742263509Sdim                  Var->getType(), Var->getInit());
743263509Sdim  return Field;
744263509Sdim}
745263509Sdim
746234287Sdimvoid Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
747263509Sdim                  Declarator &ParamInfo, Scope *CurScope) {
748234287Sdim  // Determine if we're within a context where we know that the lambda will
749234287Sdim  // be dependent, because there are template parameters in scope.
750234287Sdim  bool KnownDependent = false;
751263509Sdim  LambdaScopeInfo *const LSI = getCurLambda();
752263509Sdim  assert(LSI && "LambdaScopeInfo should be on stack!");
753263509Sdim  TemplateParameterList *TemplateParams =
754263509Sdim            getGenericLambdaTemplateParameterList(LSI, *this);
755263509Sdim
756263509Sdim  if (Scope *TmplScope = CurScope->getTemplateParamParent()) {
757263509Sdim    // Since we have our own TemplateParams, so check if an outer scope
758263509Sdim    // has template params, only then are we in a dependent scope.
759263509Sdim    if (TemplateParams)  {
760263509Sdim      TmplScope = TmplScope->getParent();
761263509Sdim      TmplScope = TmplScope ? TmplScope->getTemplateParamParent() : 0;
762263509Sdim    }
763263509Sdim    if (TmplScope && !TmplScope->decl_empty())
764234287Sdim      KnownDependent = true;
765263509Sdim  }
766234287Sdim  // Determine the signature of the call operator.
767234287Sdim  TypeSourceInfo *MethodTyInfo;
768234287Sdim  bool ExplicitParams = true;
769234287Sdim  bool ExplicitResultType = true;
770245431Sdim  bool ContainsUnexpandedParameterPack = false;
771234287Sdim  SourceLocation EndLoc;
772252723Sdim  SmallVector<ParmVarDecl *, 8> Params;
773234287Sdim  if (ParamInfo.getNumTypeObjects() == 0) {
774234287Sdim    // C++11 [expr.prim.lambda]p4:
775234287Sdim    //   If a lambda-expression does not include a lambda-declarator, it is as
776234287Sdim    //   if the lambda-declarator were ().
777263509Sdim    FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
778263509Sdim        /*IsVariadic=*/false, /*IsCXXMethod=*/true));
779234287Sdim    EPI.HasTrailingReturn = true;
780234287Sdim    EPI.TypeQuals |= DeclSpec::TQ_const;
781263509Sdim    // C++1y [expr.prim.lambda]:
782263509Sdim    //   The lambda return type is 'auto', which is replaced by the
783263509Sdim    //   trailing-return type if provided and/or deduced from 'return'
784263509Sdim    //   statements
785263509Sdim    // We don't do this before C++1y, because we don't support deduced return
786263509Sdim    // types there.
787263509Sdim    QualType DefaultTypeForNoTrailingReturn =
788263509Sdim        getLangOpts().CPlusPlus1y ? Context.getAutoDeductType()
789263509Sdim                                  : Context.DependentTy;
790263509Sdim    QualType MethodTy =
791263509Sdim        Context.getFunctionType(DefaultTypeForNoTrailingReturn, None, EPI);
792234287Sdim    MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
793234287Sdim    ExplicitParams = false;
794234287Sdim    ExplicitResultType = false;
795234287Sdim    EndLoc = Intro.Range.getEnd();
796234287Sdim  } else {
797234287Sdim    assert(ParamInfo.isFunctionDeclarator() &&
798234287Sdim           "lambda-declarator is a function");
799234287Sdim    DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
800263509Sdim
801234287Sdim    // C++11 [expr.prim.lambda]p5:
802234287Sdim    //   This function call operator is declared const (9.3.1) if and only if
803234287Sdim    //   the lambda-expression's parameter-declaration-clause is not followed
804234287Sdim    //   by mutable. It is neither virtual nor declared volatile. [...]
805234287Sdim    if (!FTI.hasMutableQualifier())
806234287Sdim      FTI.TypeQuals |= DeclSpec::TQ_const;
807263509Sdim
808234287Sdim    MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
809234287Sdim    assert(MethodTyInfo && "no type from lambda-declarator");
810234287Sdim    EndLoc = ParamInfo.getSourceRange().getEnd();
811245431Sdim
812263509Sdim    ExplicitResultType = FTI.hasTrailingReturnType();
813263509Sdim
814245431Sdim    if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
815245431Sdim        cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
816245431Sdim      // Empty arg list, don't push any params.
817245431Sdim      checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
818245431Sdim    } else {
819245431Sdim      Params.reserve(FTI.NumArgs);
820245431Sdim      for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
821245431Sdim        Params.push_back(cast<ParmVarDecl>(FTI.ArgInfo[i].Param));
822245431Sdim    }
823245431Sdim
824245431Sdim    // Check for unexpanded parameter packs in the method type.
825245431Sdim    if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
826245431Sdim      ContainsUnexpandedParameterPack = true;
827234287Sdim  }
828245431Sdim
829245431Sdim  CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
830263509Sdim                                                 KnownDependent, Intro.Default);
831245431Sdim
832245431Sdim  CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
833234287Sdim                                                MethodTyInfo, EndLoc, Params);
834234287Sdim  if (ExplicitParams)
835234287Sdim    CheckCXXDefaultArguments(Method);
836234287Sdim
837234287Sdim  // Attributes on the lambda apply to the method.
838234287Sdim  ProcessDeclAttributes(CurScope, Method, ParamInfo);
839234287Sdim
840234287Sdim  // Introduce the function call operator as the current declaration context.
841234287Sdim  PushDeclContext(CurScope, Method);
842234287Sdim
843263509Sdim  // Build the lambda scope.
844263509Sdim  buildLambdaScope(LSI, Method,
845263509Sdim                       Intro.Range,
846263509Sdim                       Intro.Default, Intro.DefaultLoc,
847263509Sdim                       ExplicitParams,
848234287Sdim                       ExplicitResultType,
849245431Sdim                       !Method->isConst());
850263509Sdim
851263509Sdim  // Distinct capture names, for diagnostics.
852263509Sdim  llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
853263509Sdim
854234287Sdim  // Handle explicit captures.
855234287Sdim  SourceLocation PrevCaptureLoc
856234287Sdim    = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
857263509Sdim  for (SmallVectorImpl<LambdaCapture>::const_iterator
858263509Sdim         C = Intro.Captures.begin(),
859263509Sdim         E = Intro.Captures.end();
860263509Sdim       C != E;
861234287Sdim       PrevCaptureLoc = C->Loc, ++C) {
862234287Sdim    if (C->Kind == LCK_This) {
863234287Sdim      // C++11 [expr.prim.lambda]p8:
864234287Sdim      //   An identifier or this shall not appear more than once in a
865234287Sdim      //   lambda-capture.
866234287Sdim      if (LSI->isCXXThisCaptured()) {
867234287Sdim        Diag(C->Loc, diag::err_capture_more_than_once)
868234287Sdim          << "'this'"
869234287Sdim          << SourceRange(LSI->getCXXThisCapture().getLocation())
870234287Sdim          << FixItHint::CreateRemoval(
871234287Sdim               SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
872234287Sdim        continue;
873234287Sdim      }
874234287Sdim
875234287Sdim      // C++11 [expr.prim.lambda]p8:
876234287Sdim      //   If a lambda-capture includes a capture-default that is =, the
877234287Sdim      //   lambda-capture shall not contain this [...].
878234287Sdim      if (Intro.Default == LCD_ByCopy) {
879234287Sdim        Diag(C->Loc, diag::err_this_capture_with_copy_default)
880234287Sdim          << FixItHint::CreateRemoval(
881234287Sdim               SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
882234287Sdim        continue;
883234287Sdim      }
884234287Sdim
885234287Sdim      // C++11 [expr.prim.lambda]p12:
886234287Sdim      //   If this is captured by a local lambda expression, its nearest
887234287Sdim      //   enclosing function shall be a non-static member function.
888234287Sdim      QualType ThisCaptureType = getCurrentThisType();
889234287Sdim      if (ThisCaptureType.isNull()) {
890234287Sdim        Diag(C->Loc, diag::err_this_capture) << true;
891234287Sdim        continue;
892234287Sdim      }
893234287Sdim
894234287Sdim      CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
895234287Sdim      continue;
896234287Sdim    }
897234287Sdim
898234287Sdim    assert(C->Id && "missing identifier for capture");
899234287Sdim
900263509Sdim    if (C->Init.isInvalid())
901234287Sdim      continue;
902263509Sdim
903263509Sdim    VarDecl *Var = 0;
904263509Sdim    if (C->Init.isUsable()) {
905263509Sdim      Diag(C->Loc, getLangOpts().CPlusPlus1y
906263509Sdim                       ? diag::warn_cxx11_compat_init_capture
907263509Sdim                       : diag::ext_init_capture);
908263509Sdim
909263509Sdim      if (C->Init.get()->containsUnexpandedParameterPack())
910263509Sdim        ContainsUnexpandedParameterPack = true;
911263509Sdim      // If the initializer expression is usable, but the InitCaptureType
912263509Sdim      // is not, then an error has occurred - so ignore the capture for now.
913263509Sdim      // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
914263509Sdim      // FIXME: we should create the init capture variable and mark it invalid
915263509Sdim      // in this case.
916263509Sdim      if (C->InitCaptureType.get().isNull())
917263509Sdim        continue;
918263509Sdim      Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
919263509Sdim            C->Id, C->Init.take());
920263509Sdim      // C++1y [expr.prim.lambda]p11:
921263509Sdim      //   An init-capture behaves as if it declares and explicitly
922263509Sdim      //   captures a variable [...] whose declarative region is the
923263509Sdim      //   lambda-expression's compound-statement
924263509Sdim      if (Var)
925263509Sdim        PushOnScopeChains(Var, CurScope, false);
926263509Sdim    } else {
927263509Sdim      // C++11 [expr.prim.lambda]p8:
928263509Sdim      //   If a lambda-capture includes a capture-default that is &, the
929263509Sdim      //   identifiers in the lambda-capture shall not be preceded by &.
930263509Sdim      //   If a lambda-capture includes a capture-default that is =, [...]
931263509Sdim      //   each identifier it contains shall be preceded by &.
932263509Sdim      if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
933263509Sdim        Diag(C->Loc, diag::err_reference_capture_with_reference_default)
934263509Sdim          << FixItHint::CreateRemoval(
935263509Sdim               SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
936263509Sdim        continue;
937263509Sdim      } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
938263509Sdim        Diag(C->Loc, diag::err_copy_capture_with_copy_default)
939263509Sdim          << FixItHint::CreateRemoval(
940263509Sdim               SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
941263509Sdim        continue;
942263509Sdim      }
943263509Sdim
944263509Sdim      // C++11 [expr.prim.lambda]p10:
945263509Sdim      //   The identifiers in a capture-list are looked up using the usual
946263509Sdim      //   rules for unqualified name lookup (3.4.1)
947263509Sdim      DeclarationNameInfo Name(C->Id, C->Loc);
948263509Sdim      LookupResult R(*this, Name, LookupOrdinaryName);
949263509Sdim      LookupName(R, CurScope);
950263509Sdim      if (R.isAmbiguous())
951263509Sdim        continue;
952263509Sdim      if (R.empty()) {
953263509Sdim        // FIXME: Disable corrections that would add qualification?
954263509Sdim        CXXScopeSpec ScopeSpec;
955263509Sdim        DeclFilterCCC<VarDecl> Validator;
956263509Sdim        if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
957263509Sdim          continue;
958263509Sdim      }
959263509Sdim
960263509Sdim      Var = R.getAsSingle<VarDecl>();
961234287Sdim    }
962234287Sdim
963263509Sdim    // C++11 [expr.prim.lambda]p8:
964263509Sdim    //   An identifier or this shall not appear more than once in a
965263509Sdim    //   lambda-capture.
966263509Sdim    if (!CaptureNames.insert(C->Id)) {
967263509Sdim      if (Var && LSI->isCaptured(Var)) {
968263509Sdim        Diag(C->Loc, diag::err_capture_more_than_once)
969263509Sdim          << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
970263509Sdim          << FixItHint::CreateRemoval(
971263509Sdim               SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
972263509Sdim      } else
973263509Sdim        // Previous capture captured something different (one or both was
974263509Sdim        // an init-cpature): no fixit.
975263509Sdim        Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
976234287Sdim      continue;
977234287Sdim    }
978234287Sdim
979234287Sdim    // C++11 [expr.prim.lambda]p10:
980263509Sdim    //   [...] each such lookup shall find a variable with automatic storage
981263509Sdim    //   duration declared in the reaching scope of the local lambda expression.
982234287Sdim    // Note that the 'reaching scope' check happens in tryCaptureVariable().
983234287Sdim    if (!Var) {
984234287Sdim      Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
985234287Sdim      continue;
986234287Sdim    }
987234287Sdim
988245431Sdim    // Ignore invalid decls; they'll just confuse the code later.
989245431Sdim    if (Var->isInvalidDecl())
990245431Sdim      continue;
991245431Sdim
992234287Sdim    if (!Var->hasLocalStorage()) {
993234287Sdim      Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
994234287Sdim      Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
995234287Sdim      continue;
996234287Sdim    }
997234287Sdim
998234287Sdim    // C++11 [expr.prim.lambda]p23:
999234287Sdim    //   A capture followed by an ellipsis is a pack expansion (14.5.3).
1000234287Sdim    SourceLocation EllipsisLoc;
1001234287Sdim    if (C->EllipsisLoc.isValid()) {
1002234287Sdim      if (Var->isParameterPack()) {
1003234287Sdim        EllipsisLoc = C->EllipsisLoc;
1004234287Sdim      } else {
1005234287Sdim        Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1006234287Sdim          << SourceRange(C->Loc);
1007234287Sdim
1008234287Sdim        // Just ignore the ellipsis.
1009234287Sdim      }
1010234287Sdim    } else if (Var->isParameterPack()) {
1011245431Sdim      ContainsUnexpandedParameterPack = true;
1012234287Sdim    }
1013263509Sdim
1014263509Sdim    if (C->Init.isUsable()) {
1015263509Sdim      buildInitCaptureField(LSI, Var);
1016263509Sdim    } else {
1017263509Sdim      TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
1018263509Sdim                                                   TryCapture_ExplicitByVal;
1019263509Sdim      tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
1020263509Sdim    }
1021234287Sdim  }
1022234287Sdim  finishLambdaExplicitCaptures(LSI);
1023234287Sdim
1024245431Sdim  LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1025245431Sdim
1026234287Sdim  // Add lambda parameters into scope.
1027234287Sdim  addLambdaParameters(Method, CurScope);
1028234287Sdim
1029234287Sdim  // Enter a new evaluation context to insulate the lambda from any
1030234287Sdim  // cleanups from the enclosing full-expression.
1031234287Sdim  PushExpressionEvaluationContext(PotentiallyEvaluated);
1032234287Sdim}
1033234287Sdim
1034234287Sdimvoid Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
1035234287Sdim                            bool IsInstantiation) {
1036234287Sdim  // Leave the expression-evaluation context.
1037234287Sdim  DiscardCleanupsInEvaluationContext();
1038234287Sdim  PopExpressionEvaluationContext();
1039234287Sdim
1040234287Sdim  // Leave the context of the lambda.
1041234287Sdim  if (!IsInstantiation)
1042234287Sdim    PopDeclContext();
1043234287Sdim
1044234287Sdim  // Finalize the lambda.
1045234287Sdim  LambdaScopeInfo *LSI = getCurLambda();
1046234287Sdim  CXXRecordDecl *Class = LSI->Lambda;
1047234287Sdim  Class->setInvalidDecl();
1048245431Sdim  SmallVector<Decl*, 4> Fields;
1049245431Sdim  for (RecordDecl::field_iterator i = Class->field_begin(),
1050245431Sdim                                  e = Class->field_end(); i != e; ++i)
1051245431Sdim    Fields.push_back(*i);
1052234287Sdim  ActOnFields(0, Class->getLocation(), Class, Fields,
1053234287Sdim              SourceLocation(), SourceLocation(), 0);
1054234287Sdim  CheckCompletedCXXClass(Class);
1055234287Sdim
1056234287Sdim  PopFunctionScopeInfo();
1057234287Sdim}
1058234287Sdim
1059234287Sdim/// \brief Add a lambda's conversion to function pointer, as described in
1060234287Sdim/// C++11 [expr.prim.lambda]p6.
1061234287Sdimstatic void addFunctionPointerConversion(Sema &S,
1062234287Sdim                                         SourceRange IntroducerRange,
1063234287Sdim                                         CXXRecordDecl *Class,
1064234287Sdim                                         CXXMethodDecl *CallOperator) {
1065234287Sdim  // Add the conversion to function pointer.
1066263509Sdim  const FunctionProtoType *CallOpProto =
1067263509Sdim      CallOperator->getType()->getAs<FunctionProtoType>();
1068263509Sdim  const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
1069263509Sdim      CallOpProto->getExtProtoInfo();
1070263509Sdim  QualType PtrToFunctionTy;
1071263509Sdim  QualType InvokerFunctionTy;
1072234287Sdim  {
1073263509Sdim    FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
1074263509Sdim    CallingConv CC = S.Context.getDefaultCallingConvention(
1075263509Sdim        CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
1076263509Sdim    InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
1077263509Sdim    InvokerExtInfo.TypeQuals = 0;
1078263509Sdim    assert(InvokerExtInfo.RefQualifier == RQ_None &&
1079263509Sdim        "Lambda's call operator should not have a reference qualifier");
1080263509Sdim    InvokerFunctionTy = S.Context.getFunctionType(CallOpProto->getResultType(),
1081263509Sdim        CallOpProto->getArgTypes(), InvokerExtInfo);
1082263509Sdim    PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
1083234287Sdim  }
1084263509Sdim
1085263509Sdim  // Create the type of the conversion function.
1086263509Sdim  FunctionProtoType::ExtProtoInfo ConvExtInfo(
1087263509Sdim      S.Context.getDefaultCallingConvention(
1088263509Sdim      /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1089263509Sdim  // The conversion function is always const.
1090263509Sdim  ConvExtInfo.TypeQuals = Qualifiers::Const;
1091263509Sdim  QualType ConvTy =
1092263509Sdim      S.Context.getFunctionType(PtrToFunctionTy, None, ConvExtInfo);
1093263509Sdim
1094263509Sdim  SourceLocation Loc = IntroducerRange.getBegin();
1095263509Sdim  DeclarationName ConversionName
1096263509Sdim    = S.Context.DeclarationNames.getCXXConversionFunctionName(
1097263509Sdim        S.Context.getCanonicalType(PtrToFunctionTy));
1098263509Sdim  DeclarationNameLoc ConvNameLoc;
1099263509Sdim  // Construct a TypeSourceInfo for the conversion function, and wire
1100263509Sdim  // all the parameters appropriately for the FunctionProtoTypeLoc
1101263509Sdim  // so that everything works during transformation/instantiation of
1102263509Sdim  // generic lambdas.
1103263509Sdim  // The main reason for wiring up the parameters of the conversion
1104263509Sdim  // function with that of the call operator is so that constructs
1105263509Sdim  // like the following work:
1106263509Sdim  // auto L = [](auto b) {                <-- 1
1107263509Sdim  //   return [](auto a) -> decltype(a) { <-- 2
1108263509Sdim  //      return a;
1109263509Sdim  //   };
1110263509Sdim  // };
1111263509Sdim  // int (*fp)(int) = L(5);
1112263509Sdim  // Because the trailing return type can contain DeclRefExprs that refer
1113263509Sdim  // to the original call operator's variables, we hijack the call
1114263509Sdim  // operators ParmVarDecls below.
1115263509Sdim  TypeSourceInfo *ConvNamePtrToFunctionTSI =
1116263509Sdim      S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
1117263509Sdim  ConvNameLoc.NamedType.TInfo = ConvNamePtrToFunctionTSI;
1118263509Sdim
1119263509Sdim  // The conversion function is a conversion to a pointer-to-function.
1120263509Sdim  TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
1121263509Sdim  FunctionProtoTypeLoc ConvTL =
1122263509Sdim      ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
1123263509Sdim  // Get the result of the conversion function which is a pointer-to-function.
1124263509Sdim  PointerTypeLoc PtrToFunctionTL =
1125263509Sdim      ConvTL.getResultLoc().getAs<PointerTypeLoc>();
1126263509Sdim  // Do the same for the TypeSourceInfo that is used to name the conversion
1127263509Sdim  // operator.
1128263509Sdim  PointerTypeLoc ConvNamePtrToFunctionTL =
1129263509Sdim      ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
1130234287Sdim
1131263509Sdim  // Get the underlying function types that the conversion function will
1132263509Sdim  // be converting to (should match the type of the call operator).
1133263509Sdim  FunctionProtoTypeLoc CallOpConvTL =
1134263509Sdim      PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1135263509Sdim  FunctionProtoTypeLoc CallOpConvNameTL =
1136263509Sdim    ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1137234287Sdim
1138263509Sdim  // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
1139263509Sdim  // These parameter's are essentially used to transform the name and
1140263509Sdim  // the type of the conversion operator.  By using the same parameters
1141263509Sdim  // as the call operator's we don't have to fix any back references that
1142263509Sdim  // the trailing return type of the call operator's uses (such as
1143263509Sdim  // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
1144263509Sdim  // - we can simply use the return type of the call operator, and
1145263509Sdim  // everything should work.
1146263509Sdim  SmallVector<ParmVarDecl *, 4> InvokerParams;
1147263509Sdim  for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1148263509Sdim    ParmVarDecl *From = CallOperator->getParamDecl(I);
1149263509Sdim
1150263509Sdim    InvokerParams.push_back(ParmVarDecl::Create(S.Context,
1151263509Sdim           // Temporarily add to the TU. This is set to the invoker below.
1152263509Sdim                                             S.Context.getTranslationUnitDecl(),
1153263509Sdim                                             From->getLocStart(),
1154263509Sdim                                             From->getLocation(),
1155263509Sdim                                             From->getIdentifier(),
1156263509Sdim                                             From->getType(),
1157263509Sdim                                             From->getTypeSourceInfo(),
1158263509Sdim                                             From->getStorageClass(),
1159263509Sdim                                             /*DefaultArg=*/0));
1160263509Sdim    CallOpConvTL.setArg(I, From);
1161263509Sdim    CallOpConvNameTL.setArg(I, From);
1162263509Sdim  }
1163263509Sdim
1164234287Sdim  CXXConversionDecl *Conversion
1165234287Sdim    = CXXConversionDecl::Create(S.Context, Class, Loc,
1166263509Sdim                                DeclarationNameInfo(ConversionName,
1167263509Sdim                                  Loc, ConvNameLoc),
1168234287Sdim                                ConvTy,
1169263509Sdim                                ConvTSI,
1170263509Sdim                                /*isInline=*/true, /*isExplicit=*/false,
1171234287Sdim                                /*isConstexpr=*/false,
1172234287Sdim                                CallOperator->getBody()->getLocEnd());
1173234287Sdim  Conversion->setAccess(AS_public);
1174234287Sdim  Conversion->setImplicit(true);
1175263509Sdim
1176263509Sdim  if (Class->isGenericLambda()) {
1177263509Sdim    // Create a template version of the conversion operator, using the template
1178263509Sdim    // parameter list of the function call operator.
1179263509Sdim    FunctionTemplateDecl *TemplateCallOperator =
1180263509Sdim            CallOperator->getDescribedFunctionTemplate();
1181263509Sdim    FunctionTemplateDecl *ConversionTemplate =
1182263509Sdim                  FunctionTemplateDecl::Create(S.Context, Class,
1183263509Sdim                                      Loc, ConversionName,
1184263509Sdim                                      TemplateCallOperator->getTemplateParameters(),
1185263509Sdim                                      Conversion);
1186263509Sdim    ConversionTemplate->setAccess(AS_public);
1187263509Sdim    ConversionTemplate->setImplicit(true);
1188263509Sdim    Conversion->setDescribedFunctionTemplate(ConversionTemplate);
1189263509Sdim    Class->addDecl(ConversionTemplate);
1190263509Sdim  } else
1191263509Sdim    Class->addDecl(Conversion);
1192263509Sdim  // Add a non-static member function that will be the result of
1193263509Sdim  // the conversion with a certain unique ID.
1194263509Sdim  DeclarationName InvokerName = &S.Context.Idents.get(
1195263509Sdim                                                 getLambdaStaticInvokerName());
1196263509Sdim  // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
1197263509Sdim  // we should get a prebuilt TrivialTypeSourceInfo from Context
1198263509Sdim  // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
1199263509Sdim  // then rewire the parameters accordingly, by hoisting up the InvokeParams
1200263509Sdim  // loop below and then use its Params to set Invoke->setParams(...) below.
1201263509Sdim  // This would avoid the 'const' qualifier of the calloperator from
1202263509Sdim  // contaminating the type of the invoker, which is currently adjusted
1203263509Sdim  // in SemaTemplateDeduction.cpp:DeduceTemplateArguments.  Fixing the
1204263509Sdim  // trailing return type of the invoker would require a visitor to rebuild
1205263509Sdim  // the trailing return type and adjusting all back DeclRefExpr's to refer
1206263509Sdim  // to the new static invoker parameters - not the call operator's.
1207234287Sdim  CXXMethodDecl *Invoke
1208234287Sdim    = CXXMethodDecl::Create(S.Context, Class, Loc,
1209263509Sdim                            DeclarationNameInfo(InvokerName, Loc),
1210263509Sdim                            InvokerFunctionTy,
1211263509Sdim                            CallOperator->getTypeSourceInfo(),
1212252723Sdim                            SC_Static, /*IsInline=*/true,
1213234287Sdim                            /*IsConstexpr=*/false,
1214234287Sdim                            CallOperator->getBody()->getLocEnd());
1215263509Sdim  for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
1216263509Sdim    InvokerParams[I]->setOwningFunction(Invoke);
1217263509Sdim  Invoke->setParams(InvokerParams);
1218234287Sdim  Invoke->setAccess(AS_private);
1219234287Sdim  Invoke->setImplicit(true);
1220263509Sdim  if (Class->isGenericLambda()) {
1221263509Sdim    FunctionTemplateDecl *TemplateCallOperator =
1222263509Sdim            CallOperator->getDescribedFunctionTemplate();
1223263509Sdim    FunctionTemplateDecl *StaticInvokerTemplate = FunctionTemplateDecl::Create(
1224263509Sdim                          S.Context, Class, Loc, InvokerName,
1225263509Sdim                          TemplateCallOperator->getTemplateParameters(),
1226263509Sdim                          Invoke);
1227263509Sdim    StaticInvokerTemplate->setAccess(AS_private);
1228263509Sdim    StaticInvokerTemplate->setImplicit(true);
1229263509Sdim    Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
1230263509Sdim    Class->addDecl(StaticInvokerTemplate);
1231263509Sdim  } else
1232263509Sdim    Class->addDecl(Invoke);
1233234287Sdim}
1234234287Sdim
1235234287Sdim/// \brief Add a lambda's conversion to block pointer.
1236234287Sdimstatic void addBlockPointerConversion(Sema &S,
1237234287Sdim                                      SourceRange IntroducerRange,
1238234287Sdim                                      CXXRecordDecl *Class,
1239234287Sdim                                      CXXMethodDecl *CallOperator) {
1240234287Sdim  const FunctionProtoType *Proto
1241234287Sdim    = CallOperator->getType()->getAs<FunctionProtoType>();
1242234287Sdim  QualType BlockPtrTy;
1243234287Sdim  {
1244234287Sdim    FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
1245234287Sdim    ExtInfo.TypeQuals = 0;
1246263509Sdim    QualType FunctionTy = S.Context.getFunctionType(
1247263509Sdim        Proto->getResultType(), Proto->getArgTypes(), ExtInfo);
1248234287Sdim    BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
1249234287Sdim  }
1250263509Sdim
1251263509Sdim  FunctionProtoType::ExtProtoInfo ExtInfo(S.Context.getDefaultCallingConvention(
1252263509Sdim      /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1253234287Sdim  ExtInfo.TypeQuals = Qualifiers::Const;
1254252723Sdim  QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ExtInfo);
1255234287Sdim
1256234287Sdim  SourceLocation Loc = IntroducerRange.getBegin();
1257234287Sdim  DeclarationName Name
1258234287Sdim    = S.Context.DeclarationNames.getCXXConversionFunctionName(
1259234287Sdim        S.Context.getCanonicalType(BlockPtrTy));
1260234287Sdim  DeclarationNameLoc NameLoc;
1261234287Sdim  NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
1262234287Sdim  CXXConversionDecl *Conversion
1263234287Sdim    = CXXConversionDecl::Create(S.Context, Class, Loc,
1264234287Sdim                                DeclarationNameInfo(Name, Loc, NameLoc),
1265234287Sdim                                ConvTy,
1266234287Sdim                                S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
1267263509Sdim                                /*isInline=*/true, /*isExplicit=*/false,
1268234287Sdim                                /*isConstexpr=*/false,
1269234287Sdim                                CallOperator->getBody()->getLocEnd());
1270234287Sdim  Conversion->setAccess(AS_public);
1271234287Sdim  Conversion->setImplicit(true);
1272234287Sdim  Class->addDecl(Conversion);
1273234287Sdim}
1274234287Sdim
1275234287SdimExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
1276234287Sdim                                 Scope *CurScope,
1277234287Sdim                                 bool IsInstantiation) {
1278234287Sdim  // Collect information from the lambda scope.
1279252723Sdim  SmallVector<LambdaExpr::Capture, 4> Captures;
1280252723Sdim  SmallVector<Expr *, 4> CaptureInits;
1281234287Sdim  LambdaCaptureDefault CaptureDefault;
1282263509Sdim  SourceLocation CaptureDefaultLoc;
1283234287Sdim  CXXRecordDecl *Class;
1284234287Sdim  CXXMethodDecl *CallOperator;
1285234287Sdim  SourceRange IntroducerRange;
1286234287Sdim  bool ExplicitParams;
1287234287Sdim  bool ExplicitResultType;
1288234287Sdim  bool LambdaExprNeedsCleanups;
1289245431Sdim  bool ContainsUnexpandedParameterPack;
1290252723Sdim  SmallVector<VarDecl *, 4> ArrayIndexVars;
1291252723Sdim  SmallVector<unsigned, 4> ArrayIndexStarts;
1292234287Sdim  {
1293234287Sdim    LambdaScopeInfo *LSI = getCurLambda();
1294234287Sdim    CallOperator = LSI->CallOperator;
1295234287Sdim    Class = LSI->Lambda;
1296234287Sdim    IntroducerRange = LSI->IntroducerRange;
1297234287Sdim    ExplicitParams = LSI->ExplicitParams;
1298234287Sdim    ExplicitResultType = !LSI->HasImplicitReturnType;
1299234287Sdim    LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
1300245431Sdim    ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
1301234287Sdim    ArrayIndexVars.swap(LSI->ArrayIndexVars);
1302234287Sdim    ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
1303234287Sdim
1304234287Sdim    // Translate captures.
1305234287Sdim    for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
1306234287Sdim      LambdaScopeInfo::Capture From = LSI->Captures[I];
1307234287Sdim      assert(!From.isBlockCapture() && "Cannot capture __block variables");
1308234287Sdim      bool IsImplicit = I >= LSI->NumExplicitCaptures;
1309234287Sdim
1310234287Sdim      // Handle 'this' capture.
1311234287Sdim      if (From.isThisCapture()) {
1312234287Sdim        Captures.push_back(LambdaExpr::Capture(From.getLocation(),
1313234287Sdim                                               IsImplicit,
1314234287Sdim                                               LCK_This));
1315234287Sdim        CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
1316234287Sdim                                                         getCurrentThisType(),
1317234287Sdim                                                         /*isImplicit=*/true));
1318234287Sdim        continue;
1319234287Sdim      }
1320234287Sdim
1321234287Sdim      VarDecl *Var = From.getVariable();
1322234287Sdim      LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
1323234287Sdim      Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
1324234287Sdim                                             Kind, Var, From.getEllipsisLoc()));
1325263509Sdim      CaptureInits.push_back(From.getInitExpr());
1326234287Sdim    }
1327234287Sdim
1328234287Sdim    switch (LSI->ImpCaptureStyle) {
1329234287Sdim    case CapturingScopeInfo::ImpCap_None:
1330234287Sdim      CaptureDefault = LCD_None;
1331234287Sdim      break;
1332234287Sdim
1333234287Sdim    case CapturingScopeInfo::ImpCap_LambdaByval:
1334234287Sdim      CaptureDefault = LCD_ByCopy;
1335234287Sdim      break;
1336234287Sdim
1337252723Sdim    case CapturingScopeInfo::ImpCap_CapturedRegion:
1338234287Sdim    case CapturingScopeInfo::ImpCap_LambdaByref:
1339234287Sdim      CaptureDefault = LCD_ByRef;
1340234287Sdim      break;
1341234287Sdim
1342234287Sdim    case CapturingScopeInfo::ImpCap_Block:
1343234287Sdim      llvm_unreachable("block capture in lambda");
1344234287Sdim      break;
1345234287Sdim    }
1346263509Sdim    CaptureDefaultLoc = LSI->CaptureDefaultLoc;
1347234287Sdim
1348234287Sdim    // C++11 [expr.prim.lambda]p4:
1349234287Sdim    //   If a lambda-expression does not include a
1350234287Sdim    //   trailing-return-type, it is as if the trailing-return-type
1351234287Sdim    //   denotes the following type:
1352263509Sdim    //
1353263509Sdim    // Skip for C++1y return type deduction semantics which uses
1354263509Sdim    // different machinery.
1355263509Sdim    // FIXME: Refactor and Merge the return type deduction machinery.
1356234287Sdim    // FIXME: Assumes current resolution to core issue 975.
1357263509Sdim    if (LSI->HasImplicitReturnType && !getLangOpts().CPlusPlus1y) {
1358245431Sdim      deduceClosureReturnType(*LSI);
1359245431Sdim
1360234287Sdim      //   - if there are no return statements in the
1361234287Sdim      //     compound-statement, or all return statements return
1362234287Sdim      //     either an expression of type void or no expression or
1363234287Sdim      //     braced-init-list, the type void;
1364234287Sdim      if (LSI->ReturnType.isNull()) {
1365234287Sdim        LSI->ReturnType = Context.VoidTy;
1366234287Sdim      }
1367234287Sdim
1368234287Sdim      // Create a function type with the inferred return type.
1369234287Sdim      const FunctionProtoType *Proto
1370234287Sdim        = CallOperator->getType()->getAs<FunctionProtoType>();
1371263509Sdim      QualType FunctionTy = Context.getFunctionType(
1372263509Sdim          LSI->ReturnType, Proto->getArgTypes(), Proto->getExtProtoInfo());
1373234287Sdim      CallOperator->setType(FunctionTy);
1374234287Sdim    }
1375234287Sdim    // C++ [expr.prim.lambda]p7:
1376234287Sdim    //   The lambda-expression's compound-statement yields the
1377234287Sdim    //   function-body (8.4) of the function call operator [...].
1378234287Sdim    ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
1379234287Sdim    CallOperator->setLexicalDeclContext(Class);
1380263509Sdim    Decl *TemplateOrNonTemplateCallOperatorDecl =
1381263509Sdim        CallOperator->getDescribedFunctionTemplate()
1382263509Sdim        ? CallOperator->getDescribedFunctionTemplate()
1383263509Sdim        : cast<Decl>(CallOperator);
1384263509Sdim
1385263509Sdim    TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
1386263509Sdim    Class->addDecl(TemplateOrNonTemplateCallOperatorDecl);
1387263509Sdim
1388234287Sdim    PopExpressionEvaluationContext();
1389234287Sdim
1390234287Sdim    // C++11 [expr.prim.lambda]p6:
1391234287Sdim    //   The closure type for a lambda-expression with no lambda-capture
1392234287Sdim    //   has a public non-virtual non-explicit const conversion function
1393234287Sdim    //   to pointer to function having the same parameter and return
1394234287Sdim    //   types as the closure type's function call operator.
1395234287Sdim    if (Captures.empty() && CaptureDefault == LCD_None)
1396234287Sdim      addFunctionPointerConversion(*this, IntroducerRange, Class,
1397234287Sdim                                   CallOperator);
1398234287Sdim
1399234287Sdim    // Objective-C++:
1400234287Sdim    //   The closure type for a lambda-expression has a public non-virtual
1401234287Sdim    //   non-explicit const conversion function to a block pointer having the
1402234287Sdim    //   same parameter and return types as the closure type's function call
1403234287Sdim    //   operator.
1404263509Sdim    // FIXME: Fix generic lambda to block conversions.
1405263509Sdim    if (getLangOpts().Blocks && getLangOpts().ObjC1 &&
1406263509Sdim                                              !Class->isGenericLambda())
1407234287Sdim      addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
1408234287Sdim
1409234287Sdim    // Finalize the lambda class.
1410245431Sdim    SmallVector<Decl*, 4> Fields;
1411245431Sdim    for (RecordDecl::field_iterator i = Class->field_begin(),
1412245431Sdim                                    e = Class->field_end(); i != e; ++i)
1413245431Sdim      Fields.push_back(*i);
1414234287Sdim    ActOnFields(0, Class->getLocation(), Class, Fields,
1415234287Sdim                SourceLocation(), SourceLocation(), 0);
1416234287Sdim    CheckCompletedCXXClass(Class);
1417234287Sdim  }
1418234287Sdim
1419234287Sdim  if (LambdaExprNeedsCleanups)
1420234287Sdim    ExprNeedsCleanups = true;
1421234287Sdim
1422234287Sdim  LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
1423263509Sdim                                          CaptureDefault, CaptureDefaultLoc,
1424263509Sdim                                          Captures,
1425234287Sdim                                          ExplicitParams, ExplicitResultType,
1426234287Sdim                                          CaptureInits, ArrayIndexVars,
1427245431Sdim                                          ArrayIndexStarts, Body->getLocEnd(),
1428245431Sdim                                          ContainsUnexpandedParameterPack);
1429234287Sdim
1430234287Sdim  if (!CurContext->isDependentContext()) {
1431234287Sdim    switch (ExprEvalContexts.back().Context) {
1432263509Sdim    // C++11 [expr.prim.lambda]p2:
1433263509Sdim    //   A lambda-expression shall not appear in an unevaluated operand
1434263509Sdim    //   (Clause 5).
1435234287Sdim    case Unevaluated:
1436252723Sdim    case UnevaluatedAbstract:
1437263509Sdim    // C++1y [expr.const]p2:
1438263509Sdim    //   A conditional-expression e is a core constant expression unless the
1439263509Sdim    //   evaluation of e, following the rules of the abstract machine, would
1440263509Sdim    //   evaluate [...] a lambda-expression.
1441263509Sdim    //
1442263509Sdim    // This is technically incorrect, there are some constant evaluated contexts
1443263509Sdim    // where this should be allowed.  We should probably fix this when DR1607 is
1444263509Sdim    // ratified, it lays out the exact set of conditions where we shouldn't
1445263509Sdim    // allow a lambda-expression.
1446263509Sdim    case ConstantEvaluated:
1447234287Sdim      // We don't actually diagnose this case immediately, because we
1448234287Sdim      // could be within a context where we might find out later that
1449234287Sdim      // the expression is potentially evaluated (e.g., for typeid).
1450234287Sdim      ExprEvalContexts.back().Lambdas.push_back(Lambda);
1451234287Sdim      break;
1452234287Sdim
1453234287Sdim    case PotentiallyEvaluated:
1454234287Sdim    case PotentiallyEvaluatedIfUsed:
1455234287Sdim      break;
1456234287Sdim    }
1457234287Sdim  }
1458263509Sdim
1459234287Sdim  return MaybeBindToTemporary(Lambda);
1460234287Sdim}
1461234287Sdim
1462234287SdimExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
1463234287Sdim                                               SourceLocation ConvLocation,
1464234287Sdim                                               CXXConversionDecl *Conv,
1465234287Sdim                                               Expr *Src) {
1466234287Sdim  // Make sure that the lambda call operator is marked used.
1467234287Sdim  CXXRecordDecl *Lambda = Conv->getParent();
1468234287Sdim  CXXMethodDecl *CallOperator
1469234287Sdim    = cast<CXXMethodDecl>(
1470252723Sdim        Lambda->lookup(
1471252723Sdim          Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
1472234287Sdim  CallOperator->setReferenced();
1473263509Sdim  CallOperator->markUsed(Context);
1474234287Sdim
1475234287Sdim  ExprResult Init = PerformCopyInitialization(
1476234287Sdim                      InitializedEntity::InitializeBlock(ConvLocation,
1477234287Sdim                                                         Src->getType(),
1478234287Sdim                                                         /*NRVO=*/false),
1479234287Sdim                      CurrentLocation, Src);
1480234287Sdim  if (!Init.isInvalid())
1481234287Sdim    Init = ActOnFinishFullExpr(Init.take());
1482234287Sdim
1483234287Sdim  if (Init.isInvalid())
1484234287Sdim    return ExprError();
1485234287Sdim
1486234287Sdim  // Create the new block to be returned.
1487234287Sdim  BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
1488234287Sdim
1489234287Sdim  // Set the type information.
1490234287Sdim  Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
1491234287Sdim  Block->setIsVariadic(CallOperator->isVariadic());
1492234287Sdim  Block->setBlockMissingReturnType(false);
1493234287Sdim
1494234287Sdim  // Add parameters.
1495234287Sdim  SmallVector<ParmVarDecl *, 4> BlockParams;
1496234287Sdim  for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1497234287Sdim    ParmVarDecl *From = CallOperator->getParamDecl(I);
1498234287Sdim    BlockParams.push_back(ParmVarDecl::Create(Context, Block,
1499234287Sdim                                              From->getLocStart(),
1500234287Sdim                                              From->getLocation(),
1501234287Sdim                                              From->getIdentifier(),
1502234287Sdim                                              From->getType(),
1503234287Sdim                                              From->getTypeSourceInfo(),
1504234287Sdim                                              From->getStorageClass(),
1505234287Sdim                                              /*DefaultArg=*/0));
1506234287Sdim  }
1507234287Sdim  Block->setParams(BlockParams);
1508234287Sdim
1509234287Sdim  Block->setIsConversionFromLambda(true);
1510234287Sdim
1511234287Sdim  // Add capture. The capture uses a fake variable, which doesn't correspond
1512234287Sdim  // to any actual memory location. However, the initializer copy-initializes
1513234287Sdim  // the lambda object.
1514234287Sdim  TypeSourceInfo *CapVarTSI =
1515234287Sdim      Context.getTrivialTypeSourceInfo(Src->getType());
1516234287Sdim  VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1517234287Sdim                                    ConvLocation, 0,
1518234287Sdim                                    Src->getType(), CapVarTSI,
1519252723Sdim                                    SC_None);
1520234287Sdim  BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
1521234287Sdim                             /*Nested=*/false, /*Copy=*/Init.take());
1522234287Sdim  Block->setCaptures(Context, &Capture, &Capture + 1,
1523234287Sdim                     /*CapturesCXXThis=*/false);
1524234287Sdim
1525234287Sdim  // Add a fake function body to the block. IR generation is responsible
1526234287Sdim  // for filling in the actual body, which cannot be expressed as an AST.
1527245431Sdim  Block->setBody(new (Context) CompoundStmt(ConvLocation));
1528234287Sdim
1529234287Sdim  // Create the block literal expression.
1530234287Sdim  Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1531234287Sdim  ExprCleanupObjects.push_back(Block);
1532234287Sdim  ExprNeedsCleanups = true;
1533234287Sdim
1534234287Sdim  return BuildBlock;
1535234287Sdim}
1536