blob: 0719f4156f3db5ea3c54ae47435f79bacb011274 [file] [log] [blame]
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001//===--- 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"
Faisal Vali2b391ab2013-09-26 19:54:12 +000014#include "clang/AST/ASTLambda.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "clang/AST/ExprCXX.h"
Reid Klecknerd8110b62013-09-10 20:14:30 +000016#include "clang/Basic/TargetInfo.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregor03dd13c2012-02-08 21:18:48 +000018#include "clang/Sema/Initialization.h"
19#include "clang/Sema/Lookup.h"
Douglas Gregor6f88e5e2012-02-21 04:17:39 +000020#include "clang/Sema/Scope.h"
Douglas Gregor03dd13c2012-02-08 21:18:48 +000021#include "clang/Sema/ScopeInfo.h"
22#include "clang/Sema/SemaInternal.h"
Faisal Valia17d19f2013-11-07 05:17:06 +000023#include "clang/Sema/SemaLambda.h"
Richard Smithba71c082013-05-16 06:20:58 +000024#include "TypeLocBuilder.h"
Douglas Gregor03dd13c2012-02-08 21:18:48 +000025using namespace clang;
26using namespace sema;
27
Faisal Valiab3d6462013-12-07 20:22:44 +000028/// \brief Examines the FunctionScopeInfo stack to determine the nearest
29/// enclosing lambda (to the current lambda) that is 'capture-ready' for
30/// the variable referenced in the current lambda (i.e. \p VarToCapture).
31/// If successful, returns the index into Sema's FunctionScopeInfo stack
32/// of the capture-ready lambda's LambdaScopeInfo.
33///
34/// Climbs down the stack of lambdas (deepest nested lambda - i.e. current
35/// lambda - is on top) to determine the index of the nearest enclosing/outer
36/// lambda that is ready to capture the \p VarToCapture being referenced in
37/// the current lambda.
38/// As we climb down the stack, we want the index of the first such lambda -
39/// that is the lambda with the highest index that is 'capture-ready'.
40///
41/// A lambda 'L' is capture-ready for 'V' (var or this) if:
42/// - its enclosing context is non-dependent
43/// - and if the chain of lambdas between L and the lambda in which
44/// V is potentially used (i.e. the lambda at the top of the scope info
45/// stack), can all capture or have already captured V.
46/// If \p VarToCapture is 'null' then we are trying to capture 'this'.
47///
48/// Note that a lambda that is deemed 'capture-ready' still needs to be checked
49/// for whether it is 'capture-capable' (see
50/// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly
51/// capture.
52///
53/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
54/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
55/// is at the top of the stack and has the highest index.
56/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
57///
58/// \returns An Optional<unsigned> Index that if evaluates to 'true' contains
59/// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda
60/// which is capture-ready. If the return value evaluates to 'false' then
61/// no lambda is capture-ready for \p VarToCapture.
62
63static inline Optional<unsigned>
64getStackIndexOfNearestEnclosingCaptureReadyLambda(
65 ArrayRef<const clang::sema::FunctionScopeInfo *> FunctionScopes,
66 VarDecl *VarToCapture) {
67 // Label failure to capture.
68 const Optional<unsigned> NoLambdaIsCaptureReady;
69
70 assert(
71 isa<clang::sema::LambdaScopeInfo>(
72 FunctionScopes[FunctionScopes.size() - 1]) &&
73 "The function on the top of sema's function-info stack must be a lambda");
Faisal Valia17d19f2013-11-07 05:17:06 +000074
Faisal Valiab3d6462013-12-07 20:22:44 +000075 // If VarToCapture is null, we are attempting to capture 'this'.
76 const bool IsCapturingThis = !VarToCapture;
Faisal Valia17d19f2013-11-07 05:17:06 +000077 const bool IsCapturingVariable = !IsCapturingThis;
Faisal Valiab3d6462013-12-07 20:22:44 +000078
79 // Start with the current lambda at the top of the stack (highest index).
Faisal Valia17d19f2013-11-07 05:17:06 +000080 unsigned CurScopeIndex = FunctionScopes.size() - 1;
Faisal Valiab3d6462013-12-07 20:22:44 +000081 DeclContext *EnclosingDC =
82 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator;
83
84 do {
85 const clang::sema::LambdaScopeInfo *LSI =
86 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]);
87 // IF we have climbed down to an intervening enclosing lambda that contains
88 // the variable declaration - it obviously can/must not capture the
Faisal Valia17d19f2013-11-07 05:17:06 +000089 // variable.
Faisal Valiab3d6462013-12-07 20:22:44 +000090 // Since its enclosing DC is dependent, all the lambdas between it and the
91 // innermost nested lambda are dependent (otherwise we wouldn't have
92 // arrived here) - so we don't yet have a lambda that can capture the
93 // variable.
94 if (IsCapturingVariable &&
95 VarToCapture->getDeclContext()->Equals(EnclosingDC))
96 return NoLambdaIsCaptureReady;
97
98 // For an enclosing lambda to be capture ready for an entity, all
99 // intervening lambda's have to be able to capture that entity. If even
100 // one of the intervening lambda's is not capable of capturing the entity
101 // then no enclosing lambda can ever capture that entity.
102 // For e.g.
103 // const int x = 10;
104 // [=](auto a) { #1
105 // [](auto b) { #2 <-- an intervening lambda that can never capture 'x'
106 // [=](auto c) { #3
107 // f(x, c); <-- can not lead to x's speculative capture by #1 or #2
108 // }; }; };
Faisal Valia17d19f2013-11-07 05:17:06 +0000109 // If they do not have a default implicit capture, check to see
110 // if the entity has already been explicitly captured.
Faisal Valiab3d6462013-12-07 20:22:44 +0000111 // If even a single dependent enclosing lambda lacks the capability
112 // to ever capture this variable, there is no further enclosing
Faisal Valia17d19f2013-11-07 05:17:06 +0000113 // non-dependent lambda that can capture this variable.
114 if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) {
Faisal Valiab3d6462013-12-07 20:22:44 +0000115 if (IsCapturingVariable && !LSI->isCaptured(VarToCapture))
116 return NoLambdaIsCaptureReady;
Faisal Valia17d19f2013-11-07 05:17:06 +0000117 if (IsCapturingThis && !LSI->isCXXThisCaptured())
Faisal Valiab3d6462013-12-07 20:22:44 +0000118 return NoLambdaIsCaptureReady;
Faisal Valia17d19f2013-11-07 05:17:06 +0000119 }
120 EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC);
Faisal Valiab3d6462013-12-07 20:22:44 +0000121
122 assert(CurScopeIndex);
Faisal Valia17d19f2013-11-07 05:17:06 +0000123 --CurScopeIndex;
Faisal Valiab3d6462013-12-07 20:22:44 +0000124 } while (!EnclosingDC->isTranslationUnit() &&
125 EnclosingDC->isDependentContext() &&
126 isLambdaCallOperator(EnclosingDC));
Faisal Valia17d19f2013-11-07 05:17:06 +0000127
Faisal Valiab3d6462013-12-07 20:22:44 +0000128 assert(CurScopeIndex < (FunctionScopes.size() - 1));
129 // If the enclosingDC is not dependent, then the immediately nested lambda
130 // (one index above) is capture-ready.
131 if (!EnclosingDC->isDependentContext())
132 return CurScopeIndex + 1;
133 return NoLambdaIsCaptureReady;
134}
135
136/// \brief Examines the FunctionScopeInfo stack to determine the nearest
137/// enclosing lambda (to the current lambda) that is 'capture-capable' for
138/// the variable referenced in the current lambda (i.e. \p VarToCapture).
139/// If successful, returns the index into Sema's FunctionScopeInfo stack
140/// of the capture-capable lambda's LambdaScopeInfo.
141///
142/// Given the current stack of lambdas being processed by Sema and
143/// the variable of interest, to identify the nearest enclosing lambda (to the
144/// current lambda at the top of the stack) that can truly capture
145/// a variable, it has to have the following two properties:
146/// a) 'capture-ready' - be the innermost lambda that is 'capture-ready':
147/// - climb down the stack (i.e. starting from the innermost and examining
148/// each outer lambda step by step) checking if each enclosing
149/// lambda can either implicitly or explicitly capture the variable.
150/// Record the first such lambda that is enclosed in a non-dependent
151/// context. If no such lambda currently exists return failure.
152/// b) 'capture-capable' - make sure the 'capture-ready' lambda can truly
153/// capture the variable by checking all its enclosing lambdas:
154/// - check if all outer lambdas enclosing the 'capture-ready' lambda
155/// identified above in 'a' can also capture the variable (this is done
156/// via tryCaptureVariable for variables and CheckCXXThisCapture for
157/// 'this' by passing in the index of the Lambda identified in step 'a')
158///
159/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
160/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
161/// is at the top of the stack.
162///
163/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
164///
165///
166/// \returns An Optional<unsigned> Index that if evaluates to 'true' contains
167/// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda
168/// which is capture-capable. If the return value evaluates to 'false' then
169/// no lambda is capture-capable for \p VarToCapture.
170
171Optional<unsigned> clang::getStackIndexOfNearestEnclosingCaptureCapableLambda(
172 ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes,
173 VarDecl *VarToCapture, Sema &S) {
174
175 const Optional<unsigned> FailDistance;
176
177 const Optional<unsigned> OptionalStackIndex =
178 getStackIndexOfNearestEnclosingCaptureReadyLambda(FunctionScopes,
179 VarToCapture);
180 if (!OptionalStackIndex)
181 return FailDistance;
182
183 const unsigned IndexOfCaptureReadyLambda = OptionalStackIndex.getValue();
184 assert(
185 ((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) ||
186 (S.getCurGenericLambda() && S.getCurGenericLambda()->ImpCaptureStyle !=
187 sema::LambdaScopeInfo::ImpCap_None)) &&
188 "The capture ready lambda for a potential capture can only be the "
189 "current lambda if it is a generic lambda with an implicit capture");
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;
Faisal Valia17d19f2013-11-07 05:17:06 +0000196 const bool IsCapturingVariable = !IsCapturingThis;
197
198 if (IsCapturingVariable) {
Faisal Valiab3d6462013-12-07 20:22:44 +0000199 // 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.
Faisal Valia17d19f2013-11-07 05:17:06 +0000202 QualType CaptureType, DeclRefType;
Faisal Valiab3d6462013-12-07 20:22:44 +0000203 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 FailDistance;
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 FailDistance;
223 }
224 return IndexOfCaptureReadyLambda;
Faisal Valia17d19f2013-11-07 05:17:06 +0000225}
Faisal Valic1a6dc42013-10-23 16:10:50 +0000226
227static inline TemplateParameterList *
228getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) {
229 if (LSI->GLTemplateParameterList)
230 return LSI->GLTemplateParameterList;
231
232 if (LSI->AutoTemplateParams.size()) {
233 SourceRange IntroRange = LSI->IntroducerRange;
234 SourceLocation LAngleLoc = IntroRange.getBegin();
235 SourceLocation RAngleLoc = IntroRange.getEnd();
236 LSI->GLTemplateParameterList = TemplateParameterList::Create(
Faisal Valiab3d6462013-12-07 20:22:44 +0000237 SemaRef.Context,
238 /*Template kw loc*/ SourceLocation(), LAngleLoc,
239 (NamedDecl **)LSI->AutoTemplateParams.data(),
240 LSI->AutoTemplateParams.size(), RAngleLoc);
Faisal Valic1a6dc42013-10-23 16:10:50 +0000241 }
242 return LSI->GLTemplateParameterList;
243}
244
Douglas Gregor680e9e02012-02-21 19:11:17 +0000245CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
Eli Friedmand564afb2012-09-19 01:18:11 +0000246 TypeSourceInfo *Info,
Faisal Valic1a6dc42013-10-23 16:10:50 +0000247 bool KnownDependent,
248 LambdaCaptureDefault CaptureDefault) {
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000249 DeclContext *DC = CurContext;
250 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
251 DC = DC->getParent();
Faisal Valic1a6dc42013-10-23 16:10:50 +0000252 bool IsGenericLambda = getGenericLambdaTemplateParameterList(getCurLambda(),
253 *this);
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000254 // Start constructing the lambda class.
Eli Friedmand564afb2012-09-19 01:18:11 +0000255 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info,
Douglas Gregor680e9e02012-02-21 19:11:17 +0000256 IntroducerRange.getBegin(),
Faisal Valic1a6dc42013-10-23 16:10:50 +0000257 KnownDependent,
258 IsGenericLambda,
259 CaptureDefault);
Douglas Gregor43c3f282012-02-20 20:47:06 +0000260 DC->addDecl(Class);
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000261
262 return Class;
263}
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000264
Douglas Gregorb61e8092012-04-04 17:40:10 +0000265/// \brief Determine whether the given context is or is enclosed in an inline
266/// function.
267static bool isInInlineFunction(const DeclContext *DC) {
268 while (!DC->isFileContext()) {
269 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
270 if (FD->isInlined())
271 return true;
272
273 DC = DC->getLexicalParent();
274 }
275
276 return false;
277}
278
Eli Friedman7e346a82013-07-01 20:22:57 +0000279MangleNumberingContext *
Eli Friedman3b7d46c2013-07-10 00:30:46 +0000280Sema::getCurrentMangleNumberContext(const DeclContext *DC,
Eli Friedman7e346a82013-07-01 20:22:57 +0000281 Decl *&ManglingContextDecl) {
282 // Compute the context for allocating mangling numbers in the current
283 // expression, if the ABI requires them.
284 ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
285
286 enum ContextKind {
287 Normal,
288 DefaultArgument,
289 DataMember,
290 StaticDataMember
291 } Kind = Normal;
292
293 // Default arguments of member function parameters that appear in a class
294 // definition, as well as the initializers of data members, receive special
295 // treatment. Identify them.
296 if (ManglingContextDecl) {
297 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
298 if (const DeclContext *LexicalDC
299 = Param->getDeclContext()->getLexicalParent())
300 if (LexicalDC->isRecord())
301 Kind = DefaultArgument;
302 } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
303 if (Var->getDeclContext()->isRecord())
304 Kind = StaticDataMember;
305 } else if (isa<FieldDecl>(ManglingContextDecl)) {
306 Kind = DataMember;
307 }
308 }
309
310 // Itanium ABI [5.1.7]:
311 // In the following contexts [...] the one-definition rule requires closure
312 // types in different translation units to "correspond":
313 bool IsInNonspecializedTemplate =
314 !ActiveTemplateInstantiations.empty() || CurContext->isDependentContext();
315 switch (Kind) {
316 case Normal:
317 // -- the bodies of non-exported nonspecialized template functions
318 // -- the bodies of inline functions
319 if ((IsInNonspecializedTemplate &&
320 !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
321 isInInlineFunction(CurContext)) {
322 ManglingContextDecl = 0;
323 return &Context.getManglingNumberContext(DC);
324 }
325
326 ManglingContextDecl = 0;
327 return 0;
328
329 case StaticDataMember:
330 // -- the initializers of nonspecialized static members of template classes
331 if (!IsInNonspecializedTemplate) {
332 ManglingContextDecl = 0;
333 return 0;
334 }
335 // Fall through to get the current context.
336
337 case DataMember:
338 // -- the in-class initializers of class members
339 case DefaultArgument:
340 // -- default arguments appearing in class definitions
Reid Klecknerd8110b62013-09-10 20:14:30 +0000341 return &ExprEvalContexts.back().getMangleNumberingContext(Context);
Eli Friedman7e346a82013-07-01 20:22:57 +0000342 }
Andy Gibbs456198d2013-07-02 16:01:56 +0000343
344 llvm_unreachable("unexpected context");
Eli Friedman7e346a82013-07-01 20:22:57 +0000345}
346
Reid Klecknerd8110b62013-09-10 20:14:30 +0000347MangleNumberingContext &
348Sema::ExpressionEvaluationContextRecord::getMangleNumberingContext(
349 ASTContext &Ctx) {
350 assert(ManglingContextDecl && "Need to have a context declaration");
351 if (!MangleNumbering)
352 MangleNumbering = Ctx.createMangleNumberingContext();
353 return *MangleNumbering;
354}
355
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000356CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
Richard Smith4db51c22013-09-25 05:02:54 +0000357 SourceRange IntroducerRange,
358 TypeSourceInfo *MethodTypeInfo,
359 SourceLocation EndLoc,
360 ArrayRef<ParmVarDecl *> Params) {
361 QualType MethodType = MethodTypeInfo->getType();
Faisal Vali2b391ab2013-09-26 19:54:12 +0000362 TemplateParameterList *TemplateParams =
363 getGenericLambdaTemplateParameterList(getCurLambda(), *this);
364 // If a lambda appears in a dependent context or is a generic lambda (has
365 // template parameters) and has an 'auto' return type, deduce it to a
366 // dependent type.
367 if (Class->isDependentContext() || TemplateParams) {
Richard Smith4db51c22013-09-25 05:02:54 +0000368 const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
369 QualType Result = FPT->getResultType();
370 if (Result->isUndeducedType()) {
371 Result = SubstAutoType(Result, Context.DependentTy);
372 MethodType = Context.getFunctionType(Result, FPT->getArgTypes(),
373 FPT->getExtProtoInfo());
374 }
375 }
376
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000377 // C++11 [expr.prim.lambda]p5:
378 // The closure type for a lambda-expression has a public inline function
379 // call operator (13.5.4) whose parameters and return type are described by
380 // the lambda-expression's parameter-declaration-clause and
381 // trailing-return-type respectively.
382 DeclarationName MethodName
383 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
384 DeclarationNameLoc MethodNameLoc;
385 MethodNameLoc.CXXOperatorName.BeginOpNameLoc
386 = IntroducerRange.getBegin().getRawEncoding();
387 MethodNameLoc.CXXOperatorName.EndOpNameLoc
388 = IntroducerRange.getEnd().getRawEncoding();
389 CXXMethodDecl *Method
390 = CXXMethodDecl::Create(Context, Class, EndLoc,
391 DeclarationNameInfo(MethodName,
392 IntroducerRange.getBegin(),
393 MethodNameLoc),
Richard Smith4db51c22013-09-25 05:02:54 +0000394 MethodType, MethodTypeInfo,
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000395 SC_None,
396 /*isInline=*/true,
397 /*isConstExpr=*/false,
398 EndLoc);
399 Method->setAccess(AS_public);
400
401 // Temporarily set the lexical declaration context to the current
402 // context, so that the Scope stack matches the lexical nesting.
Douglas Gregor43c3f282012-02-20 20:47:06 +0000403 Method->setLexicalDeclContext(CurContext);
Faisal Vali2b391ab2013-09-26 19:54:12 +0000404 // Create a function template if we have a template parameter list
405 FunctionTemplateDecl *const TemplateMethod = TemplateParams ?
406 FunctionTemplateDecl::Create(Context, Class,
407 Method->getLocation(), MethodName,
408 TemplateParams,
409 Method) : 0;
410 if (TemplateMethod) {
411 TemplateMethod->setLexicalDeclContext(CurContext);
412 TemplateMethod->setAccess(AS_public);
413 Method->setDescribedFunctionTemplate(TemplateMethod);
414 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000415
Douglas Gregoradb376e2012-02-14 22:28:59 +0000416 // Add parameters.
417 if (!Params.empty()) {
418 Method->setParams(Params);
419 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
420 const_cast<ParmVarDecl **>(Params.end()),
421 /*CheckParameterNames=*/false);
422
423 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
424 PEnd = Method->param_end();
425 P != PEnd; ++P)
426 (*P)->setOwningFunction(Method);
427 }
Richard Smith505df232012-07-22 23:45:10 +0000428
Eli Friedman7e346a82013-07-01 20:22:57 +0000429 Decl *ManglingContextDecl;
430 if (MangleNumberingContext *MCtx =
431 getCurrentMangleNumberContext(Class->getDeclContext(),
432 ManglingContextDecl)) {
433 unsigned ManglingNumber = MCtx->getManglingNumber(Method);
434 Class->setLambdaMangling(ManglingNumber, ManglingContextDecl);
Douglas Gregorb61e8092012-04-04 17:40:10 +0000435 }
436
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000437 return Method;
438}
439
Faisal Vali2b391ab2013-09-26 19:54:12 +0000440void Sema::buildLambdaScope(LambdaScopeInfo *LSI,
441 CXXMethodDecl *CallOperator,
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000442 SourceRange IntroducerRange,
443 LambdaCaptureDefault CaptureDefault,
James Dennettddd36ff2013-08-09 23:08:25 +0000444 SourceLocation CaptureDefaultLoc,
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000445 bool ExplicitParams,
446 bool ExplicitResultType,
447 bool Mutable) {
Faisal Vali2b391ab2013-09-26 19:54:12 +0000448 LSI->CallOperator = CallOperator;
Faisal Valic1a6dc42013-10-23 16:10:50 +0000449 CXXRecordDecl *LambdaClass = CallOperator->getParent();
450 LSI->Lambda = LambdaClass;
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000451 if (CaptureDefault == LCD_ByCopy)
452 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
453 else if (CaptureDefault == LCD_ByRef)
454 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
James Dennettddd36ff2013-08-09 23:08:25 +0000455 LSI->CaptureDefaultLoc = CaptureDefaultLoc;
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000456 LSI->IntroducerRange = IntroducerRange;
457 LSI->ExplicitParams = ExplicitParams;
458 LSI->Mutable = Mutable;
459
460 if (ExplicitResultType) {
461 LSI->ReturnType = CallOperator->getResultType();
Douglas Gregor621003e2012-02-14 21:20:44 +0000462
463 if (!LSI->ReturnType->isDependentType() &&
464 !LSI->ReturnType->isVoidType()) {
465 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
466 diag::err_lambda_incomplete_result)) {
467 // Do nothing.
Douglas Gregor621003e2012-02-14 21:20:44 +0000468 }
469 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000470 } else {
471 LSI->HasImplicitReturnType = true;
472 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000473}
474
475void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
476 LSI->finishedExplicitCaptures();
477}
478
Douglas Gregoradb376e2012-02-14 22:28:59 +0000479void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000480 // Introduce our parameters into the function scope
481 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
482 p < NumParams; ++p) {
483 ParmVarDecl *Param = CallOperator->getParamDecl(p);
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000484
485 // If this has an identifier, add it to the scope stack.
486 if (CurScope && Param->getIdentifier()) {
487 CheckShadow(CurScope, Param);
488
489 PushOnScopeChains(Param, CurScope);
490 }
491 }
492}
493
John McCalle4c11cc2013-03-09 00:54:31 +0000494/// If this expression is an enumerator-like expression of some type
495/// T, return the type T; otherwise, return null.
496///
497/// Pointer comparisons on the result here should always work because
498/// it's derived from either the parent of an EnumConstantDecl
499/// (i.e. the definition) or the declaration returned by
500/// EnumType::getDecl() (i.e. the definition).
501static EnumDecl *findEnumForBlockReturn(Expr *E) {
502 // An expression is an enumerator-like expression of type T if,
503 // ignoring parens and parens-like expressions:
504 E = E->IgnoreParens();
Jordan Rosed39e5f12012-07-02 21:19:23 +0000505
John McCalle4c11cc2013-03-09 00:54:31 +0000506 // - it is an enumerator whose enum type is T or
507 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
508 if (EnumConstantDecl *D
509 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
510 return cast<EnumDecl>(D->getDeclContext());
511 }
512 return 0;
Jordan Rosed39e5f12012-07-02 21:19:23 +0000513 }
514
John McCalle4c11cc2013-03-09 00:54:31 +0000515 // - it is a comma expression whose RHS is an enumerator-like
516 // expression of type T or
517 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
518 if (BO->getOpcode() == BO_Comma)
519 return findEnumForBlockReturn(BO->getRHS());
520 return 0;
521 }
Jordan Rosed39e5f12012-07-02 21:19:23 +0000522
John McCalle4c11cc2013-03-09 00:54:31 +0000523 // - it is a statement-expression whose value expression is an
524 // enumerator-like expression of type T or
525 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
526 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
527 return findEnumForBlockReturn(last);
528 return 0;
529 }
530
531 // - it is a ternary conditional operator (not the GNU ?:
532 // extension) whose second and third operands are
533 // enumerator-like expressions of type T or
534 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
535 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
536 if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
537 return ED;
538 return 0;
539 }
540
541 // (implicitly:)
542 // - it is an implicit integral conversion applied to an
543 // enumerator-like expression of type T or
544 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall1b4259b2013-05-08 03:34:22 +0000545 // We can sometimes see integral conversions in valid
546 // enumerator-like expressions.
John McCalle4c11cc2013-03-09 00:54:31 +0000547 if (ICE->getCastKind() == CK_IntegralCast)
548 return findEnumForBlockReturn(ICE->getSubExpr());
John McCall1b4259b2013-05-08 03:34:22 +0000549
550 // Otherwise, just rely on the type.
John McCalle4c11cc2013-03-09 00:54:31 +0000551 }
552
553 // - it is an expression of that formal enum type.
554 if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
555 return ET->getDecl();
556 }
557
558 // Otherwise, nope.
559 return 0;
560}
561
562/// Attempt to find a type T for which the returned expression of the
563/// given statement is an enumerator-like expression of that type.
564static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
565 if (Expr *retValue = ret->getRetValue())
566 return findEnumForBlockReturn(retValue);
567 return 0;
568}
569
570/// Attempt to find a common type T for which all of the returned
571/// expressions in a block are enumerator-like expressions of that
572/// type.
573static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
574 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
575
576 // Try to find one for the first return.
577 EnumDecl *ED = findEnumForBlockReturn(*i);
578 if (!ED) return 0;
579
580 // Check that the rest of the returns have the same enum.
581 for (++i; i != e; ++i) {
582 if (findEnumForBlockReturn(*i) != ED)
583 return 0;
584 }
585
586 // Never infer an anonymous enum type.
587 if (!ED->hasNameForLinkage()) return 0;
588
589 return ED;
590}
591
592/// Adjust the given return statements so that they formally return
593/// the given type. It should require, at most, an IntegralCast.
594static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
595 QualType returnType) {
596 for (ArrayRef<ReturnStmt*>::iterator
597 i = returns.begin(), e = returns.end(); i != e; ++i) {
598 ReturnStmt *ret = *i;
599 Expr *retValue = ret->getRetValue();
600 if (S.Context.hasSameType(retValue->getType(), returnType))
601 continue;
602
603 // Right now we only support integral fixup casts.
604 assert(returnType->isIntegralOrUnscopedEnumerationType());
605 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
606
607 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
608
609 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
610 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast,
611 E, /*base path*/ 0, VK_RValue);
612 if (cleanups) {
613 cleanups->setSubExpr(E);
614 } else {
615 ret->setRetValue(E);
Jordan Rosed39e5f12012-07-02 21:19:23 +0000616 }
617 }
Jordan Rosed39e5f12012-07-02 21:19:23 +0000618}
619
620void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
Manuel Klimek2fdbea22013-08-22 12:12:24 +0000621 assert(CSI.HasImplicitReturnType);
Faisal Vali2b391ab2013-09-26 19:54:12 +0000622 // If it was ever a placeholder, it had to been deduced to DependentTy.
623 assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
Jordan Rosed39e5f12012-07-02 21:19:23 +0000624
John McCalle4c11cc2013-03-09 00:54:31 +0000625 // C++ Core Issue #975, proposed resolution:
626 // If a lambda-expression does not include a trailing-return-type,
627 // it is as if the trailing-return-type denotes the following type:
628 // - if there are no return statements in the compound-statement,
629 // or all return statements return either an expression of type
630 // void or no expression or braced-init-list, the type void;
631 // - otherwise, if all return statements return an expression
632 // and the types of the returned expressions after
633 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
634 // array-to-pointer conversion (4.2 [conv.array]), and
635 // function-to-pointer conversion (4.3 [conv.func]) are the
636 // same, that common type;
637 // - otherwise, the program is ill-formed.
638 //
639 // In addition, in blocks in non-C++ modes, if all of the return
640 // statements are enumerator-like expressions of some type T, where
641 // T has a name for linkage, then we infer the return type of the
642 // block to be that type.
643
Jordan Rosed39e5f12012-07-02 21:19:23 +0000644 // First case: no return statements, implicit void return type.
645 ASTContext &Ctx = getASTContext();
646 if (CSI.Returns.empty()) {
647 // It's possible there were simply no /valid/ return statements.
648 // In this case, the first one we found may have at least given us a type.
649 if (CSI.ReturnType.isNull())
650 CSI.ReturnType = Ctx.VoidTy;
651 return;
652 }
653
654 // Second case: at least one return statement has dependent type.
655 // Delay type checking until instantiation.
656 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
Manuel Klimek2fdbea22013-08-22 12:12:24 +0000657 if (CSI.ReturnType->isDependentType())
Jordan Rosed39e5f12012-07-02 21:19:23 +0000658 return;
659
John McCalle4c11cc2013-03-09 00:54:31 +0000660 // Try to apply the enum-fuzz rule.
661 if (!getLangOpts().CPlusPlus) {
662 assert(isa<BlockScopeInfo>(CSI));
663 const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
664 if (ED) {
665 CSI.ReturnType = Context.getTypeDeclType(ED);
666 adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
667 return;
668 }
669 }
670
Jordan Rosed39e5f12012-07-02 21:19:23 +0000671 // Third case: only one return statement. Don't bother doing extra work!
672 SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
673 E = CSI.Returns.end();
674 if (I+1 == E)
675 return;
676
677 // General case: many return statements.
678 // Check that they all have compatible return types.
Jordan Rosed39e5f12012-07-02 21:19:23 +0000679
680 // We require the return types to strictly match here.
John McCalle4c11cc2013-03-09 00:54:31 +0000681 // Note that we've already done the required promotions as part of
682 // processing the return statement.
Jordan Rosed39e5f12012-07-02 21:19:23 +0000683 for (; I != E; ++I) {
684 const ReturnStmt *RS = *I;
685 const Expr *RetE = RS->getRetValue();
Jordan Rosed39e5f12012-07-02 21:19:23 +0000686
John McCalle4c11cc2013-03-09 00:54:31 +0000687 QualType ReturnType = (RetE ? RetE->getType() : Context.VoidTy);
688 if (Context.hasSameType(ReturnType, CSI.ReturnType))
689 continue;
Jordan Rosed39e5f12012-07-02 21:19:23 +0000690
John McCalle4c11cc2013-03-09 00:54:31 +0000691 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
692 // TODO: It's possible that the *first* return is the divergent one.
693 Diag(RS->getLocStart(),
694 diag::err_typecheck_missing_return_type_incompatible)
695 << ReturnType << CSI.ReturnType
696 << isa<LambdaScopeInfo>(CSI);
697 // Continue iterating so that we keep emitting diagnostics.
Jordan Rosed39e5f12012-07-02 21:19:23 +0000698 }
699}
700
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000701QualType Sema::performLambdaInitCaptureInitialization(SourceLocation Loc,
702 bool ByRef,
703 IdentifierInfo *Id,
704 Expr *&Init) {
705
706 // We do not need to distinguish between direct-list-initialization
707 // and copy-list-initialization here, because we will always deduce
708 // std::initializer_list<T>, and direct- and copy-list-initialization
709 // always behave the same for such a type.
710 // FIXME: We should model whether an '=' was present.
711 const bool IsDirectInit = isa<ParenListExpr>(Init) || isa<InitListExpr>(Init);
712
713 // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to
714 // deduce against.
Richard Smithba71c082013-05-16 06:20:58 +0000715 QualType DeductType = Context.getAutoDeductType();
716 TypeLocBuilder TLB;
717 TLB.pushTypeSpec(DeductType).setNameLoc(Loc);
718 if (ByRef) {
719 DeductType = BuildReferenceType(DeductType, true, Loc, Id);
720 assert(!DeductType.isNull() && "can't build reference to auto");
721 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
722 }
Eli Friedman7152fbe2013-06-07 20:31:48 +0000723 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
Richard Smithba71c082013-05-16 06:20:58 +0000724
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000725 // Are we a non-list direct initialization?
726 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
727
728 Expr *DeduceInit = Init;
729 // Initializer could be a C++ direct-initializer. Deduction only works if it
730 // contains exactly one expression.
731 if (CXXDirectInit) {
732 if (CXXDirectInit->getNumExprs() == 0) {
733 Diag(CXXDirectInit->getLocStart(), diag::err_init_capture_no_expression)
734 << DeclarationName(Id) << TSI->getType() << Loc;
735 return QualType();
736 } else if (CXXDirectInit->getNumExprs() > 1) {
737 Diag(CXXDirectInit->getExpr(1)->getLocStart(),
738 diag::err_init_capture_multiple_expressions)
739 << DeclarationName(Id) << TSI->getType() << Loc;
740 return QualType();
741 } else {
742 DeduceInit = CXXDirectInit->getExpr(0);
743 }
744 }
745
746 // Now deduce against the initialization expression and store the deduced
747 // type below.
748 QualType DeducedType;
749 if (DeduceAutoType(TSI, DeduceInit, DeducedType) == DAR_Failed) {
750 if (isa<InitListExpr>(Init))
751 Diag(Loc, diag::err_init_capture_deduction_failure_from_init_list)
752 << DeclarationName(Id)
753 << (DeduceInit->getType().isNull() ? TSI->getType()
754 : DeduceInit->getType())
755 << DeduceInit->getSourceRange();
756 else
757 Diag(Loc, diag::err_init_capture_deduction_failure)
758 << DeclarationName(Id) << TSI->getType()
759 << (DeduceInit->getType().isNull() ? TSI->getType()
760 : DeduceInit->getType())
761 << DeduceInit->getSourceRange();
762 }
763 if (DeducedType.isNull())
764 return QualType();
765
766 // Perform initialization analysis and ensure any implicit conversions
767 // (such as lvalue-to-rvalue) are enforced.
768 InitializedEntity Entity =
769 InitializedEntity::InitializeLambdaCapture(Id, DeducedType, Loc);
770 InitializationKind Kind =
771 IsDirectInit
772 ? (CXXDirectInit ? InitializationKind::CreateDirect(
773 Loc, Init->getLocStart(), Init->getLocEnd())
774 : InitializationKind::CreateDirectList(Loc))
775 : InitializationKind::CreateCopy(Loc, Init->getLocStart());
776
777 MultiExprArg Args = Init;
778 if (CXXDirectInit)
779 Args =
780 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
781 QualType DclT;
782 InitializationSequence InitSeq(*this, Entity, Kind, Args);
783 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
784
785 if (Result.isInvalid())
786 return QualType();
787 Init = Result.takeAs<Expr>();
788
789 // The init-capture initialization is a full-expression that must be
790 // processed as one before we enter the declcontext of the lambda's
791 // call-operator.
792 Result = ActOnFinishFullExpr(Init, Loc, /*DiscardedValue*/ false,
793 /*IsConstexpr*/ false,
794 /*IsLambdaInitCaptureInitalizer*/ true);
795 if (Result.isInvalid())
796 return QualType();
797
798 Init = Result.takeAs<Expr>();
799 return DeducedType;
800}
801
802VarDecl *Sema::createLambdaInitCaptureVarDecl(SourceLocation Loc,
803 QualType InitCaptureType, IdentifierInfo *Id, Expr *Init) {
804
805 TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType,
806 Loc);
Richard Smithbb13c9a2013-09-28 04:02:39 +0000807 // Create a dummy variable representing the init-capture. This is not actually
808 // used as a variable, and only exists as a way to name and refer to the
809 // init-capture.
810 // FIXME: Pass in separate source locations for '&' and identifier.
Richard Smith75e3f692013-09-28 04:31:26 +0000811 VarDecl *NewVD = VarDecl::Create(Context, CurContext, Loc,
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000812 Loc, Id, InitCaptureType, TSI, SC_Auto);
Richard Smithbb13c9a2013-09-28 04:02:39 +0000813 NewVD->setInitCapture(true);
814 NewVD->setReferenced(true);
815 NewVD->markUsed(Context);
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000816 NewVD->setInit(Init);
Richard Smithbb13c9a2013-09-28 04:02:39 +0000817 return NewVD;
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000818
Richard Smithbb13c9a2013-09-28 04:02:39 +0000819}
Richard Smithba71c082013-05-16 06:20:58 +0000820
Richard Smithbb13c9a2013-09-28 04:02:39 +0000821FieldDecl *Sema::buildInitCaptureField(LambdaScopeInfo *LSI, VarDecl *Var) {
822 FieldDecl *Field = FieldDecl::Create(
823 Context, LSI->Lambda, Var->getLocation(), Var->getLocation(),
824 0, Var->getType(), Var->getTypeSourceInfo(), 0, false, ICIS_NoInit);
825 Field->setImplicit(true);
826 Field->setAccess(AS_private);
827 LSI->Lambda->addDecl(Field);
Richard Smithba71c082013-05-16 06:20:58 +0000828
Richard Smithbb13c9a2013-09-28 04:02:39 +0000829 LSI->addCapture(Var, /*isBlock*/false, Var->getType()->isReferenceType(),
830 /*isNested*/false, Var->getLocation(), SourceLocation(),
831 Var->getType(), Var->getInit());
832 return Field;
Richard Smithba71c082013-05-16 06:20:58 +0000833}
834
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000835void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
Faisal Vali2b391ab2013-09-26 19:54:12 +0000836 Declarator &ParamInfo, Scope *CurScope) {
Douglas Gregor680e9e02012-02-21 19:11:17 +0000837 // Determine if we're within a context where we know that the lambda will
838 // be dependent, because there are template parameters in scope.
839 bool KnownDependent = false;
Faisal Vali2b391ab2013-09-26 19:54:12 +0000840 LambdaScopeInfo *const LSI = getCurLambda();
841 assert(LSI && "LambdaScopeInfo should be on stack!");
842 TemplateParameterList *TemplateParams =
843 getGenericLambdaTemplateParameterList(LSI, *this);
844
845 if (Scope *TmplScope = CurScope->getTemplateParamParent()) {
846 // Since we have our own TemplateParams, so check if an outer scope
847 // has template params, only then are we in a dependent scope.
848 if (TemplateParams) {
849 TmplScope = TmplScope->getParent();
850 TmplScope = TmplScope ? TmplScope->getTemplateParamParent() : 0;
851 }
852 if (TmplScope && !TmplScope->decl_empty())
Douglas Gregor680e9e02012-02-21 19:11:17 +0000853 KnownDependent = true;
Faisal Vali2b391ab2013-09-26 19:54:12 +0000854 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000855 // Determine the signature of the call operator.
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000856 TypeSourceInfo *MethodTyInfo;
857 bool ExplicitParams = true;
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000858 bool ExplicitResultType = true;
Richard Smith2589b9802012-07-25 03:56:55 +0000859 bool ContainsUnexpandedParameterPack = false;
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000860 SourceLocation EndLoc;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000861 SmallVector<ParmVarDecl *, 8> Params;
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000862 if (ParamInfo.getNumTypeObjects() == 0) {
863 // C++11 [expr.prim.lambda]p4:
864 // If a lambda-expression does not include a lambda-declarator, it is as
865 // if the lambda-declarator were ().
Reid Kleckner78af0702013-08-27 23:08:25 +0000866 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
867 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Richard Smith5e580292012-02-10 09:58:53 +0000868 EPI.HasTrailingReturn = true;
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000869 EPI.TypeQuals |= DeclSpec::TQ_const;
Richard Smith4db51c22013-09-25 05:02:54 +0000870 // C++1y [expr.prim.lambda]:
871 // The lambda return type is 'auto', which is replaced by the
872 // trailing-return type if provided and/or deduced from 'return'
873 // statements
874 // We don't do this before C++1y, because we don't support deduced return
875 // types there.
876 QualType DefaultTypeForNoTrailingReturn =
877 getLangOpts().CPlusPlus1y ? Context.getAutoDeductType()
878 : Context.DependentTy;
879 QualType MethodTy =
880 Context.getFunctionType(DefaultTypeForNoTrailingReturn, None, EPI);
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000881 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
882 ExplicitParams = false;
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000883 ExplicitResultType = false;
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000884 EndLoc = Intro.Range.getEnd();
885 } else {
886 assert(ParamInfo.isFunctionDeclarator() &&
887 "lambda-declarator is a function");
888 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
Richard Smith4db51c22013-09-25 05:02:54 +0000889
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000890 // C++11 [expr.prim.lambda]p5:
891 // This function call operator is declared const (9.3.1) if and only if
892 // the lambda-expression's parameter-declaration-clause is not followed
893 // by mutable. It is neither virtual nor declared volatile. [...]
894 if (!FTI.hasMutableQualifier())
895 FTI.TypeQuals |= DeclSpec::TQ_const;
Richard Smith4db51c22013-09-25 05:02:54 +0000896
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000897 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000898 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000899 EndLoc = ParamInfo.getSourceRange().getEnd();
Richard Smith4db51c22013-09-25 05:02:54 +0000900
901 ExplicitResultType = FTI.hasTrailingReturnType();
Manuel Klimek2fdbea22013-08-22 12:12:24 +0000902
Eli Friedman8f5e9832012-09-20 01:40:23 +0000903 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
904 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
905 // Empty arg list, don't push any params.
906 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
907 } else {
908 Params.reserve(FTI.NumArgs);
909 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
910 Params.push_back(cast<ParmVarDecl>(FTI.ArgInfo[i].Param));
911 }
Douglas Gregor7efd007c2012-06-15 16:59:29 +0000912
913 // Check for unexpanded parameter packs in the method type.
Richard Smith2589b9802012-07-25 03:56:55 +0000914 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
915 ContainsUnexpandedParameterPack = true;
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000916 }
Eli Friedmand564afb2012-09-19 01:18:11 +0000917
918 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
Faisal Valic1a6dc42013-10-23 16:10:50 +0000919 KnownDependent, Intro.Default);
Eli Friedmand564afb2012-09-19 01:18:11 +0000920
Douglas Gregor7efd007c2012-06-15 16:59:29 +0000921 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregoradb376e2012-02-14 22:28:59 +0000922 MethodTyInfo, EndLoc, Params);
Douglas Gregoradb376e2012-02-14 22:28:59 +0000923 if (ExplicitParams)
924 CheckCXXDefaultArguments(Method);
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000925
Bill Wendling44426052012-12-20 19:22:21 +0000926 // Attributes on the lambda apply to the method.
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000927 ProcessDeclAttributes(CurScope, Method, ParamInfo);
928
Douglas Gregor8c50e7c2012-02-09 00:47:04 +0000929 // Introduce the function call operator as the current declaration context.
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000930 PushDeclContext(CurScope, Method);
931
Faisal Vali2b391ab2013-09-26 19:54:12 +0000932 // Build the lambda scope.
933 buildLambdaScope(LSI, Method,
James Dennettddd36ff2013-08-09 23:08:25 +0000934 Intro.Range,
935 Intro.Default, Intro.DefaultLoc,
936 ExplicitParams,
Douglas Gregor0c46b2b2012-02-13 22:00:16 +0000937 ExplicitResultType,
David Blaikief5697e52012-08-10 00:55:35 +0000938 !Method->isConst());
Richard Smithba71c082013-05-16 06:20:58 +0000939
940 // Distinct capture names, for diagnostics.
941 llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
942
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000943 // Handle explicit captures.
Douglas Gregora1bffa22012-02-10 17:46:20 +0000944 SourceLocation PrevCaptureLoc
945 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Craig Topper2341c0d2013-07-04 03:08:24 +0000946 for (SmallVectorImpl<LambdaCapture>::const_iterator
947 C = Intro.Captures.begin(),
948 E = Intro.Captures.end();
949 C != E;
Douglas Gregora1bffa22012-02-10 17:46:20 +0000950 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000951 if (C->Kind == LCK_This) {
952 // C++11 [expr.prim.lambda]p8:
953 // An identifier or this shall not appear more than once in a
954 // lambda-capture.
955 if (LSI->isCXXThisCaptured()) {
956 Diag(C->Loc, diag::err_capture_more_than_once)
957 << "'this'"
Douglas Gregora1bffa22012-02-10 17:46:20 +0000958 << SourceRange(LSI->getCXXThisCapture().getLocation())
959 << FixItHint::CreateRemoval(
960 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000961 continue;
962 }
963
964 // C++11 [expr.prim.lambda]p8:
965 // If a lambda-capture includes a capture-default that is =, the
966 // lambda-capture shall not contain this [...].
967 if (Intro.Default == LCD_ByCopy) {
Douglas Gregora1bffa22012-02-10 17:46:20 +0000968 Diag(C->Loc, diag::err_this_capture_with_copy_default)
969 << FixItHint::CreateRemoval(
970 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregor03dd13c2012-02-08 21:18:48 +0000971 continue;
972 }
973
974 // C++11 [expr.prim.lambda]p12:
975 // If this is captured by a local lambda expression, its nearest
976 // enclosing function shall be a non-static member function.
977 QualType ThisCaptureType = getCurrentThisType();
978 if (ThisCaptureType.isNull()) {
979 Diag(C->Loc, diag::err_this_capture) << true;
980 continue;
981 }
982
983 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
984 continue;
985 }
986
Richard Smithba71c082013-05-16 06:20:58 +0000987 assert(C->Id && "missing identifier for capture");
988
Richard Smith21b3ab42013-05-09 21:36:41 +0000989 if (C->Init.isInvalid())
990 continue;
Richard Smithba71c082013-05-16 06:20:58 +0000991
Faisal Vali5fb7c3c2013-12-05 01:40:41 +0000992 VarDecl *Var = 0;
Richard Smithbb13c9a2013-09-28 04:02:39 +0000993 if (C->Init.isUsable()) {
Richard Smith5b013f52013-09-28 05:38:27 +0000994 Diag(C->Loc, getLangOpts().CPlusPlus1y
995 ? diag::warn_cxx11_compat_init_capture
996 : diag::ext_init_capture);
997
Richard Smithba71c082013-05-16 06:20:58 +0000998 if (C->Init.get()->containsUnexpandedParameterPack())
999 ContainsUnexpandedParameterPack = true;
Faisal Vali5fb7c3c2013-12-05 01:40:41 +00001000 // If the initializer expression is usable, but the InitCaptureType
1001 // is not, then an error has occurred - so ignore the capture for now.
1002 // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
1003 // FIXME: we should create the init capture variable and mark it invalid
1004 // in this case.
1005 if (C->InitCaptureType.get().isNull())
1006 continue;
1007 Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
1008 C->Id, C->Init.take());
Richard Smithba71c082013-05-16 06:20:58 +00001009 // C++1y [expr.prim.lambda]p11:
Richard Smithbb13c9a2013-09-28 04:02:39 +00001010 // An init-capture behaves as if it declares and explicitly
1011 // captures a variable [...] whose declarative region is the
1012 // lambda-expression's compound-statement
1013 if (Var)
1014 PushOnScopeChains(Var, CurScope, false);
1015 } else {
1016 // C++11 [expr.prim.lambda]p8:
1017 // If a lambda-capture includes a capture-default that is &, the
1018 // identifiers in the lambda-capture shall not be preceded by &.
1019 // If a lambda-capture includes a capture-default that is =, [...]
1020 // each identifier it contains shall be preceded by &.
1021 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
1022 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
1023 << FixItHint::CreateRemoval(
1024 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001025 continue;
Richard Smithbb13c9a2013-09-28 04:02:39 +00001026 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
1027 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
1028 << FixItHint::CreateRemoval(
1029 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1030 continue;
1031 }
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001032
Richard Smithbb13c9a2013-09-28 04:02:39 +00001033 // C++11 [expr.prim.lambda]p10:
1034 // The identifiers in a capture-list are looked up using the usual
1035 // rules for unqualified name lookup (3.4.1)
1036 DeclarationNameInfo Name(C->Id, C->Loc);
1037 LookupResult R(*this, Name, LookupOrdinaryName);
1038 LookupName(R, CurScope);
1039 if (R.isAmbiguous())
1040 continue;
1041 if (R.empty()) {
1042 // FIXME: Disable corrections that would add qualification?
1043 CXXScopeSpec ScopeSpec;
1044 DeclFilterCCC<VarDecl> Validator;
1045 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
1046 continue;
1047 }
1048
1049 Var = R.getAsSingle<VarDecl>();
1050 }
Richard Smithba71c082013-05-16 06:20:58 +00001051
1052 // C++11 [expr.prim.lambda]p8:
1053 // An identifier or this shall not appear more than once in a
1054 // lambda-capture.
1055 if (!CaptureNames.insert(C->Id)) {
1056 if (Var && LSI->isCaptured(Var)) {
1057 Diag(C->Loc, diag::err_capture_more_than_once)
1058 << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
1059 << FixItHint::CreateRemoval(
1060 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1061 } else
Richard Smithbb13c9a2013-09-28 04:02:39 +00001062 // Previous capture captured something different (one or both was
1063 // an init-cpature): no fixit.
Richard Smithba71c082013-05-16 06:20:58 +00001064 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
1065 continue;
1066 }
1067
1068 // C++11 [expr.prim.lambda]p10:
1069 // [...] each such lookup shall find a variable with automatic storage
1070 // duration declared in the reaching scope of the local lambda expression.
1071 // Note that the 'reaching scope' check happens in tryCaptureVariable().
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001072 if (!Var) {
1073 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
1074 continue;
1075 }
1076
Eli Friedmane979db12012-09-18 21:11:30 +00001077 // Ignore invalid decls; they'll just confuse the code later.
1078 if (Var->isInvalidDecl())
1079 continue;
1080
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001081 if (!Var->hasLocalStorage()) {
1082 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
1083 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
1084 continue;
1085 }
1086
Douglas Gregor3e308b12012-02-14 19:27:52 +00001087 // C++11 [expr.prim.lambda]p23:
1088 // A capture followed by an ellipsis is a pack expansion (14.5.3).
1089 SourceLocation EllipsisLoc;
1090 if (C->EllipsisLoc.isValid()) {
1091 if (Var->isParameterPack()) {
1092 EllipsisLoc = C->EllipsisLoc;
1093 } else {
1094 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1095 << SourceRange(C->Loc);
1096
1097 // Just ignore the ellipsis.
1098 }
1099 } else if (Var->isParameterPack()) {
Richard Smith2589b9802012-07-25 03:56:55 +00001100 ContainsUnexpandedParameterPack = true;
Douglas Gregor3e308b12012-02-14 19:27:52 +00001101 }
Richard Smithbb13c9a2013-09-28 04:02:39 +00001102
1103 if (C->Init.isUsable()) {
1104 buildInitCaptureField(LSI, Var);
1105 } else {
1106 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
1107 TryCapture_ExplicitByVal;
1108 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
1109 }
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001110 }
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00001111 finishLambdaExplicitCaptures(LSI);
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001112
Richard Smith2589b9802012-07-25 03:56:55 +00001113 LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
1114
Douglas Gregoradb376e2012-02-14 22:28:59 +00001115 // Add lambda parameters into scope.
1116 addLambdaParameters(Method, CurScope);
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001117
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00001118 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00001119 // cleanups from the enclosing full-expression.
1120 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001121}
1122
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00001123void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
1124 bool IsInstantiation) {
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001125 // Leave the expression-evaluation context.
1126 DiscardCleanupsInEvaluationContext();
1127 PopExpressionEvaluationContext();
1128
1129 // Leave the context of the lambda.
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00001130 if (!IsInstantiation)
1131 PopDeclContext();
Douglas Gregorab23d9a2012-02-09 01:28:42 +00001132
1133 // Finalize the lambda.
1134 LambdaScopeInfo *LSI = getCurLambda();
1135 CXXRecordDecl *Class = LSI->Lambda;
1136 Class->setInvalidDecl();
David Blaikie2d7c57e2012-04-30 02:36:29 +00001137 SmallVector<Decl*, 4> Fields;
1138 for (RecordDecl::field_iterator i = Class->field_begin(),
1139 e = Class->field_end(); i != e; ++i)
David Blaikie40ed2972012-06-06 20:45:41 +00001140 Fields.push_back(*i);
Douglas Gregorab23d9a2012-02-09 01:28:42 +00001141 ActOnFields(0, Class->getLocation(), Class, Fields,
1142 SourceLocation(), SourceLocation(), 0);
1143 CheckCompletedCXXClass(Class);
1144
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001145 PopFunctionScopeInfo();
1146}
1147
Douglas Gregor13f09b42012-02-15 22:00:51 +00001148/// \brief Add a lambda's conversion to function pointer, as described in
1149/// C++11 [expr.prim.lambda]p6.
1150static void addFunctionPointerConversion(Sema &S,
1151 SourceRange IntroducerRange,
1152 CXXRecordDecl *Class,
1153 CXXMethodDecl *CallOperator) {
Douglas Gregor355efbb2012-02-17 03:02:34 +00001154 // Add the conversion to function pointer.
Faisal Vali66605d42013-10-24 01:05:22 +00001155 const FunctionProtoType *CallOpProto =
1156 CallOperator->getType()->getAs<FunctionProtoType>();
1157 const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
1158 CallOpProto->getExtProtoInfo();
1159 QualType PtrToFunctionTy;
1160 QualType InvokerFunctionTy;
Douglas Gregor13f09b42012-02-15 22:00:51 +00001161 {
Faisal Vali66605d42013-10-24 01:05:22 +00001162 FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
Reid Kleckner78af0702013-08-27 23:08:25 +00001163 CallingConv CC = S.Context.getDefaultCallingConvention(
Faisal Vali66605d42013-10-24 01:05:22 +00001164 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
1165 InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
1166 InvokerExtInfo.TypeQuals = 0;
1167 assert(InvokerExtInfo.RefQualifier == RQ_None &&
1168 "Lambda's call operator should not have a reference qualifier");
1169 InvokerFunctionTy = S.Context.getFunctionType(CallOpProto->getResultType(),
1170 CallOpProto->getArgTypes(), InvokerExtInfo);
1171 PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
Douglas Gregor13f09b42012-02-15 22:00:51 +00001172 }
Reid Kleckner78af0702013-08-27 23:08:25 +00001173
Faisal Vali66605d42013-10-24 01:05:22 +00001174 // Create the type of the conversion function.
1175 FunctionProtoType::ExtProtoInfo ConvExtInfo(
1176 S.Context.getDefaultCallingConvention(
Reid Kleckner78af0702013-08-27 23:08:25 +00001177 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Faisal Vali66605d42013-10-24 01:05:22 +00001178 // The conversion function is always const.
1179 ConvExtInfo.TypeQuals = Qualifiers::Const;
1180 QualType ConvTy =
1181 S.Context.getFunctionType(PtrToFunctionTy, None, ConvExtInfo);
Reid Kleckner78af0702013-08-27 23:08:25 +00001182
Douglas Gregor13f09b42012-02-15 22:00:51 +00001183 SourceLocation Loc = IntroducerRange.getBegin();
Faisal Vali66605d42013-10-24 01:05:22 +00001184 DeclarationName ConversionName
Douglas Gregor13f09b42012-02-15 22:00:51 +00001185 = S.Context.DeclarationNames.getCXXConversionFunctionName(
Faisal Vali66605d42013-10-24 01:05:22 +00001186 S.Context.getCanonicalType(PtrToFunctionTy));
1187 DeclarationNameLoc ConvNameLoc;
1188 // Construct a TypeSourceInfo for the conversion function, and wire
1189 // all the parameters appropriately for the FunctionProtoTypeLoc
1190 // so that everything works during transformation/instantiation of
1191 // generic lambdas.
1192 // The main reason for wiring up the parameters of the conversion
1193 // function with that of the call operator is so that constructs
1194 // like the following work:
1195 // auto L = [](auto b) { <-- 1
1196 // return [](auto a) -> decltype(a) { <-- 2
1197 // return a;
1198 // };
1199 // };
1200 // int (*fp)(int) = L(5);
1201 // Because the trailing return type can contain DeclRefExprs that refer
1202 // to the original call operator's variables, we hijack the call
1203 // operators ParmVarDecls below.
1204 TypeSourceInfo *ConvNamePtrToFunctionTSI =
1205 S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
1206 ConvNameLoc.NamedType.TInfo = ConvNamePtrToFunctionTSI;
1207
1208 // The conversion function is a conversion to a pointer-to-function.
1209 TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
1210 FunctionProtoTypeLoc ConvTL =
1211 ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>();
1212 // Get the result of the conversion function which is a pointer-to-function.
1213 PointerTypeLoc PtrToFunctionTL =
1214 ConvTL.getResultLoc().getAs<PointerTypeLoc>();
1215 // Do the same for the TypeSourceInfo that is used to name the conversion
1216 // operator.
1217 PointerTypeLoc ConvNamePtrToFunctionTL =
1218 ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
1219
1220 // Get the underlying function types that the conversion function will
1221 // be converting to (should match the type of the call operator).
1222 FunctionProtoTypeLoc CallOpConvTL =
1223 PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1224 FunctionProtoTypeLoc CallOpConvNameTL =
1225 ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1226
1227 // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
1228 // These parameter's are essentially used to transform the name and
1229 // the type of the conversion operator. By using the same parameters
1230 // as the call operator's we don't have to fix any back references that
1231 // the trailing return type of the call operator's uses (such as
1232 // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
1233 // - we can simply use the return type of the call operator, and
1234 // everything should work.
1235 SmallVector<ParmVarDecl *, 4> InvokerParams;
1236 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1237 ParmVarDecl *From = CallOperator->getParamDecl(I);
1238
1239 InvokerParams.push_back(ParmVarDecl::Create(S.Context,
1240 // Temporarily add to the TU. This is set to the invoker below.
1241 S.Context.getTranslationUnitDecl(),
1242 From->getLocStart(),
1243 From->getLocation(),
1244 From->getIdentifier(),
1245 From->getType(),
1246 From->getTypeSourceInfo(),
1247 From->getStorageClass(),
1248 /*DefaultArg=*/0));
1249 CallOpConvTL.setArg(I, From);
1250 CallOpConvNameTL.setArg(I, From);
1251 }
1252
Douglas Gregor13f09b42012-02-15 22:00:51 +00001253 CXXConversionDecl *Conversion
1254 = CXXConversionDecl::Create(S.Context, Class, Loc,
Faisal Vali66605d42013-10-24 01:05:22 +00001255 DeclarationNameInfo(ConversionName,
1256 Loc, ConvNameLoc),
Douglas Gregor13f09b42012-02-15 22:00:51 +00001257 ConvTy,
Faisal Vali66605d42013-10-24 01:05:22 +00001258 ConvTSI,
Eli Friedman8f54e132013-06-13 19:39:48 +00001259 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregor13f09b42012-02-15 22:00:51 +00001260 /*isConstexpr=*/false,
1261 CallOperator->getBody()->getLocEnd());
1262 Conversion->setAccess(AS_public);
1263 Conversion->setImplicit(true);
Faisal Vali571df122013-09-29 08:45:24 +00001264
1265 if (Class->isGenericLambda()) {
1266 // Create a template version of the conversion operator, using the template
1267 // parameter list of the function call operator.
1268 FunctionTemplateDecl *TemplateCallOperator =
1269 CallOperator->getDescribedFunctionTemplate();
1270 FunctionTemplateDecl *ConversionTemplate =
1271 FunctionTemplateDecl::Create(S.Context, Class,
Faisal Vali66605d42013-10-24 01:05:22 +00001272 Loc, ConversionName,
Faisal Vali571df122013-09-29 08:45:24 +00001273 TemplateCallOperator->getTemplateParameters(),
1274 Conversion);
1275 ConversionTemplate->setAccess(AS_public);
1276 ConversionTemplate->setImplicit(true);
1277 Conversion->setDescribedFunctionTemplate(ConversionTemplate);
1278 Class->addDecl(ConversionTemplate);
1279 } else
1280 Class->addDecl(Conversion);
Faisal Vali2b391ab2013-09-26 19:54:12 +00001281 // Add a non-static member function that will be the result of
1282 // the conversion with a certain unique ID.
Faisal Vali66605d42013-10-24 01:05:22 +00001283 DeclarationName InvokerName = &S.Context.Idents.get(
1284 getLambdaStaticInvokerName());
Faisal Vali571df122013-09-29 08:45:24 +00001285 // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
1286 // we should get a prebuilt TrivialTypeSourceInfo from Context
1287 // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
1288 // then rewire the parameters accordingly, by hoisting up the InvokeParams
1289 // loop below and then use its Params to set Invoke->setParams(...) below.
1290 // This would avoid the 'const' qualifier of the calloperator from
1291 // contaminating the type of the invoker, which is currently adjusted
Faisal Vali66605d42013-10-24 01:05:22 +00001292 // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the
1293 // trailing return type of the invoker would require a visitor to rebuild
1294 // the trailing return type and adjusting all back DeclRefExpr's to refer
1295 // to the new static invoker parameters - not the call operator's.
Douglas Gregor355efbb2012-02-17 03:02:34 +00001296 CXXMethodDecl *Invoke
1297 = CXXMethodDecl::Create(S.Context, Class, Loc,
Faisal Vali66605d42013-10-24 01:05:22 +00001298 DeclarationNameInfo(InvokerName, Loc),
1299 InvokerFunctionTy,
1300 CallOperator->getTypeSourceInfo(),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001301 SC_Static, /*IsInline=*/true,
Douglas Gregor355efbb2012-02-17 03:02:34 +00001302 /*IsConstexpr=*/false,
1303 CallOperator->getBody()->getLocEnd());
Faisal Vali66605d42013-10-24 01:05:22 +00001304 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
1305 InvokerParams[I]->setOwningFunction(Invoke);
1306 Invoke->setParams(InvokerParams);
Douglas Gregor355efbb2012-02-17 03:02:34 +00001307 Invoke->setAccess(AS_private);
1308 Invoke->setImplicit(true);
Faisal Vali571df122013-09-29 08:45:24 +00001309 if (Class->isGenericLambda()) {
1310 FunctionTemplateDecl *TemplateCallOperator =
1311 CallOperator->getDescribedFunctionTemplate();
1312 FunctionTemplateDecl *StaticInvokerTemplate = FunctionTemplateDecl::Create(
Faisal Vali66605d42013-10-24 01:05:22 +00001313 S.Context, Class, Loc, InvokerName,
Faisal Vali571df122013-09-29 08:45:24 +00001314 TemplateCallOperator->getTemplateParameters(),
1315 Invoke);
1316 StaticInvokerTemplate->setAccess(AS_private);
1317 StaticInvokerTemplate->setImplicit(true);
1318 Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
1319 Class->addDecl(StaticInvokerTemplate);
1320 } else
1321 Class->addDecl(Invoke);
Douglas Gregor13f09b42012-02-15 22:00:51 +00001322}
1323
Douglas Gregor33e863c2012-02-15 22:08:38 +00001324/// \brief Add a lambda's conversion to block pointer.
1325static void addBlockPointerConversion(Sema &S,
1326 SourceRange IntroducerRange,
1327 CXXRecordDecl *Class,
1328 CXXMethodDecl *CallOperator) {
1329 const FunctionProtoType *Proto
1330 = CallOperator->getType()->getAs<FunctionProtoType>();
1331 QualType BlockPtrTy;
1332 {
1333 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
1334 ExtInfo.TypeQuals = 0;
Reid Kleckner896b32f2013-06-10 20:51:09 +00001335 QualType FunctionTy = S.Context.getFunctionType(
1336 Proto->getResultType(), Proto->getArgTypes(), ExtInfo);
Douglas Gregor33e863c2012-02-15 22:08:38 +00001337 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
1338 }
Reid Kleckner78af0702013-08-27 23:08:25 +00001339
1340 FunctionProtoType::ExtProtoInfo ExtInfo(S.Context.getDefaultCallingConvention(
1341 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Douglas Gregor33e863c2012-02-15 22:08:38 +00001342 ExtInfo.TypeQuals = Qualifiers::Const;
Dmitri Gribenko44ebbd52013-05-05 00:41:58 +00001343 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ExtInfo);
Douglas Gregor33e863c2012-02-15 22:08:38 +00001344
1345 SourceLocation Loc = IntroducerRange.getBegin();
1346 DeclarationName Name
1347 = S.Context.DeclarationNames.getCXXConversionFunctionName(
1348 S.Context.getCanonicalType(BlockPtrTy));
1349 DeclarationNameLoc NameLoc;
1350 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
1351 CXXConversionDecl *Conversion
1352 = CXXConversionDecl::Create(S.Context, Class, Loc,
1353 DeclarationNameInfo(Name, Loc, NameLoc),
1354 ConvTy,
1355 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
Eli Friedmanef102822013-06-13 20:56:27 +00001356 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregor33e863c2012-02-15 22:08:38 +00001357 /*isConstexpr=*/false,
1358 CallOperator->getBody()->getLocEnd());
1359 Conversion->setAccess(AS_public);
1360 Conversion->setImplicit(true);
1361 Class->addDecl(Conversion);
1362}
Douglas Gregor6f88e5e2012-02-21 04:17:39 +00001363
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00001364ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Douglas Gregor63798542012-02-20 19:44:39 +00001365 Scope *CurScope,
Douglas Gregor63798542012-02-20 19:44:39 +00001366 bool IsInstantiation) {
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001367 // Collect information from the lambda scope.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001368 SmallVector<LambdaExpr::Capture, 4> Captures;
1369 SmallVector<Expr *, 4> CaptureInits;
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001370 LambdaCaptureDefault CaptureDefault;
James Dennettddd36ff2013-08-09 23:08:25 +00001371 SourceLocation CaptureDefaultLoc;
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001372 CXXRecordDecl *Class;
Douglas Gregor12695102012-02-10 08:36:38 +00001373 CXXMethodDecl *CallOperator;
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001374 SourceRange IntroducerRange;
1375 bool ExplicitParams;
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00001376 bool ExplicitResultType;
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00001377 bool LambdaExprNeedsCleanups;
Richard Smith2589b9802012-07-25 03:56:55 +00001378 bool ContainsUnexpandedParameterPack;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001379 SmallVector<VarDecl *, 4> ArrayIndexVars;
1380 SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001381 {
1382 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregor12695102012-02-10 08:36:38 +00001383 CallOperator = LSI->CallOperator;
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001384 Class = LSI->Lambda;
1385 IntroducerRange = LSI->IntroducerRange;
1386 ExplicitParams = LSI->ExplicitParams;
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00001387 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00001388 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Richard Smith2589b9802012-07-25 03:56:55 +00001389 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
Douglas Gregor54fcea62012-02-13 16:35:30 +00001390 ArrayIndexVars.swap(LSI->ArrayIndexVars);
1391 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
1392
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001393 // Translate captures.
1394 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
1395 LambdaScopeInfo::Capture From = LSI->Captures[I];
1396 assert(!From.isBlockCapture() && "Cannot capture __block variables");
1397 bool IsImplicit = I >= LSI->NumExplicitCaptures;
1398
1399 // Handle 'this' capture.
1400 if (From.isThisCapture()) {
1401 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
1402 IsImplicit,
1403 LCK_This));
1404 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
1405 getCurrentThisType(),
1406 /*isImplicit=*/true));
1407 continue;
1408 }
1409
1410 VarDecl *Var = From.getVariable();
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001411 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
1412 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregor3e308b12012-02-14 19:27:52 +00001413 Kind, Var, From.getEllipsisLoc()));
Richard Smithba71c082013-05-16 06:20:58 +00001414 CaptureInits.push_back(From.getInitExpr());
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001415 }
1416
1417 switch (LSI->ImpCaptureStyle) {
1418 case CapturingScopeInfo::ImpCap_None:
1419 CaptureDefault = LCD_None;
1420 break;
1421
1422 case CapturingScopeInfo::ImpCap_LambdaByval:
1423 CaptureDefault = LCD_ByCopy;
1424 break;
1425
Tareq A. Siraj6dfa25a2013-04-16 19:37:38 +00001426 case CapturingScopeInfo::ImpCap_CapturedRegion:
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001427 case CapturingScopeInfo::ImpCap_LambdaByref:
1428 CaptureDefault = LCD_ByRef;
1429 break;
1430
1431 case CapturingScopeInfo::ImpCap_Block:
1432 llvm_unreachable("block capture in lambda");
1433 break;
1434 }
James Dennettddd36ff2013-08-09 23:08:25 +00001435 CaptureDefaultLoc = LSI->CaptureDefaultLoc;
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001436
Douglas Gregor73456262012-02-09 10:18:50 +00001437 // C++11 [expr.prim.lambda]p4:
1438 // If a lambda-expression does not include a
1439 // trailing-return-type, it is as if the trailing-return-type
1440 // denotes the following type:
Richard Smith4db51c22013-09-25 05:02:54 +00001441 //
1442 // Skip for C++1y return type deduction semantics which uses
1443 // different machinery.
1444 // FIXME: Refactor and Merge the return type deduction machinery.
Douglas Gregor73456262012-02-09 10:18:50 +00001445 // FIXME: Assumes current resolution to core issue 975.
Richard Smith4db51c22013-09-25 05:02:54 +00001446 if (LSI->HasImplicitReturnType && !getLangOpts().CPlusPlus1y) {
Jordan Rosed39e5f12012-07-02 21:19:23 +00001447 deduceClosureReturnType(*LSI);
1448
Douglas Gregor73456262012-02-09 10:18:50 +00001449 // - if there are no return statements in the
1450 // compound-statement, or all return statements return
1451 // either an expression of type void or no expression or
1452 // braced-init-list, the type void;
1453 if (LSI->ReturnType.isNull()) {
1454 LSI->ReturnType = Context.VoidTy;
Douglas Gregor73456262012-02-09 10:18:50 +00001455 }
1456
1457 // Create a function type with the inferred return type.
1458 const FunctionProtoType *Proto
1459 = CallOperator->getType()->getAs<FunctionProtoType>();
Reid Kleckner896b32f2013-06-10 20:51:09 +00001460 QualType FunctionTy = Context.getFunctionType(
1461 LSI->ReturnType, Proto->getArgTypes(), Proto->getExtProtoInfo());
Douglas Gregor73456262012-02-09 10:18:50 +00001462 CallOperator->setType(FunctionTy);
1463 }
Douglas Gregor1a22d282012-02-12 17:34:23 +00001464 // C++ [expr.prim.lambda]p7:
1465 // The lambda-expression's compound-statement yields the
1466 // function-body (8.4) of the function call operator [...].
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00001467 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor1a22d282012-02-12 17:34:23 +00001468 CallOperator->setLexicalDeclContext(Class);
Faisal Vali2b391ab2013-09-26 19:54:12 +00001469 Decl *TemplateOrNonTemplateCallOperatorDecl =
1470 CallOperator->getDescribedFunctionTemplate()
1471 ? CallOperator->getDescribedFunctionTemplate()
1472 : cast<Decl>(CallOperator);
1473
1474 TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
1475 Class->addDecl(TemplateOrNonTemplateCallOperatorDecl);
1476
Douglas Gregor5dbc14f2012-02-21 20:05:31 +00001477 PopExpressionEvaluationContext();
Douglas Gregor1a22d282012-02-12 17:34:23 +00001478
Douglas Gregor04bbab52012-02-10 16:13:20 +00001479 // C++11 [expr.prim.lambda]p6:
1480 // The closure type for a lambda-expression with no lambda-capture
1481 // has a public non-virtual non-explicit const conversion function
1482 // to pointer to function having the same parameter and return
1483 // types as the closure type's function call operator.
Douglas Gregor13f09b42012-02-15 22:00:51 +00001484 if (Captures.empty() && CaptureDefault == LCD_None)
1485 addFunctionPointerConversion(*this, IntroducerRange, Class,
1486 CallOperator);
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00001487
Douglas Gregor33e863c2012-02-15 22:08:38 +00001488 // Objective-C++:
1489 // The closure type for a lambda-expression has a public non-virtual
1490 // non-explicit const conversion function to a block pointer having the
1491 // same parameter and return types as the closure type's function call
1492 // operator.
Faisal Vali571df122013-09-29 08:45:24 +00001493 // FIXME: Fix generic lambda to block conversions.
1494 if (getLangOpts().Blocks && getLangOpts().ObjC1 &&
1495 !Class->isGenericLambda())
Douglas Gregor33e863c2012-02-15 22:08:38 +00001496 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
1497
Douglas Gregor04bbab52012-02-10 16:13:20 +00001498 // Finalize the lambda class.
David Blaikie2d7c57e2012-04-30 02:36:29 +00001499 SmallVector<Decl*, 4> Fields;
1500 for (RecordDecl::field_iterator i = Class->field_begin(),
1501 e = Class->field_end(); i != e; ++i)
David Blaikie40ed2972012-06-06 20:45:41 +00001502 Fields.push_back(*i);
Douglas Gregor04bbab52012-02-10 16:13:20 +00001503 ActOnFields(0, Class->getLocation(), Class, Fields,
1504 SourceLocation(), SourceLocation(), 0);
1505 CheckCompletedCXXClass(Class);
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001506 }
1507
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00001508 if (LambdaExprNeedsCleanups)
1509 ExprNeedsCleanups = true;
Douglas Gregor63798542012-02-20 19:44:39 +00001510
Douglas Gregor89625492012-02-09 08:14:43 +00001511 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
James Dennettddd36ff2013-08-09 23:08:25 +00001512 CaptureDefault, CaptureDefaultLoc,
1513 Captures,
Douglas Gregor0c46b2b2012-02-13 22:00:16 +00001514 ExplicitParams, ExplicitResultType,
1515 CaptureInits, ArrayIndexVars,
Richard Smith2589b9802012-07-25 03:56:55 +00001516 ArrayIndexStarts, Body->getLocEnd(),
1517 ContainsUnexpandedParameterPack);
David Majnemer9adc3612013-10-25 09:12:52 +00001518
Douglas Gregorb4328232012-02-14 00:00:48 +00001519 if (!CurContext->isDependentContext()) {
1520 switch (ExprEvalContexts.back().Context) {
David Majnemer9adc3612013-10-25 09:12:52 +00001521 // C++11 [expr.prim.lambda]p2:
1522 // A lambda-expression shall not appear in an unevaluated operand
1523 // (Clause 5).
Douglas Gregorb4328232012-02-14 00:00:48 +00001524 case Unevaluated:
John McCallf413f5e2013-05-03 00:10:13 +00001525 case UnevaluatedAbstract:
David Majnemer9adc3612013-10-25 09:12:52 +00001526 // C++1y [expr.const]p2:
1527 // A conditional-expression e is a core constant expression unless the
1528 // evaluation of e, following the rules of the abstract machine, would
1529 // evaluate [...] a lambda-expression.
David Majnemer2748da92013-11-05 08:01:18 +00001530 //
1531 // This is technically incorrect, there are some constant evaluated contexts
1532 // where this should be allowed. We should probably fix this when DR1607 is
1533 // ratified, it lays out the exact set of conditions where we shouldn't
1534 // allow a lambda-expression.
David Majnemer9adc3612013-10-25 09:12:52 +00001535 case ConstantEvaluated:
Douglas Gregorb4328232012-02-14 00:00:48 +00001536 // We don't actually diagnose this case immediately, because we
1537 // could be within a context where we might find out later that
1538 // the expression is potentially evaluated (e.g., for typeid).
1539 ExprEvalContexts.back().Lambdas.push_back(Lambda);
1540 break;
Douglas Gregor89625492012-02-09 08:14:43 +00001541
Douglas Gregorb4328232012-02-14 00:00:48 +00001542 case PotentiallyEvaluated:
1543 case PotentiallyEvaluatedIfUsed:
1544 break;
1545 }
Douglas Gregor89625492012-02-09 08:14:43 +00001546 }
Faisal Valia17d19f2013-11-07 05:17:06 +00001547
Douglas Gregor8c50e7c2012-02-09 00:47:04 +00001548 return MaybeBindToTemporary(Lambda);
Douglas Gregor03dd13c2012-02-08 21:18:48 +00001549}
Eli Friedman98b01ed2012-03-01 04:01:32 +00001550
1551ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
1552 SourceLocation ConvLocation,
1553 CXXConversionDecl *Conv,
1554 Expr *Src) {
1555 // Make sure that the lambda call operator is marked used.
1556 CXXRecordDecl *Lambda = Conv->getParent();
1557 CXXMethodDecl *CallOperator
1558 = cast<CXXMethodDecl>(
David Blaikieff7d47a2012-12-19 00:45:41 +00001559 Lambda->lookup(
1560 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Eli Friedman98b01ed2012-03-01 04:01:32 +00001561 CallOperator->setReferenced();
Eli Friedman276dd182013-09-05 00:02:25 +00001562 CallOperator->markUsed(Context);
Eli Friedman98b01ed2012-03-01 04:01:32 +00001563
1564 ExprResult Init = PerformCopyInitialization(
1565 InitializedEntity::InitializeBlock(ConvLocation,
1566 Src->getType(),
1567 /*NRVO=*/false),
1568 CurrentLocation, Src);
1569 if (!Init.isInvalid())
1570 Init = ActOnFinishFullExpr(Init.take());
1571
1572 if (Init.isInvalid())
1573 return ExprError();
1574
1575 // Create the new block to be returned.
1576 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
1577
1578 // Set the type information.
1579 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
1580 Block->setIsVariadic(CallOperator->isVariadic());
1581 Block->setBlockMissingReturnType(false);
1582
1583 // Add parameters.
1584 SmallVector<ParmVarDecl *, 4> BlockParams;
1585 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1586 ParmVarDecl *From = CallOperator->getParamDecl(I);
1587 BlockParams.push_back(ParmVarDecl::Create(Context, Block,
1588 From->getLocStart(),
1589 From->getLocation(),
1590 From->getIdentifier(),
1591 From->getType(),
1592 From->getTypeSourceInfo(),
1593 From->getStorageClass(),
Eli Friedman98b01ed2012-03-01 04:01:32 +00001594 /*DefaultArg=*/0));
1595 }
1596 Block->setParams(BlockParams);
1597
1598 Block->setIsConversionFromLambda(true);
1599
1600 // Add capture. The capture uses a fake variable, which doesn't correspond
1601 // to any actual memory location. However, the initializer copy-initializes
1602 // the lambda object.
1603 TypeSourceInfo *CapVarTSI =
1604 Context.getTrivialTypeSourceInfo(Src->getType());
1605 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1606 ConvLocation, 0,
1607 Src->getType(), CapVarTSI,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00001608 SC_None);
Eli Friedman98b01ed2012-03-01 04:01:32 +00001609 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
1610 /*Nested=*/false, /*Copy=*/Init.take());
1611 Block->setCaptures(Context, &Capture, &Capture + 1,
1612 /*CapturesCXXThis=*/false);
1613
1614 // Add a fake function body to the block. IR generation is responsible
1615 // for filling in the actual body, which cannot be expressed as an AST.
Benjamin Kramere2a929d2012-07-04 17:03:41 +00001616 Block->setBody(new (Context) CompoundStmt(ConvLocation));
Eli Friedman98b01ed2012-03-01 04:01:32 +00001617
1618 // Create the block literal expression.
1619 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1620 ExprCleanupObjects.push_back(Block);
1621 ExprNeedsCleanups = true;
1622
1623 return BuildBlock;
1624}