]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/Sema/SemaLambda.cpp
Upgrade to OpenSSH 7.3p1.
[FreeBSD/FreeBSD.git] / contrib / llvm / tools / clang / lib / Sema / SemaLambda.cpp
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 "TypeLocBuilder.h"
15 #include "clang/AST/ASTLambda.h"
16 #include "clang/AST/ExprCXX.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/Sema/Initialization.h"
19 #include "clang/Sema/Lookup.h"
20 #include "clang/Sema/Scope.h"
21 #include "clang/Sema/ScopeInfo.h"
22 #include "clang/Sema/SemaInternal.h"
23 #include "clang/Sema/SemaLambda.h"
24 using namespace clang;
25 using namespace sema;
26
27 /// \brief Examines the FunctionScopeInfo stack to determine the nearest
28 /// enclosing lambda (to the current lambda) that is 'capture-ready' for 
29 /// the variable referenced in the current lambda (i.e. \p VarToCapture).
30 /// If successful, returns the index into Sema's FunctionScopeInfo stack
31 /// of the capture-ready lambda's LambdaScopeInfo.
32 ///  
33 /// Climbs down the stack of lambdas (deepest nested lambda - i.e. current 
34 /// lambda - is on top) to determine the index of the nearest enclosing/outer
35 /// lambda that is ready to capture the \p VarToCapture being referenced in 
36 /// the current lambda. 
37 /// As we climb down the stack, we want the index of the first such lambda -
38 /// that is the lambda with the highest index that is 'capture-ready'. 
39 /// 
40 /// A lambda 'L' is capture-ready for 'V' (var or this) if:
41 ///  - its enclosing context is non-dependent
42 ///  - and if the chain of lambdas between L and the lambda in which
43 ///    V is potentially used (i.e. the lambda at the top of the scope info 
44 ///    stack), can all capture or have already captured V.
45 /// If \p VarToCapture is 'null' then we are trying to capture 'this'.
46 /// 
47 /// Note that a lambda that is deemed 'capture-ready' still needs to be checked
48 /// for whether it is 'capture-capable' (see
49 /// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly 
50 /// capture.
51 ///
52 /// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
53 ///  LambdaScopeInfo inherits from).  The current/deepest/innermost lambda
54 ///  is at the top of the stack and has the highest index.
55 /// \param VarToCapture - the variable to capture.  If NULL, capture 'this'.
56 ///
57 /// \returns An Optional<unsigned> Index that if evaluates to 'true' contains
58 /// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda
59 /// which is capture-ready.  If the return value evaluates to 'false' then
60 /// no lambda is capture-ready for \p VarToCapture.
61
62 static inline Optional<unsigned>
63 getStackIndexOfNearestEnclosingCaptureReadyLambda(
64     ArrayRef<const clang::sema::FunctionScopeInfo *> FunctionScopes,
65     VarDecl *VarToCapture) {
66   // Label failure to capture.
67   const Optional<unsigned> NoLambdaIsCaptureReady;
68
69   // Ignore all inner captured regions.
70   unsigned CurScopeIndex = FunctionScopes.size() - 1;
71   while (CurScopeIndex > 0 && isa<clang::sema::CapturedRegionScopeInfo>(
72                                   FunctionScopes[CurScopeIndex]))
73     --CurScopeIndex;
74   assert(
75       isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) &&
76       "The function on the top of sema's function-info stack must be a lambda");
77
78   // If VarToCapture is null, we are attempting to capture 'this'.
79   const bool IsCapturingThis = !VarToCapture;
80   const bool IsCapturingVariable = !IsCapturingThis;
81
82   // Start with the current lambda at the top of the stack (highest index).
83   DeclContext *EnclosingDC =
84       cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator;
85
86   do {
87     const clang::sema::LambdaScopeInfo *LSI =
88         cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]);
89     // IF we have climbed down to an intervening enclosing lambda that contains
90     // the variable declaration - it obviously can/must not capture the
91     // variable.
92     // Since its enclosing DC is dependent, all the lambdas between it and the
93     // innermost nested lambda are dependent (otherwise we wouldn't have
94     // arrived here) - so we don't yet have a lambda that can capture the
95     // variable.
96     if (IsCapturingVariable &&
97         VarToCapture->getDeclContext()->Equals(EnclosingDC))
98       return NoLambdaIsCaptureReady;
99
100     // For an enclosing lambda to be capture ready for an entity, all
101     // intervening lambda's have to be able to capture that entity. If even
102     // one of the intervening lambda's is not capable of capturing the entity
103     // then no enclosing lambda can ever capture that entity.
104     // For e.g.
105     // const int x = 10;
106     // [=](auto a) {    #1
107     //   [](auto b) {   #2 <-- an intervening lambda that can never capture 'x'
108     //    [=](auto c) { #3
109     //       f(x, c);  <-- can not lead to x's speculative capture by #1 or #2
110     //    }; }; };
111     // If they do not have a default implicit capture, check to see
112     // if the entity has already been explicitly captured.
113     // If even a single dependent enclosing lambda lacks the capability
114     // to ever capture this variable, there is no further enclosing
115     // non-dependent lambda that can capture this variable.
116     if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) {
117       if (IsCapturingVariable && !LSI->isCaptured(VarToCapture))
118         return NoLambdaIsCaptureReady;
119       if (IsCapturingThis && !LSI->isCXXThisCaptured())
120         return NoLambdaIsCaptureReady;
121     }
122     EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC);
123     
124     assert(CurScopeIndex);
125     --CurScopeIndex;
126   } while (!EnclosingDC->isTranslationUnit() &&
127            EnclosingDC->isDependentContext() &&
128            isLambdaCallOperator(EnclosingDC));
129
130   assert(CurScopeIndex < (FunctionScopes.size() - 1));
131   // If the enclosingDC is not dependent, then the immediately nested lambda
132   // (one index above) is capture-ready.
133   if (!EnclosingDC->isDependentContext())
134     return CurScopeIndex + 1;
135   return NoLambdaIsCaptureReady;
136 }
137
138 /// \brief Examines the FunctionScopeInfo stack to determine the nearest
139 /// enclosing lambda (to the current lambda) that is 'capture-capable' for 
140 /// the variable referenced in the current lambda (i.e. \p VarToCapture).
141 /// If successful, returns the index into Sema's FunctionScopeInfo stack
142 /// of the capture-capable lambda's LambdaScopeInfo.
143 ///
144 /// Given the current stack of lambdas being processed by Sema and
145 /// the variable of interest, to identify the nearest enclosing lambda (to the 
146 /// current lambda at the top of the stack) that can truly capture
147 /// a variable, it has to have the following two properties:
148 ///  a) 'capture-ready' - be the innermost lambda that is 'capture-ready':
149 ///     - climb down the stack (i.e. starting from the innermost and examining
150 ///       each outer lambda step by step) checking if each enclosing
151 ///       lambda can either implicitly or explicitly capture the variable.
152 ///       Record the first such lambda that is enclosed in a non-dependent
153 ///       context. If no such lambda currently exists return failure.
154 ///  b) 'capture-capable' - make sure the 'capture-ready' lambda can truly
155 ///  capture the variable by checking all its enclosing lambdas:
156 ///     - check if all outer lambdas enclosing the 'capture-ready' lambda
157 ///       identified above in 'a' can also capture the variable (this is done
158 ///       via tryCaptureVariable for variables and CheckCXXThisCapture for
159 ///       'this' by passing in the index of the Lambda identified in step 'a')
160 ///
161 /// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
162 /// LambdaScopeInfo inherits from).  The current/deepest/innermost lambda
163 /// is at the top of the stack.
164 ///
165 /// \param VarToCapture - the variable to capture.  If NULL, capture 'this'.
166 ///
167 ///
168 /// \returns An Optional<unsigned> Index that if evaluates to 'true' contains
169 /// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda
170 /// which is capture-capable.  If the return value evaluates to 'false' then
171 /// no lambda is capture-capable for \p VarToCapture.
172
173 Optional<unsigned> clang::getStackIndexOfNearestEnclosingCaptureCapableLambda(
174     ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes,
175     VarDecl *VarToCapture, Sema &S) {
176
177   const Optional<unsigned> NoLambdaIsCaptureCapable;
178   
179   const Optional<unsigned> OptionalStackIndex =
180       getStackIndexOfNearestEnclosingCaptureReadyLambda(FunctionScopes,
181                                                         VarToCapture);
182   if (!OptionalStackIndex)
183     return NoLambdaIsCaptureCapable;
184
185   const unsigned IndexOfCaptureReadyLambda = OptionalStackIndex.getValue();
186   assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) ||
187           S.getCurGenericLambda()) &&
188          "The capture ready lambda for a potential capture can only be the "
189          "current lambda if it is a generic lambda");
190
191   const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI =
192       cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]);
193   
194   // If VarToCapture is null, we are attempting to capture 'this'
195   const bool IsCapturingThis = !VarToCapture;
196   const bool IsCapturingVariable = !IsCapturingThis;
197
198   if (IsCapturingVariable) {
199     // Check if the capture-ready lambda can truly capture the variable, by
200     // checking whether all enclosing lambdas of the capture-ready lambda allow
201     // the capture - i.e. make sure it is capture-capable.
202     QualType CaptureType, DeclRefType;
203     const bool CanCaptureVariable =
204         !S.tryCaptureVariable(VarToCapture,
205                               /*ExprVarIsUsedInLoc*/ SourceLocation(),
206                               clang::Sema::TryCapture_Implicit,
207                               /*EllipsisLoc*/ SourceLocation(),
208                               /*BuildAndDiagnose*/ false, CaptureType,
209                               DeclRefType, &IndexOfCaptureReadyLambda);
210     if (!CanCaptureVariable)
211       return NoLambdaIsCaptureCapable;
212   } else {
213     // Check if the capture-ready lambda can truly capture 'this' by checking
214     // whether all enclosing lambdas of the capture-ready lambda can capture
215     // 'this'.
216     const bool CanCaptureThis =
217         !S.CheckCXXThisCapture(
218              CaptureReadyLambdaLSI->PotentialThisCaptureLocation,
219              /*Explicit*/ false, /*BuildAndDiagnose*/ false,
220              &IndexOfCaptureReadyLambda);
221     if (!CanCaptureThis)
222       return NoLambdaIsCaptureCapable;
223   } 
224   return IndexOfCaptureReadyLambda;
225 }
226
227 static inline TemplateParameterList *
228 getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) {
229   if (LSI->GLTemplateParameterList)
230     return LSI->GLTemplateParameterList;
231
232   if (!LSI->AutoTemplateParams.empty()) {
233     SourceRange IntroRange = LSI->IntroducerRange;
234     SourceLocation LAngleLoc = IntroRange.getBegin();
235     SourceLocation RAngleLoc = IntroRange.getEnd();
236     LSI->GLTemplateParameterList = TemplateParameterList::Create(
237         SemaRef.Context,
238         /*Template kw loc*/ SourceLocation(), LAngleLoc,
239         llvm::makeArrayRef((NamedDecl *const *)LSI->AutoTemplateParams.data(),
240                            LSI->AutoTemplateParams.size()),
241         RAngleLoc);
242   }
243   return LSI->GLTemplateParameterList;
244 }
245
246 CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
247                                              TypeSourceInfo *Info,
248                                              bool KnownDependent, 
249                                              LambdaCaptureDefault CaptureDefault) {
250   DeclContext *DC = CurContext;
251   while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
252     DC = DC->getParent();
253   bool IsGenericLambda = getGenericLambdaTemplateParameterList(getCurLambda(),
254                                                                *this);  
255   // Start constructing the lambda class.
256   CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info,
257                                                      IntroducerRange.getBegin(),
258                                                      KnownDependent, 
259                                                      IsGenericLambda, 
260                                                      CaptureDefault);
261   DC->addDecl(Class);
262
263   return Class;
264 }
265
266 /// \brief Determine whether the given context is or is enclosed in an inline
267 /// function.
268 static bool isInInlineFunction(const DeclContext *DC) {
269   while (!DC->isFileContext()) {
270     if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
271       if (FD->isInlined())
272         return true;
273     
274     DC = DC->getLexicalParent();
275   }
276   
277   return false;
278 }
279
280 MangleNumberingContext *
281 Sema::getCurrentMangleNumberContext(const DeclContext *DC,
282                                     Decl *&ManglingContextDecl) {
283   // Compute the context for allocating mangling numbers in the current
284   // expression, if the ABI requires them.
285   ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
286
287   enum ContextKind {
288     Normal,
289     DefaultArgument,
290     DataMember,
291     StaticDataMember
292   } Kind = Normal;
293
294   // Default arguments of member function parameters that appear in a class
295   // definition, as well as the initializers of data members, receive special
296   // treatment. Identify them.
297   if (ManglingContextDecl) {
298     if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
299       if (const DeclContext *LexicalDC
300           = Param->getDeclContext()->getLexicalParent())
301         if (LexicalDC->isRecord())
302           Kind = DefaultArgument;
303     } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
304       if (Var->getDeclContext()->isRecord())
305         Kind = StaticDataMember;
306     } else if (isa<FieldDecl>(ManglingContextDecl)) {
307       Kind = DataMember;
308     }
309   }
310
311   // Itanium ABI [5.1.7]:
312   //   In the following contexts [...] the one-definition rule requires closure
313   //   types in different translation units to "correspond":
314   bool IsInNonspecializedTemplate =
315     !ActiveTemplateInstantiations.empty() || CurContext->isDependentContext();
316   switch (Kind) {
317   case Normal: {
318     //  -- the bodies of non-exported nonspecialized template functions
319     //  -- the bodies of inline functions
320     if ((IsInNonspecializedTemplate &&
321          !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
322         isInInlineFunction(CurContext)) {
323       ManglingContextDecl = nullptr;
324       while (auto *CD = dyn_cast<CapturedDecl>(DC))
325         DC = CD->getParent();
326       return &Context.getManglingNumberContext(DC);
327     }
328
329     ManglingContextDecl = nullptr;
330     return nullptr;
331   }
332
333   case StaticDataMember:
334     //  -- the initializers of nonspecialized static members of template classes
335     if (!IsInNonspecializedTemplate) {
336       ManglingContextDecl = nullptr;
337       return nullptr;
338     }
339     // Fall through to get the current context.
340
341   case DataMember:
342     //  -- the in-class initializers of class members
343   case DefaultArgument:
344     //  -- default arguments appearing in class definitions
345     return &ExprEvalContexts.back().getMangleNumberingContext(Context);
346   }
347
348   llvm_unreachable("unexpected context");
349 }
350
351 MangleNumberingContext &
352 Sema::ExpressionEvaluationContextRecord::getMangleNumberingContext(
353     ASTContext &Ctx) {
354   assert(ManglingContextDecl && "Need to have a context declaration");
355   if (!MangleNumbering)
356     MangleNumbering = Ctx.createMangleNumberingContext();
357   return *MangleNumbering;
358 }
359
360 CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
361                                            SourceRange IntroducerRange,
362                                            TypeSourceInfo *MethodTypeInfo,
363                                            SourceLocation EndLoc,
364                                            ArrayRef<ParmVarDecl *> Params) {
365   QualType MethodType = MethodTypeInfo->getType();
366   TemplateParameterList *TemplateParams = 
367             getGenericLambdaTemplateParameterList(getCurLambda(), *this);
368   // If a lambda appears in a dependent context or is a generic lambda (has
369   // template parameters) and has an 'auto' return type, deduce it to a 
370   // dependent type.
371   if (Class->isDependentContext() || TemplateParams) {
372     const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
373     QualType Result = FPT->getReturnType();
374     if (Result->isUndeducedType()) {
375       Result = SubstAutoType(Result, Context.DependentTy);
376       MethodType = Context.getFunctionType(Result, FPT->getParamTypes(),
377                                            FPT->getExtProtoInfo());
378     }
379   }
380
381   // C++11 [expr.prim.lambda]p5:
382   //   The closure type for a lambda-expression has a public inline function 
383   //   call operator (13.5.4) whose parameters and return type are described by
384   //   the lambda-expression's parameter-declaration-clause and 
385   //   trailing-return-type respectively.
386   DeclarationName MethodName
387     = Context.DeclarationNames.getCXXOperatorName(OO_Call);
388   DeclarationNameLoc MethodNameLoc;
389   MethodNameLoc.CXXOperatorName.BeginOpNameLoc
390     = IntroducerRange.getBegin().getRawEncoding();
391   MethodNameLoc.CXXOperatorName.EndOpNameLoc
392     = IntroducerRange.getEnd().getRawEncoding();
393   CXXMethodDecl *Method
394     = CXXMethodDecl::Create(Context, Class, EndLoc,
395                             DeclarationNameInfo(MethodName, 
396                                                 IntroducerRange.getBegin(),
397                                                 MethodNameLoc),
398                             MethodType, MethodTypeInfo,
399                             SC_None,
400                             /*isInline=*/true,
401                             /*isConstExpr=*/false,
402                             EndLoc);
403   Method->setAccess(AS_public);
404   
405   // Temporarily set the lexical declaration context to the current
406   // context, so that the Scope stack matches the lexical nesting.
407   Method->setLexicalDeclContext(CurContext);  
408   // Create a function template if we have a template parameter list
409   FunctionTemplateDecl *const TemplateMethod = TemplateParams ?
410             FunctionTemplateDecl::Create(Context, Class,
411                                          Method->getLocation(), MethodName, 
412                                          TemplateParams,
413                                          Method) : nullptr;
414   if (TemplateMethod) {
415     TemplateMethod->setLexicalDeclContext(CurContext);
416     TemplateMethod->setAccess(AS_public);
417     Method->setDescribedFunctionTemplate(TemplateMethod);
418   }
419   
420   // Add parameters.
421   if (!Params.empty()) {
422     Method->setParams(Params);
423     CheckParmsForFunctionDef(Params,
424                              /*CheckParameterNames=*/false);
425
426     for (auto P : Method->parameters())
427       P->setOwningFunction(Method);
428   }
429
430   Decl *ManglingContextDecl;
431   if (MangleNumberingContext *MCtx =
432           getCurrentMangleNumberContext(Class->getDeclContext(),
433                                         ManglingContextDecl)) {
434     unsigned ManglingNumber = MCtx->getManglingNumber(Method);
435     Class->setLambdaMangling(ManglingNumber, ManglingContextDecl);
436   }
437
438   return Method;
439 }
440
441 void Sema::buildLambdaScope(LambdaScopeInfo *LSI,
442                                         CXXMethodDecl *CallOperator,
443                                         SourceRange IntroducerRange,
444                                         LambdaCaptureDefault CaptureDefault,
445                                         SourceLocation CaptureDefaultLoc,
446                                         bool ExplicitParams,
447                                         bool ExplicitResultType,
448                                         bool Mutable) {
449   LSI->CallOperator = CallOperator;
450   CXXRecordDecl *LambdaClass = CallOperator->getParent();
451   LSI->Lambda = LambdaClass;
452   if (CaptureDefault == LCD_ByCopy)
453     LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
454   else if (CaptureDefault == LCD_ByRef)
455     LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
456   LSI->CaptureDefaultLoc = CaptureDefaultLoc;
457   LSI->IntroducerRange = IntroducerRange;
458   LSI->ExplicitParams = ExplicitParams;
459   LSI->Mutable = Mutable;
460
461   if (ExplicitResultType) {
462     LSI->ReturnType = CallOperator->getReturnType();
463
464     if (!LSI->ReturnType->isDependentType() &&
465         !LSI->ReturnType->isVoidType()) {
466       if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
467                               diag::err_lambda_incomplete_result)) {
468         // Do nothing.
469       }
470     }
471   } else {
472     LSI->HasImplicitReturnType = true;
473   }
474 }
475
476 void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
477   LSI->finishedExplicitCaptures();
478 }
479
480 void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {  
481   // Introduce our parameters into the function scope
482   for (unsigned p = 0, NumParams = CallOperator->getNumParams(); 
483        p < NumParams; ++p) {
484     ParmVarDecl *Param = CallOperator->getParamDecl(p);
485     
486     // If this has an identifier, add it to the scope stack.
487     if (CurScope && Param->getIdentifier()) {
488       CheckShadow(CurScope, Param);
489       
490       PushOnScopeChains(Param, CurScope);
491     }
492   }
493 }
494
495 /// If this expression is an enumerator-like expression of some type
496 /// T, return the type T; otherwise, return null.
497 ///
498 /// Pointer comparisons on the result here should always work because
499 /// it's derived from either the parent of an EnumConstantDecl
500 /// (i.e. the definition) or the declaration returned by
501 /// EnumType::getDecl() (i.e. the definition).
502 static EnumDecl *findEnumForBlockReturn(Expr *E) {
503   // An expression is an enumerator-like expression of type T if,
504   // ignoring parens and parens-like expressions:
505   E = E->IgnoreParens();
506
507   //  - it is an enumerator whose enum type is T or
508   if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
509     if (EnumConstantDecl *D
510           = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
511       return cast<EnumDecl>(D->getDeclContext());
512     }
513     return nullptr;
514   }
515
516   //  - it is a comma expression whose RHS is an enumerator-like
517   //    expression of type T or
518   if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
519     if (BO->getOpcode() == BO_Comma)
520       return findEnumForBlockReturn(BO->getRHS());
521     return nullptr;
522   }
523
524   //  - it is a statement-expression whose value expression is an
525   //    enumerator-like expression of type T or
526   if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
527     if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
528       return findEnumForBlockReturn(last);
529     return nullptr;
530   }
531
532   //   - it is a ternary conditional operator (not the GNU ?:
533   //     extension) whose second and third operands are
534   //     enumerator-like expressions of type T or
535   if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
536     if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
537       if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
538         return ED;
539     return nullptr;
540   }
541
542   // (implicitly:)
543   //   - it is an implicit integral conversion applied to an
544   //     enumerator-like expression of type T or
545   if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
546     // We can sometimes see integral conversions in valid
547     // enumerator-like expressions.
548     if (ICE->getCastKind() == CK_IntegralCast)
549       return findEnumForBlockReturn(ICE->getSubExpr());
550
551     // Otherwise, just rely on the type.
552   }
553
554   //   - it is an expression of that formal enum type.
555   if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
556     return ET->getDecl();
557   }
558
559   // Otherwise, nope.
560   return nullptr;
561 }
562
563 /// Attempt to find a type T for which the returned expression of the
564 /// given statement is an enumerator-like expression of that type.
565 static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
566   if (Expr *retValue = ret->getRetValue())
567     return findEnumForBlockReturn(retValue);
568   return nullptr;
569 }
570
571 /// Attempt to find a common type T for which all of the returned
572 /// expressions in a block are enumerator-like expressions of that
573 /// type.
574 static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
575   ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
576
577   // Try to find one for the first return.
578   EnumDecl *ED = findEnumForBlockReturn(*i);
579   if (!ED) return nullptr;
580
581   // Check that the rest of the returns have the same enum.
582   for (++i; i != e; ++i) {
583     if (findEnumForBlockReturn(*i) != ED)
584       return nullptr;
585   }
586
587   // Never infer an anonymous enum type.
588   if (!ED->hasNameForLinkage()) return nullptr;
589
590   return ED;
591 }
592
593 /// Adjust the given return statements so that they formally return
594 /// the given type.  It should require, at most, an IntegralCast.
595 static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
596                                      QualType returnType) {
597   for (ArrayRef<ReturnStmt*>::iterator
598          i = returns.begin(), e = returns.end(); i != e; ++i) {
599     ReturnStmt *ret = *i;
600     Expr *retValue = ret->getRetValue();
601     if (S.Context.hasSameType(retValue->getType(), returnType))
602       continue;
603
604     // Right now we only support integral fixup casts.
605     assert(returnType->isIntegralOrUnscopedEnumerationType());
606     assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
607
608     ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
609
610     Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
611     E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast,
612                                  E, /*base path*/ nullptr, VK_RValue);
613     if (cleanups) {
614       cleanups->setSubExpr(E);
615     } else {
616       ret->setRetValue(E);
617     }
618   }
619 }
620
621 void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
622   assert(CSI.HasImplicitReturnType);
623   // If it was ever a placeholder, it had to been deduced to DependentTy.
624   assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType()); 
625   assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) &&
626          "lambda expressions use auto deduction in C++14 onwards");
627
628   // C++ core issue 975:
629   //   If a lambda-expression does not include a trailing-return-type,
630   //   it is as if the trailing-return-type denotes the following type:
631   //     - if there are no return statements in the compound-statement,
632   //       or all return statements return either an expression of type
633   //       void or no expression or braced-init-list, the type void;
634   //     - otherwise, if all return statements return an expression
635   //       and the types of the returned expressions after
636   //       lvalue-to-rvalue conversion (4.1 [conv.lval]),
637   //       array-to-pointer conversion (4.2 [conv.array]), and
638   //       function-to-pointer conversion (4.3 [conv.func]) are the
639   //       same, that common type;
640   //     - otherwise, the program is ill-formed.
641   //
642   // C++ core issue 1048 additionally removes top-level cv-qualifiers
643   // from the types of returned expressions to match the C++14 auto
644   // deduction rules.
645   //
646   // In addition, in blocks in non-C++ modes, if all of the return
647   // statements are enumerator-like expressions of some type T, where
648   // T has a name for linkage, then we infer the return type of the
649   // block to be that type.
650
651   // First case: no return statements, implicit void return type.
652   ASTContext &Ctx = getASTContext();
653   if (CSI.Returns.empty()) {
654     // It's possible there were simply no /valid/ return statements.
655     // In this case, the first one we found may have at least given us a type.
656     if (CSI.ReturnType.isNull())
657       CSI.ReturnType = Ctx.VoidTy;
658     return;
659   }
660
661   // Second case: at least one return statement has dependent type.
662   // Delay type checking until instantiation.
663   assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
664   if (CSI.ReturnType->isDependentType())
665     return;
666
667   // Try to apply the enum-fuzz rule.
668   if (!getLangOpts().CPlusPlus) {
669     assert(isa<BlockScopeInfo>(CSI));
670     const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
671     if (ED) {
672       CSI.ReturnType = Context.getTypeDeclType(ED);
673       adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
674       return;
675     }
676   }
677
678   // Third case: only one return statement. Don't bother doing extra work!
679   SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
680                                          E = CSI.Returns.end();
681   if (I+1 == E)
682     return;
683
684   // General case: many return statements.
685   // Check that they all have compatible return types.
686
687   // We require the return types to strictly match here.
688   // Note that we've already done the required promotions as part of
689   // processing the return statement.
690   for (; I != E; ++I) {
691     const ReturnStmt *RS = *I;
692     const Expr *RetE = RS->getRetValue();
693
694     QualType ReturnType =
695         (RetE ? RetE->getType() : Context.VoidTy).getUnqualifiedType();
696     if (Context.getCanonicalFunctionResultType(ReturnType) ==
697           Context.getCanonicalFunctionResultType(CSI.ReturnType))
698       continue;
699
700     // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
701     // TODO: It's possible that the *first* return is the divergent one.
702     Diag(RS->getLocStart(),
703          diag::err_typecheck_missing_return_type_incompatible)
704       << ReturnType << CSI.ReturnType
705       << isa<LambdaScopeInfo>(CSI);
706     // Continue iterating so that we keep emitting diagnostics.
707   }
708 }
709
710 QualType Sema::buildLambdaInitCaptureInitialization(SourceLocation Loc,
711                                                     bool ByRef,
712                                                     IdentifierInfo *Id,
713                                                     bool IsDirectInit,
714                                                     Expr *&Init) {
715   // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to
716   // deduce against.
717   QualType DeductType = Context.getAutoDeductType();
718   TypeLocBuilder TLB;
719   TLB.pushTypeSpec(DeductType).setNameLoc(Loc);
720   if (ByRef) {
721     DeductType = BuildReferenceType(DeductType, true, Loc, Id);
722     assert(!DeductType.isNull() && "can't build reference to auto");
723     TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
724   }
725   TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
726
727   // Deduce the type of the init capture.
728   QualType DeducedType = deduceVarTypeFromInitializer(
729       /*VarDecl*/nullptr, DeclarationName(Id), DeductType, TSI,
730       SourceRange(Loc, Loc), IsDirectInit, Init);
731   if (DeducedType.isNull())
732     return QualType();
733
734   // Are we a non-list direct initialization?
735   ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
736
737   // Perform initialization analysis and ensure any implicit conversions
738   // (such as lvalue-to-rvalue) are enforced.
739   InitializedEntity Entity =
740       InitializedEntity::InitializeLambdaCapture(Id, DeducedType, Loc);
741   InitializationKind Kind =
742       IsDirectInit
743           ? (CXXDirectInit ? InitializationKind::CreateDirect(
744                                  Loc, Init->getLocStart(), Init->getLocEnd())
745                            : InitializationKind::CreateDirectList(Loc))
746           : InitializationKind::CreateCopy(Loc, Init->getLocStart());
747
748   MultiExprArg Args = Init;
749   if (CXXDirectInit)
750     Args =
751         MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
752   QualType DclT;
753   InitializationSequence InitSeq(*this, Entity, Kind, Args);
754   ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
755
756   if (Result.isInvalid())
757     return QualType();
758   Init = Result.getAs<Expr>();
759
760   // The init-capture initialization is a full-expression that must be
761   // processed as one before we enter the declcontext of the lambda's
762   // call-operator.
763   Result = ActOnFinishFullExpr(Init, Loc, /*DiscardedValue*/ false,
764                                /*IsConstexpr*/ false,
765                                /*IsLambdaInitCaptureInitalizer*/ true);
766   if (Result.isInvalid())
767     return QualType();
768
769   Init = Result.getAs<Expr>();
770   return DeducedType;
771 }
772
773 VarDecl *Sema::createLambdaInitCaptureVarDecl(SourceLocation Loc,
774                                               QualType InitCaptureType,
775                                               IdentifierInfo *Id,
776                                               unsigned InitStyle, Expr *Init) {
777   TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType,
778       Loc);
779   // Create a dummy variable representing the init-capture. This is not actually
780   // used as a variable, and only exists as a way to name and refer to the
781   // init-capture.
782   // FIXME: Pass in separate source locations for '&' and identifier.
783   VarDecl *NewVD = VarDecl::Create(Context, CurContext, Loc,
784                                    Loc, Id, InitCaptureType, TSI, SC_Auto);
785   NewVD->setInitCapture(true);
786   NewVD->setReferenced(true);
787   // FIXME: Pass in a VarDecl::InitializationStyle.
788   NewVD->setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle));
789   NewVD->markUsed(Context);
790   NewVD->setInit(Init);
791   return NewVD;
792 }
793
794 FieldDecl *Sema::buildInitCaptureField(LambdaScopeInfo *LSI, VarDecl *Var) {
795   FieldDecl *Field = FieldDecl::Create(
796       Context, LSI->Lambda, Var->getLocation(), Var->getLocation(),
797       nullptr, Var->getType(), Var->getTypeSourceInfo(), nullptr, false,
798       ICIS_NoInit);
799   Field->setImplicit(true);
800   Field->setAccess(AS_private);
801   LSI->Lambda->addDecl(Field);
802
803   LSI->addCapture(Var, /*isBlock*/false, Var->getType()->isReferenceType(),
804                   /*isNested*/false, Var->getLocation(), SourceLocation(),
805                   Var->getType(), Var->getInit());
806   return Field;
807 }
808
809 void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
810                                         Declarator &ParamInfo,
811                                         Scope *CurScope) {
812   // Determine if we're within a context where we know that the lambda will
813   // be dependent, because there are template parameters in scope.
814   bool KnownDependent = false;
815   LambdaScopeInfo *const LSI = getCurLambda();
816   assert(LSI && "LambdaScopeInfo should be on stack!");
817
818   // The lambda-expression's closure type might be dependent even if its
819   // semantic context isn't, if it appears within a default argument of a
820   // function template.
821   if (CurScope->getTemplateParamParent())
822     KnownDependent = true;
823
824   // Determine the signature of the call operator.
825   TypeSourceInfo *MethodTyInfo;
826   bool ExplicitParams = true;
827   bool ExplicitResultType = true;
828   bool ContainsUnexpandedParameterPack = false;
829   SourceLocation EndLoc;
830   SmallVector<ParmVarDecl *, 8> Params;
831   if (ParamInfo.getNumTypeObjects() == 0) {
832     // C++11 [expr.prim.lambda]p4:
833     //   If a lambda-expression does not include a lambda-declarator, it is as 
834     //   if the lambda-declarator were ().
835     FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
836         /*IsVariadic=*/false, /*IsCXXMethod=*/true));
837     EPI.HasTrailingReturn = true;
838     EPI.TypeQuals |= DeclSpec::TQ_const;
839     // C++1y [expr.prim.lambda]:
840     //   The lambda return type is 'auto', which is replaced by the
841     //   trailing-return type if provided and/or deduced from 'return'
842     //   statements
843     // We don't do this before C++1y, because we don't support deduced return
844     // types there.
845     QualType DefaultTypeForNoTrailingReturn =
846         getLangOpts().CPlusPlus14 ? Context.getAutoDeductType()
847                                   : Context.DependentTy;
848     QualType MethodTy =
849         Context.getFunctionType(DefaultTypeForNoTrailingReturn, None, EPI);
850     MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
851     ExplicitParams = false;
852     ExplicitResultType = false;
853     EndLoc = Intro.Range.getEnd();
854   } else {
855     assert(ParamInfo.isFunctionDeclarator() &&
856            "lambda-declarator is a function");
857     DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
858
859     // C++11 [expr.prim.lambda]p5:
860     //   This function call operator is declared const (9.3.1) if and only if 
861     //   the lambda-expression's parameter-declaration-clause is not followed 
862     //   by mutable. It is neither virtual nor declared volatile. [...]
863     if (!FTI.hasMutableQualifier())
864       FTI.TypeQuals |= DeclSpec::TQ_const;
865
866     MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
867     assert(MethodTyInfo && "no type from lambda-declarator");
868     EndLoc = ParamInfo.getSourceRange().getEnd();
869
870     ExplicitResultType = FTI.hasTrailingReturnType();
871
872     if (FTIHasNonVoidParameters(FTI)) {
873       Params.reserve(FTI.NumParams);
874       for (unsigned i = 0, e = FTI.NumParams; i != e; ++i)
875         Params.push_back(cast<ParmVarDecl>(FTI.Params[i].Param));
876     }
877
878     // Check for unexpanded parameter packs in the method type.
879     if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
880       ContainsUnexpandedParameterPack = true;
881   }
882
883   CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
884                                                  KnownDependent, Intro.Default);
885
886   CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
887                                                 MethodTyInfo, EndLoc, Params);
888   if (ExplicitParams)
889     CheckCXXDefaultArguments(Method);
890   
891   // Attributes on the lambda apply to the method.  
892   ProcessDeclAttributes(CurScope, Method, ParamInfo);
893   
894   // Introduce the function call operator as the current declaration context.
895   PushDeclContext(CurScope, Method);
896     
897   // Build the lambda scope.
898   buildLambdaScope(LSI, Method, Intro.Range, Intro.Default, Intro.DefaultLoc,
899                    ExplicitParams, ExplicitResultType, !Method->isConst());
900
901   // C++11 [expr.prim.lambda]p9:
902   //   A lambda-expression whose smallest enclosing scope is a block scope is a
903   //   local lambda expression; any other lambda expression shall not have a
904   //   capture-default or simple-capture in its lambda-introducer.
905   //
906   // For simple-captures, this is covered by the check below that any named
907   // entity is a variable that can be captured.
908   //
909   // For DR1632, we also allow a capture-default in any context where we can
910   // odr-use 'this' (in particular, in a default initializer for a non-static
911   // data member).
912   if (Intro.Default != LCD_None && !Class->getParent()->isFunctionOrMethod() &&
913       (getCurrentThisType().isNull() ||
914        CheckCXXThisCapture(SourceLocation(), /*Explicit*/true,
915                            /*BuildAndDiagnose*/false)))
916     Diag(Intro.DefaultLoc, diag::err_capture_default_non_local);
917
918   // Distinct capture names, for diagnostics.
919   llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
920
921   // Handle explicit captures.
922   SourceLocation PrevCaptureLoc
923     = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
924   for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E;
925        PrevCaptureLoc = C->Loc, ++C) {
926     if (C->Kind == LCK_This || C->Kind == LCK_StarThis) {
927       if (C->Kind == LCK_StarThis) 
928         Diag(C->Loc, !getLangOpts().CPlusPlus1z
929                              ? diag::ext_star_this_lambda_capture_cxx1z
930                              : diag::warn_cxx14_compat_star_this_lambda_capture);
931
932       // C++11 [expr.prim.lambda]p8:
933       //   An identifier or this shall not appear more than once in a 
934       //   lambda-capture.
935       if (LSI->isCXXThisCaptured()) {
936         Diag(C->Loc, diag::err_capture_more_than_once)
937             << "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation())
938             << FixItHint::CreateRemoval(
939                    SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
940         continue;
941       }
942
943       // C++1z [expr.prim.lambda]p8:
944       //  If a lambda-capture includes a capture-default that is =, each
945       //  simple-capture of that lambda-capture shall be of the form "&
946       //  identifier" or "* this". [ Note: The form [&,this] is redundant but
947       //  accepted for compatibility with ISO C++14. --end note ]
948       if (Intro.Default == LCD_ByCopy && C->Kind != LCK_StarThis) {
949         Diag(C->Loc, diag::err_this_capture_with_copy_default)
950             << FixItHint::CreateRemoval(
951                 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
952         continue;
953       }
954
955       // C++11 [expr.prim.lambda]p12:
956       //   If this is captured by a local lambda expression, its nearest
957       //   enclosing function shall be a non-static member function.
958       QualType ThisCaptureType = getCurrentThisType();
959       if (ThisCaptureType.isNull()) {
960         Diag(C->Loc, diag::err_this_capture) << true;
961         continue;
962       }
963       
964       CheckCXXThisCapture(C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true,
965                           /*FunctionScopeIndexToStopAtPtr*/ nullptr,
966                           C->Kind == LCK_StarThis);
967       continue;
968     }
969
970     assert(C->Id && "missing identifier for capture");
971
972     if (C->Init.isInvalid())
973       continue;
974
975     VarDecl *Var = nullptr;
976     if (C->Init.isUsable()) {
977       Diag(C->Loc, getLangOpts().CPlusPlus14
978                        ? diag::warn_cxx11_compat_init_capture
979                        : diag::ext_init_capture);
980
981       if (C->Init.get()->containsUnexpandedParameterPack())
982         ContainsUnexpandedParameterPack = true;
983       // If the initializer expression is usable, but the InitCaptureType
984       // is not, then an error has occurred - so ignore the capture for now.
985       // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
986       // FIXME: we should create the init capture variable and mark it invalid 
987       // in this case.
988       if (C->InitCaptureType.get().isNull()) 
989         continue;
990
991       unsigned InitStyle;
992       switch (C->InitKind) {
993       case LambdaCaptureInitKind::NoInit:
994         llvm_unreachable("not an init-capture?");
995       case LambdaCaptureInitKind::CopyInit:
996         InitStyle = VarDecl::CInit;
997         break;
998       case LambdaCaptureInitKind::DirectInit:
999         InitStyle = VarDecl::CallInit;
1000         break;
1001       case LambdaCaptureInitKind::ListInit:
1002         InitStyle = VarDecl::ListInit;
1003         break;
1004       }
1005       Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
1006                                            C->Id, InitStyle, C->Init.get());
1007       // C++1y [expr.prim.lambda]p11:
1008       //   An init-capture behaves as if it declares and explicitly
1009       //   captures a variable [...] whose declarative region is the
1010       //   lambda-expression's compound-statement
1011       if (Var)
1012         PushOnScopeChains(Var, CurScope, false);
1013     } else {
1014       assert(C->InitKind == LambdaCaptureInitKind::NoInit &&
1015              "init capture has valid but null init?");
1016
1017       // C++11 [expr.prim.lambda]p8:
1018       //   If a lambda-capture includes a capture-default that is &, the 
1019       //   identifiers in the lambda-capture shall not be preceded by &.
1020       //   If a lambda-capture includes a capture-default that is =, [...]
1021       //   each identifier it contains shall be preceded by &.
1022       if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
1023         Diag(C->Loc, diag::err_reference_capture_with_reference_default)
1024             << FixItHint::CreateRemoval(
1025                 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1026         continue;
1027       } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
1028         Diag(C->Loc, diag::err_copy_capture_with_copy_default)
1029             << FixItHint::CreateRemoval(
1030                 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1031         continue;
1032       }
1033
1034       // C++11 [expr.prim.lambda]p10:
1035       //   The identifiers in a capture-list are looked up using the usual
1036       //   rules for unqualified name lookup (3.4.1)
1037       DeclarationNameInfo Name(C->Id, C->Loc);
1038       LookupResult R(*this, Name, LookupOrdinaryName);
1039       LookupName(R, CurScope);
1040       if (R.isAmbiguous())
1041         continue;
1042       if (R.empty()) {
1043         // FIXME: Disable corrections that would add qualification?
1044         CXXScopeSpec ScopeSpec;
1045         if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R,
1046                                 llvm::make_unique<DeclFilterCCC<VarDecl>>()))
1047           continue;
1048       }
1049
1050       Var = R.getAsSingle<VarDecl>();
1051       if (Var && DiagnoseUseOfDecl(Var, C->Loc))
1052         continue;
1053     }
1054
1055     // C++11 [expr.prim.lambda]p8:
1056     //   An identifier or this shall not appear more than once in a
1057     //   lambda-capture.
1058     if (!CaptureNames.insert(C->Id).second) {
1059       if (Var && LSI->isCaptured(Var)) {
1060         Diag(C->Loc, diag::err_capture_more_than_once)
1061             << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
1062             << FixItHint::CreateRemoval(
1063                    SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1064       } else
1065         // Previous capture captured something different (one or both was
1066         // an init-cpature): no fixit.
1067         Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
1068       continue;
1069     }
1070
1071     // C++11 [expr.prim.lambda]p10:
1072     //   [...] each such lookup shall find a variable with automatic storage
1073     //   duration declared in the reaching scope of the local lambda expression.
1074     // Note that the 'reaching scope' check happens in tryCaptureVariable().
1075     if (!Var) {
1076       Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
1077       continue;
1078     }
1079
1080     // Ignore invalid decls; they'll just confuse the code later.
1081     if (Var->isInvalidDecl())
1082       continue;
1083
1084     if (!Var->hasLocalStorage()) {
1085       Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
1086       Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
1087       continue;
1088     }
1089
1090     // C++11 [expr.prim.lambda]p23:
1091     //   A capture followed by an ellipsis is a pack expansion (14.5.3).
1092     SourceLocation EllipsisLoc;
1093     if (C->EllipsisLoc.isValid()) {
1094       if (Var->isParameterPack()) {
1095         EllipsisLoc = C->EllipsisLoc;
1096       } else {
1097         Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1098           << SourceRange(C->Loc);
1099         
1100         // Just ignore the ellipsis.
1101       }
1102     } else if (Var->isParameterPack()) {
1103       ContainsUnexpandedParameterPack = true;
1104     }
1105
1106     if (C->Init.isUsable()) {
1107       buildInitCaptureField(LSI, Var);
1108     } else {
1109       TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
1110                                                    TryCapture_ExplicitByVal;
1111       tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
1112     }
1113   }
1114   finishLambdaExplicitCaptures(LSI);
1115
1116   LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1117
1118   // Add lambda parameters into scope.
1119   addLambdaParameters(Method, CurScope);
1120
1121   // Enter a new evaluation context to insulate the lambda from any
1122   // cleanups from the enclosing full-expression.
1123   PushExpressionEvaluationContext(PotentiallyEvaluated);  
1124 }
1125
1126 void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
1127                             bool IsInstantiation) {
1128   LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(FunctionScopes.back());
1129
1130   // Leave the expression-evaluation context.
1131   DiscardCleanupsInEvaluationContext();
1132   PopExpressionEvaluationContext();
1133
1134   // Leave the context of the lambda.
1135   if (!IsInstantiation)
1136     PopDeclContext();
1137
1138   // Finalize the lambda.
1139   CXXRecordDecl *Class = LSI->Lambda;
1140   Class->setInvalidDecl();
1141   SmallVector<Decl*, 4> Fields(Class->fields());
1142   ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
1143               SourceLocation(), nullptr);
1144   CheckCompletedCXXClass(Class);
1145
1146   PopFunctionScopeInfo();
1147 }
1148
1149 /// \brief Add a lambda's conversion to function pointer, as described in
1150 /// C++11 [expr.prim.lambda]p6.
1151 static void addFunctionPointerConversion(Sema &S, 
1152                                          SourceRange IntroducerRange,
1153                                          CXXRecordDecl *Class,
1154                                          CXXMethodDecl *CallOperator) {
1155   // This conversion is explicitly disabled if the lambda's function has
1156   // pass_object_size attributes on any of its parameters.
1157   if (llvm::any_of(CallOperator->parameters(),
1158                    std::mem_fn(&ParmVarDecl::hasAttr<PassObjectSizeAttr>)))
1159     return;
1160
1161   // Add the conversion to function pointer.
1162   const FunctionProtoType *CallOpProto = 
1163       CallOperator->getType()->getAs<FunctionProtoType>();
1164   const FunctionProtoType::ExtProtoInfo CallOpExtInfo = 
1165       CallOpProto->getExtProtoInfo();   
1166   QualType PtrToFunctionTy;
1167   QualType InvokerFunctionTy;
1168   {
1169     FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
1170     CallingConv CC = S.Context.getDefaultCallingConvention(
1171         CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
1172     InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
1173     InvokerExtInfo.TypeQuals = 0;
1174     assert(InvokerExtInfo.RefQualifier == RQ_None && 
1175         "Lambda's call operator should not have a reference qualifier");
1176     InvokerFunctionTy =
1177         S.Context.getFunctionType(CallOpProto->getReturnType(),
1178                                   CallOpProto->getParamTypes(), InvokerExtInfo);
1179     PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
1180   }
1181
1182   // Create the type of the conversion function.
1183   FunctionProtoType::ExtProtoInfo ConvExtInfo(
1184       S.Context.getDefaultCallingConvention(
1185       /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1186   // The conversion function is always const.
1187   ConvExtInfo.TypeQuals = Qualifiers::Const;
1188   QualType ConvTy = 
1189       S.Context.getFunctionType(PtrToFunctionTy, None, ConvExtInfo);
1190
1191   SourceLocation Loc = IntroducerRange.getBegin();
1192   DeclarationName ConversionName
1193     = S.Context.DeclarationNames.getCXXConversionFunctionName(
1194         S.Context.getCanonicalType(PtrToFunctionTy));
1195   DeclarationNameLoc ConvNameLoc;
1196   // Construct a TypeSourceInfo for the conversion function, and wire
1197   // all the parameters appropriately for the FunctionProtoTypeLoc 
1198   // so that everything works during transformation/instantiation of 
1199   // generic lambdas.
1200   // The main reason for wiring up the parameters of the conversion
1201   // function with that of the call operator is so that constructs
1202   // like the following work:
1203   // auto L = [](auto b) {                <-- 1
1204   //   return [](auto a) -> decltype(a) { <-- 2
1205   //      return a;
1206   //   };
1207   // };
1208   // int (*fp)(int) = L(5);  
1209   // Because the trailing return type can contain DeclRefExprs that refer
1210   // to the original call operator's variables, we hijack the call 
1211   // operators ParmVarDecls below.
1212   TypeSourceInfo *ConvNamePtrToFunctionTSI = 
1213       S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
1214   ConvNameLoc.NamedType.TInfo = ConvNamePtrToFunctionTSI;
1215
1216   // The conversion function is a conversion to a pointer-to-function.
1217   TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
1218   FunctionProtoTypeLoc ConvTL = 
1219       ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
1220   // Get the result of the conversion function which is a pointer-to-function.
1221   PointerTypeLoc PtrToFunctionTL = 
1222       ConvTL.getReturnLoc().getAs<PointerTypeLoc>();
1223   // Do the same for the TypeSourceInfo that is used to name the conversion
1224   // operator.
1225   PointerTypeLoc ConvNamePtrToFunctionTL = 
1226       ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
1227   
1228   // Get the underlying function types that the conversion function will
1229   // be converting to (should match the type of the call operator).
1230   FunctionProtoTypeLoc CallOpConvTL = 
1231       PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1232   FunctionProtoTypeLoc CallOpConvNameTL = 
1233     ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1234   
1235   // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
1236   // These parameter's are essentially used to transform the name and
1237   // the type of the conversion operator.  By using the same parameters
1238   // as the call operator's we don't have to fix any back references that
1239   // the trailing return type of the call operator's uses (such as 
1240   // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
1241   // - we can simply use the return type of the call operator, and 
1242   // everything should work. 
1243   SmallVector<ParmVarDecl *, 4> InvokerParams;
1244   for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1245     ParmVarDecl *From = CallOperator->getParamDecl(I);
1246
1247     InvokerParams.push_back(ParmVarDecl::Create(S.Context, 
1248            // Temporarily add to the TU. This is set to the invoker below.
1249                                              S.Context.getTranslationUnitDecl(),
1250                                              From->getLocStart(),
1251                                              From->getLocation(),
1252                                              From->getIdentifier(),
1253                                              From->getType(),
1254                                              From->getTypeSourceInfo(),
1255                                              From->getStorageClass(),
1256                                              /*DefaultArg=*/nullptr));
1257     CallOpConvTL.setParam(I, From);
1258     CallOpConvNameTL.setParam(I, From);
1259   }
1260
1261   CXXConversionDecl *Conversion 
1262     = CXXConversionDecl::Create(S.Context, Class, Loc, 
1263                                 DeclarationNameInfo(ConversionName, 
1264                                   Loc, ConvNameLoc),
1265                                 ConvTy, 
1266                                 ConvTSI,
1267                                 /*isInline=*/true, /*isExplicit=*/false,
1268                                 /*isConstexpr=*/false, 
1269                                 CallOperator->getBody()->getLocEnd());
1270   Conversion->setAccess(AS_public);
1271   Conversion->setImplicit(true);
1272
1273   if (Class->isGenericLambda()) {
1274     // Create a template version of the conversion operator, using the template
1275     // parameter list of the function call operator.
1276     FunctionTemplateDecl *TemplateCallOperator = 
1277             CallOperator->getDescribedFunctionTemplate();
1278     FunctionTemplateDecl *ConversionTemplate =
1279                   FunctionTemplateDecl::Create(S.Context, Class,
1280                                       Loc, ConversionName,
1281                                       TemplateCallOperator->getTemplateParameters(),
1282                                       Conversion);
1283     ConversionTemplate->setAccess(AS_public);
1284     ConversionTemplate->setImplicit(true);
1285     Conversion->setDescribedFunctionTemplate(ConversionTemplate);
1286     Class->addDecl(ConversionTemplate);
1287   } else
1288     Class->addDecl(Conversion);
1289   // Add a non-static member function that will be the result of
1290   // the conversion with a certain unique ID.
1291   DeclarationName InvokerName = &S.Context.Idents.get(
1292                                                  getLambdaStaticInvokerName());
1293   // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
1294   // we should get a prebuilt TrivialTypeSourceInfo from Context
1295   // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
1296   // then rewire the parameters accordingly, by hoisting up the InvokeParams
1297   // loop below and then use its Params to set Invoke->setParams(...) below.
1298   // This would avoid the 'const' qualifier of the calloperator from 
1299   // contaminating the type of the invoker, which is currently adjusted 
1300   // in SemaTemplateDeduction.cpp:DeduceTemplateArguments.  Fixing the
1301   // trailing return type of the invoker would require a visitor to rebuild
1302   // the trailing return type and adjusting all back DeclRefExpr's to refer
1303   // to the new static invoker parameters - not the call operator's.
1304   CXXMethodDecl *Invoke
1305     = CXXMethodDecl::Create(S.Context, Class, Loc, 
1306                             DeclarationNameInfo(InvokerName, Loc), 
1307                             InvokerFunctionTy,
1308                             CallOperator->getTypeSourceInfo(), 
1309                             SC_Static, /*IsInline=*/true,
1310                             /*IsConstexpr=*/false, 
1311                             CallOperator->getBody()->getLocEnd());
1312   for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
1313     InvokerParams[I]->setOwningFunction(Invoke);
1314   Invoke->setParams(InvokerParams);
1315   Invoke->setAccess(AS_private);
1316   Invoke->setImplicit(true);
1317   if (Class->isGenericLambda()) {
1318     FunctionTemplateDecl *TemplateCallOperator = 
1319             CallOperator->getDescribedFunctionTemplate();
1320     FunctionTemplateDecl *StaticInvokerTemplate = FunctionTemplateDecl::Create(
1321                           S.Context, Class, Loc, InvokerName,
1322                           TemplateCallOperator->getTemplateParameters(),
1323                           Invoke);
1324     StaticInvokerTemplate->setAccess(AS_private);
1325     StaticInvokerTemplate->setImplicit(true);
1326     Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
1327     Class->addDecl(StaticInvokerTemplate);
1328   } else
1329     Class->addDecl(Invoke);
1330 }
1331
1332 /// \brief Add a lambda's conversion to block pointer.
1333 static void addBlockPointerConversion(Sema &S, 
1334                                       SourceRange IntroducerRange,
1335                                       CXXRecordDecl *Class,
1336                                       CXXMethodDecl *CallOperator) {
1337   const FunctionProtoType *Proto =
1338       CallOperator->getType()->getAs<FunctionProtoType>();
1339
1340   // The function type inside the block pointer type is the same as the call
1341   // operator with some tweaks. The calling convention is the default free
1342   // function convention, and the type qualifications are lost.
1343   FunctionProtoType::ExtProtoInfo BlockEPI = Proto->getExtProtoInfo();
1344   BlockEPI.ExtInfo =
1345       BlockEPI.ExtInfo.withCallingConv(S.Context.getDefaultCallingConvention(
1346           Proto->isVariadic(), /*IsCXXMethod=*/false));
1347   BlockEPI.TypeQuals = 0;
1348   QualType FunctionTy = S.Context.getFunctionType(
1349       Proto->getReturnType(), Proto->getParamTypes(), BlockEPI);
1350   QualType BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
1351
1352   FunctionProtoType::ExtProtoInfo ConversionEPI(
1353       S.Context.getDefaultCallingConvention(
1354           /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1355   ConversionEPI.TypeQuals = Qualifiers::Const;
1356   QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ConversionEPI);
1357
1358   SourceLocation Loc = IntroducerRange.getBegin();
1359   DeclarationName Name
1360     = S.Context.DeclarationNames.getCXXConversionFunctionName(
1361         S.Context.getCanonicalType(BlockPtrTy));
1362   DeclarationNameLoc NameLoc;
1363   NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
1364   CXXConversionDecl *Conversion 
1365     = CXXConversionDecl::Create(S.Context, Class, Loc, 
1366                                 DeclarationNameInfo(Name, Loc, NameLoc),
1367                                 ConvTy, 
1368                                 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
1369                                 /*isInline=*/true, /*isExplicit=*/false,
1370                                 /*isConstexpr=*/false, 
1371                                 CallOperator->getBody()->getLocEnd());
1372   Conversion->setAccess(AS_public);
1373   Conversion->setImplicit(true);
1374   Class->addDecl(Conversion);
1375 }
1376
1377 static ExprResult performLambdaVarCaptureInitialization(
1378     Sema &S, LambdaScopeInfo::Capture &Capture,
1379     FieldDecl *Field,
1380     SmallVectorImpl<VarDecl *> &ArrayIndexVars,
1381     SmallVectorImpl<unsigned> &ArrayIndexStarts) {
1382   assert(Capture.isVariableCapture() && "not a variable capture");
1383
1384   auto *Var = Capture.getVariable();
1385   SourceLocation Loc = Capture.getLocation();
1386
1387   // C++11 [expr.prim.lambda]p21:
1388   //   When the lambda-expression is evaluated, the entities that
1389   //   are captured by copy are used to direct-initialize each
1390   //   corresponding non-static data member of the resulting closure
1391   //   object. (For array members, the array elements are
1392   //   direct-initialized in increasing subscript order.) These
1393   //   initializations are performed in the (unspecified) order in
1394   //   which the non-static data members are declared.
1395       
1396   // C++ [expr.prim.lambda]p12:
1397   //   An entity captured by a lambda-expression is odr-used (3.2) in
1398   //   the scope containing the lambda-expression.
1399   ExprResult RefResult = S.BuildDeclarationNameExpr(
1400       CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
1401   if (RefResult.isInvalid())
1402     return ExprError();
1403   Expr *Ref = RefResult.get();
1404
1405   QualType FieldType = Field->getType();
1406
1407   // When the variable has array type, create index variables for each
1408   // dimension of the array. We use these index variables to subscript
1409   // the source array, and other clients (e.g., CodeGen) will perform
1410   // the necessary iteration with these index variables.
1411   //
1412   // FIXME: This is dumb. Add a proper AST representation for array
1413   // copy-construction and use it here.
1414   SmallVector<VarDecl *, 4> IndexVariables;
1415   QualType BaseType = FieldType;
1416   QualType SizeType = S.Context.getSizeType();
1417   ArrayIndexStarts.push_back(ArrayIndexVars.size());
1418   while (const ConstantArrayType *Array
1419                         = S.Context.getAsConstantArrayType(BaseType)) {
1420     // Create the iteration variable for this array index.
1421     IdentifierInfo *IterationVarName = nullptr;
1422     {
1423       SmallString<8> Str;
1424       llvm::raw_svector_ostream OS(Str);
1425       OS << "__i" << IndexVariables.size();
1426       IterationVarName = &S.Context.Idents.get(OS.str());
1427     }
1428     VarDecl *IterationVar = VarDecl::Create(
1429         S.Context, S.CurContext, Loc, Loc, IterationVarName, SizeType,
1430         S.Context.getTrivialTypeSourceInfo(SizeType, Loc), SC_None);
1431     IterationVar->setImplicit();
1432     IndexVariables.push_back(IterationVar);
1433     ArrayIndexVars.push_back(IterationVar);
1434     
1435     // Create a reference to the iteration variable.
1436     ExprResult IterationVarRef =
1437         S.BuildDeclRefExpr(IterationVar, SizeType, VK_LValue, Loc);
1438     assert(!IterationVarRef.isInvalid() &&
1439            "Reference to invented variable cannot fail!");
1440     IterationVarRef = S.DefaultLvalueConversion(IterationVarRef.get());
1441     assert(!IterationVarRef.isInvalid() &&
1442            "Conversion of invented variable cannot fail!");
1443     
1444     // Subscript the array with this iteration variable.
1445     ExprResult Subscript =
1446         S.CreateBuiltinArraySubscriptExpr(Ref, Loc, IterationVarRef.get(), Loc);
1447     if (Subscript.isInvalid())
1448       return ExprError();
1449
1450     Ref = Subscript.get();
1451     BaseType = Array->getElementType();
1452   }
1453
1454   // Construct the entity that we will be initializing. For an array, this
1455   // will be first element in the array, which may require several levels
1456   // of array-subscript entities. 
1457   SmallVector<InitializedEntity, 4> Entities;
1458   Entities.reserve(1 + IndexVariables.size());
1459   Entities.push_back(InitializedEntity::InitializeLambdaCapture(
1460       Var->getIdentifier(), FieldType, Loc));
1461   for (unsigned I = 0, N = IndexVariables.size(); I != N; ++I)
1462     Entities.push_back(
1463         InitializedEntity::InitializeElement(S.Context, 0, Entities.back()));
1464
1465   InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc);
1466   InitializationSequence Init(S, Entities.back(), InitKind, Ref);
1467   return Init.Perform(S, Entities.back(), InitKind, Ref);
1468 }
1469          
1470 ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, 
1471                                  Scope *CurScope) {
1472   LambdaScopeInfo LSI = *cast<LambdaScopeInfo>(FunctionScopes.back());
1473   ActOnFinishFunctionBody(LSI.CallOperator, Body);
1474   return BuildLambdaExpr(StartLoc, Body->getLocEnd(), &LSI);
1475 }
1476
1477 static LambdaCaptureDefault
1478 mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS) {
1479   switch (ICS) {
1480   case CapturingScopeInfo::ImpCap_None:
1481     return LCD_None;
1482   case CapturingScopeInfo::ImpCap_LambdaByval:
1483     return LCD_ByCopy;
1484   case CapturingScopeInfo::ImpCap_CapturedRegion:
1485   case CapturingScopeInfo::ImpCap_LambdaByref:
1486     return LCD_ByRef;
1487   case CapturingScopeInfo::ImpCap_Block:
1488     llvm_unreachable("block capture in lambda");
1489   }
1490   llvm_unreachable("Unknown implicit capture style");
1491 }
1492
1493 ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc,
1494                                  LambdaScopeInfo *LSI) {
1495   // Collect information from the lambda scope.
1496   SmallVector<LambdaCapture, 4> Captures;
1497   SmallVector<Expr *, 4> CaptureInits;
1498   SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc;
1499   LambdaCaptureDefault CaptureDefault =
1500       mapImplicitCaptureStyle(LSI->ImpCaptureStyle);
1501   CXXRecordDecl *Class;
1502   CXXMethodDecl *CallOperator;
1503   SourceRange IntroducerRange;
1504   bool ExplicitParams;
1505   bool ExplicitResultType;
1506   CleanupInfo LambdaCleanup;
1507   bool ContainsUnexpandedParameterPack;
1508   SmallVector<VarDecl *, 4> ArrayIndexVars;
1509   SmallVector<unsigned, 4> ArrayIndexStarts;
1510   {
1511     CallOperator = LSI->CallOperator;
1512     Class = LSI->Lambda;
1513     IntroducerRange = LSI->IntroducerRange;
1514     ExplicitParams = LSI->ExplicitParams;
1515     ExplicitResultType = !LSI->HasImplicitReturnType;
1516     LambdaCleanup = LSI->Cleanup;
1517     ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
1518     
1519     CallOperator->setLexicalDeclContext(Class);
1520     Decl *TemplateOrNonTemplateCallOperatorDecl = 
1521         CallOperator->getDescribedFunctionTemplate()  
1522         ? CallOperator->getDescribedFunctionTemplate() 
1523         : cast<Decl>(CallOperator);
1524
1525     TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
1526     Class->addDecl(TemplateOrNonTemplateCallOperatorDecl);
1527
1528     PopExpressionEvaluationContext();
1529
1530     // Translate captures.
1531     auto CurField = Class->field_begin();
1532     for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I, ++CurField) {
1533       LambdaScopeInfo::Capture From = LSI->Captures[I];
1534       assert(!From.isBlockCapture() && "Cannot capture __block variables");
1535       bool IsImplicit = I >= LSI->NumExplicitCaptures;
1536
1537       // Handle 'this' capture.
1538       if (From.isThisCapture()) {
1539         Captures.push_back(
1540             LambdaCapture(From.getLocation(), IsImplicit,
1541                           From.isCopyCapture() ? LCK_StarThis : LCK_This));
1542         CaptureInits.push_back(From.getInitExpr());
1543         ArrayIndexStarts.push_back(ArrayIndexVars.size());
1544         continue;
1545       }
1546       if (From.isVLATypeCapture()) {
1547         Captures.push_back(
1548             LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType));
1549         CaptureInits.push_back(nullptr);
1550         ArrayIndexStarts.push_back(ArrayIndexVars.size());
1551         continue;
1552       }
1553
1554       VarDecl *Var = From.getVariable();
1555       LambdaCaptureKind Kind = From.isCopyCapture() ? LCK_ByCopy : LCK_ByRef;
1556       Captures.push_back(LambdaCapture(From.getLocation(), IsImplicit, Kind,
1557                                        Var, From.getEllipsisLoc()));
1558       Expr *Init = From.getInitExpr();
1559       if (!Init) {
1560         auto InitResult = performLambdaVarCaptureInitialization(
1561             *this, From, *CurField, ArrayIndexVars, ArrayIndexStarts);
1562         if (InitResult.isInvalid())
1563           return ExprError();
1564         Init = InitResult.get();
1565       } else {
1566         ArrayIndexStarts.push_back(ArrayIndexVars.size());
1567       }
1568       CaptureInits.push_back(Init);
1569     }
1570
1571     // C++11 [expr.prim.lambda]p6:
1572     //   The closure type for a lambda-expression with no lambda-capture
1573     //   has a public non-virtual non-explicit const conversion function
1574     //   to pointer to function having the same parameter and return
1575     //   types as the closure type's function call operator.
1576     if (Captures.empty() && CaptureDefault == LCD_None)
1577       addFunctionPointerConversion(*this, IntroducerRange, Class,
1578                                    CallOperator);
1579
1580     // Objective-C++:
1581     //   The closure type for a lambda-expression has a public non-virtual
1582     //   non-explicit const conversion function to a block pointer having the
1583     //   same parameter and return types as the closure type's function call
1584     //   operator.
1585     // FIXME: Fix generic lambda to block conversions.
1586     if (getLangOpts().Blocks && getLangOpts().ObjC1 && 
1587                                               !Class->isGenericLambda())
1588       addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
1589     
1590     // Finalize the lambda class.
1591     SmallVector<Decl*, 4> Fields(Class->fields());
1592     ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
1593                 SourceLocation(), nullptr);
1594     CheckCompletedCXXClass(Class);
1595   }
1596
1597   Cleanup.mergeFrom(LambdaCleanup);
1598
1599   LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange, 
1600                                           CaptureDefault, CaptureDefaultLoc,
1601                                           Captures, 
1602                                           ExplicitParams, ExplicitResultType,
1603                                           CaptureInits, ArrayIndexVars, 
1604                                           ArrayIndexStarts, EndLoc,
1605                                           ContainsUnexpandedParameterPack);
1606
1607   if (!CurContext->isDependentContext()) {
1608     switch (ExprEvalContexts.back().Context) {
1609     // C++11 [expr.prim.lambda]p2:
1610     //   A lambda-expression shall not appear in an unevaluated operand
1611     //   (Clause 5).
1612     case Unevaluated:
1613     case UnevaluatedAbstract:
1614     // C++1y [expr.const]p2:
1615     //   A conditional-expression e is a core constant expression unless the
1616     //   evaluation of e, following the rules of the abstract machine, would
1617     //   evaluate [...] a lambda-expression.
1618     //
1619     // This is technically incorrect, there are some constant evaluated contexts
1620     // where this should be allowed.  We should probably fix this when DR1607 is
1621     // ratified, it lays out the exact set of conditions where we shouldn't
1622     // allow a lambda-expression.
1623     case ConstantEvaluated:
1624       // We don't actually diagnose this case immediately, because we
1625       // could be within a context where we might find out later that
1626       // the expression is potentially evaluated (e.g., for typeid).
1627       ExprEvalContexts.back().Lambdas.push_back(Lambda);
1628       break;
1629
1630     case DiscardedStatement:
1631     case PotentiallyEvaluated:
1632     case PotentiallyEvaluatedIfUsed:
1633       break;
1634     }
1635   }
1636
1637   return MaybeBindToTemporary(Lambda);
1638 }
1639
1640 ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
1641                                                SourceLocation ConvLocation,
1642                                                CXXConversionDecl *Conv,
1643                                                Expr *Src) {
1644   // Make sure that the lambda call operator is marked used.
1645   CXXRecordDecl *Lambda = Conv->getParent();
1646   CXXMethodDecl *CallOperator 
1647     = cast<CXXMethodDecl>(
1648         Lambda->lookup(
1649           Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
1650   CallOperator->setReferenced();
1651   CallOperator->markUsed(Context);
1652
1653   ExprResult Init = PerformCopyInitialization(
1654                       InitializedEntity::InitializeBlock(ConvLocation, 
1655                                                          Src->getType(), 
1656                                                          /*NRVO=*/false),
1657                       CurrentLocation, Src);
1658   if (!Init.isInvalid())
1659     Init = ActOnFinishFullExpr(Init.get());
1660   
1661   if (Init.isInvalid())
1662     return ExprError();
1663   
1664   // Create the new block to be returned.
1665   BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
1666
1667   // Set the type information.
1668   Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
1669   Block->setIsVariadic(CallOperator->isVariadic());
1670   Block->setBlockMissingReturnType(false);
1671
1672   // Add parameters.
1673   SmallVector<ParmVarDecl *, 4> BlockParams;
1674   for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1675     ParmVarDecl *From = CallOperator->getParamDecl(I);
1676     BlockParams.push_back(ParmVarDecl::Create(Context, Block,
1677                                               From->getLocStart(),
1678                                               From->getLocation(),
1679                                               From->getIdentifier(),
1680                                               From->getType(),
1681                                               From->getTypeSourceInfo(),
1682                                               From->getStorageClass(),
1683                                               /*DefaultArg=*/nullptr));
1684   }
1685   Block->setParams(BlockParams);
1686
1687   Block->setIsConversionFromLambda(true);
1688
1689   // Add capture. The capture uses a fake variable, which doesn't correspond
1690   // to any actual memory location. However, the initializer copy-initializes
1691   // the lambda object.
1692   TypeSourceInfo *CapVarTSI =
1693       Context.getTrivialTypeSourceInfo(Src->getType());
1694   VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1695                                     ConvLocation, nullptr,
1696                                     Src->getType(), CapVarTSI,
1697                                     SC_None);
1698   BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
1699                              /*Nested=*/false, /*Copy=*/Init.get());
1700   Block->setCaptures(Context, Capture, /*CapturesCXXThis=*/false);
1701
1702   // Add a fake function body to the block. IR generation is responsible
1703   // for filling in the actual body, which cannot be expressed as an AST.
1704   Block->setBody(new (Context) CompoundStmt(ConvLocation));
1705
1706   // Create the block literal expression.
1707   Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1708   ExprCleanupObjects.push_back(Block);
1709   Cleanup.setExprNeedsCleanups(true);
1710
1711   return BuildBlock;
1712 }