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