blob: 9b3afc999020004b5f2d30b0c782c0fbb582a65a [file] [log] [blame]
Douglas Gregore2a7ad02012-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 Valifad9e132013-09-26 19:54:12 +000014#include "clang/AST/ASTLambda.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000015#include "clang/AST/ExprCXX.h"
Reid Kleckner942f9fe2013-09-10 20:14:30 +000016#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "clang/Lex/Preprocessor.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000018#include "clang/Sema/Initialization.h"
19#include "clang/Sema/Lookup.h"
Douglas Gregor5878cbc2012-02-21 04:17:39 +000020#include "clang/Sema/Scope.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000021#include "clang/Sema/ScopeInfo.h"
22#include "clang/Sema/SemaInternal.h"
Richard Smith0d8e9642013-05-16 06:20:58 +000023#include "TypeLocBuilder.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000024using namespace clang;
25using namespace sema;
26
Faisal Valibef582b2013-10-23 16:10:50 +000027
28static inline TemplateParameterList *
29getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) {
30 if (LSI->GLTemplateParameterList)
31 return LSI->GLTemplateParameterList;
32
33 if (LSI->AutoTemplateParams.size()) {
34 SourceRange IntroRange = LSI->IntroducerRange;
35 SourceLocation LAngleLoc = IntroRange.getBegin();
36 SourceLocation RAngleLoc = IntroRange.getEnd();
37 LSI->GLTemplateParameterList = TemplateParameterList::Create(
38 SemaRef.Context,
39 /*Template kw loc*/SourceLocation(),
40 LAngleLoc,
41 (NamedDecl**)LSI->AutoTemplateParams.data(),
42 LSI->AutoTemplateParams.size(), RAngleLoc);
43 }
44 return LSI->GLTemplateParameterList;
45}
46
47
48
Douglas Gregorf4b7de12012-02-21 19:11:17 +000049CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
Eli Friedman8da8a662012-09-19 01:18:11 +000050 TypeSourceInfo *Info,
Faisal Valibef582b2013-10-23 16:10:50 +000051 bool KnownDependent,
52 LambdaCaptureDefault CaptureDefault) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +000053 DeclContext *DC = CurContext;
54 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
55 DC = DC->getParent();
Faisal Valibef582b2013-10-23 16:10:50 +000056 bool IsGenericLambda = getGenericLambdaTemplateParameterList(getCurLambda(),
57 *this);
Douglas Gregore2a7ad02012-02-08 21:18:48 +000058 // Start constructing the lambda class.
Eli Friedman8da8a662012-09-19 01:18:11 +000059 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info,
Douglas Gregorf4b7de12012-02-21 19:11:17 +000060 IntroducerRange.getBegin(),
Faisal Valibef582b2013-10-23 16:10:50 +000061 KnownDependent,
62 IsGenericLambda,
63 CaptureDefault);
Douglas Gregorfa07ab52012-02-20 20:47:06 +000064 DC->addDecl(Class);
Douglas Gregordfca6f52012-02-13 22:00:16 +000065
66 return Class;
67}
Douglas Gregore2a7ad02012-02-08 21:18:48 +000068
Douglas Gregorf54486a2012-04-04 17:40:10 +000069/// \brief Determine whether the given context is or is enclosed in an inline
70/// function.
71static bool isInInlineFunction(const DeclContext *DC) {
72 while (!DC->isFileContext()) {
73 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
74 if (FD->isInlined())
75 return true;
76
77 DC = DC->getLexicalParent();
78 }
79
80 return false;
81}
82
Eli Friedman07369dd2013-07-01 20:22:57 +000083MangleNumberingContext *
Eli Friedman5e867c82013-07-10 00:30:46 +000084Sema::getCurrentMangleNumberContext(const DeclContext *DC,
Eli Friedman07369dd2013-07-01 20:22:57 +000085 Decl *&ManglingContextDecl) {
86 // Compute the context for allocating mangling numbers in the current
87 // expression, if the ABI requires them.
88 ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
89
90 enum ContextKind {
91 Normal,
92 DefaultArgument,
93 DataMember,
94 StaticDataMember
95 } Kind = Normal;
96
97 // Default arguments of member function parameters that appear in a class
98 // definition, as well as the initializers of data members, receive special
99 // treatment. Identify them.
100 if (ManglingContextDecl) {
101 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
102 if (const DeclContext *LexicalDC
103 = Param->getDeclContext()->getLexicalParent())
104 if (LexicalDC->isRecord())
105 Kind = DefaultArgument;
106 } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
107 if (Var->getDeclContext()->isRecord())
108 Kind = StaticDataMember;
109 } else if (isa<FieldDecl>(ManglingContextDecl)) {
110 Kind = DataMember;
111 }
112 }
113
114 // Itanium ABI [5.1.7]:
115 // In the following contexts [...] the one-definition rule requires closure
116 // types in different translation units to "correspond":
117 bool IsInNonspecializedTemplate =
118 !ActiveTemplateInstantiations.empty() || CurContext->isDependentContext();
119 switch (Kind) {
120 case Normal:
121 // -- the bodies of non-exported nonspecialized template functions
122 // -- the bodies of inline functions
123 if ((IsInNonspecializedTemplate &&
124 !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
125 isInInlineFunction(CurContext)) {
126 ManglingContextDecl = 0;
127 return &Context.getManglingNumberContext(DC);
128 }
129
130 ManglingContextDecl = 0;
131 return 0;
132
133 case StaticDataMember:
134 // -- the initializers of nonspecialized static members of template classes
135 if (!IsInNonspecializedTemplate) {
136 ManglingContextDecl = 0;
137 return 0;
138 }
139 // Fall through to get the current context.
140
141 case DataMember:
142 // -- the in-class initializers of class members
143 case DefaultArgument:
144 // -- default arguments appearing in class definitions
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000145 return &ExprEvalContexts.back().getMangleNumberingContext(Context);
Eli Friedman07369dd2013-07-01 20:22:57 +0000146 }
Andy Gibbsce9cd912013-07-02 16:01:56 +0000147
148 llvm_unreachable("unexpected context");
Eli Friedman07369dd2013-07-01 20:22:57 +0000149}
150
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000151MangleNumberingContext &
152Sema::ExpressionEvaluationContextRecord::getMangleNumberingContext(
153 ASTContext &Ctx) {
154 assert(ManglingContextDecl && "Need to have a context declaration");
155 if (!MangleNumbering)
156 MangleNumbering = Ctx.createMangleNumberingContext();
157 return *MangleNumbering;
158}
159
Douglas Gregordfca6f52012-02-13 22:00:16 +0000160CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
Richard Smith41d09582013-09-25 05:02:54 +0000161 SourceRange IntroducerRange,
162 TypeSourceInfo *MethodTypeInfo,
163 SourceLocation EndLoc,
164 ArrayRef<ParmVarDecl *> Params) {
165 QualType MethodType = MethodTypeInfo->getType();
Faisal Valifad9e132013-09-26 19:54:12 +0000166 TemplateParameterList *TemplateParams =
167 getGenericLambdaTemplateParameterList(getCurLambda(), *this);
168 // If a lambda appears in a dependent context or is a generic lambda (has
169 // template parameters) and has an 'auto' return type, deduce it to a
170 // dependent type.
171 if (Class->isDependentContext() || TemplateParams) {
Richard Smith41d09582013-09-25 05:02:54 +0000172 const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
173 QualType Result = FPT->getResultType();
174 if (Result->isUndeducedType()) {
175 Result = SubstAutoType(Result, Context.DependentTy);
176 MethodType = Context.getFunctionType(Result, FPT->getArgTypes(),
177 FPT->getExtProtoInfo());
178 }
179 }
180
Douglas Gregordfca6f52012-02-13 22:00:16 +0000181 // C++11 [expr.prim.lambda]p5:
182 // The closure type for a lambda-expression has a public inline function
183 // call operator (13.5.4) whose parameters and return type are described by
184 // the lambda-expression's parameter-declaration-clause and
185 // trailing-return-type respectively.
186 DeclarationName MethodName
187 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
188 DeclarationNameLoc MethodNameLoc;
189 MethodNameLoc.CXXOperatorName.BeginOpNameLoc
190 = IntroducerRange.getBegin().getRawEncoding();
191 MethodNameLoc.CXXOperatorName.EndOpNameLoc
192 = IntroducerRange.getEnd().getRawEncoding();
193 CXXMethodDecl *Method
194 = CXXMethodDecl::Create(Context, Class, EndLoc,
195 DeclarationNameInfo(MethodName,
196 IntroducerRange.getBegin(),
197 MethodNameLoc),
Richard Smith41d09582013-09-25 05:02:54 +0000198 MethodType, MethodTypeInfo,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000199 SC_None,
200 /*isInline=*/true,
201 /*isConstExpr=*/false,
202 EndLoc);
203 Method->setAccess(AS_public);
204
205 // Temporarily set the lexical declaration context to the current
206 // context, so that the Scope stack matches the lexical nesting.
Douglas Gregorfa07ab52012-02-20 20:47:06 +0000207 Method->setLexicalDeclContext(CurContext);
Faisal Valifad9e132013-09-26 19:54:12 +0000208 // Create a function template if we have a template parameter list
209 FunctionTemplateDecl *const TemplateMethod = TemplateParams ?
210 FunctionTemplateDecl::Create(Context, Class,
211 Method->getLocation(), MethodName,
212 TemplateParams,
213 Method) : 0;
214 if (TemplateMethod) {
215 TemplateMethod->setLexicalDeclContext(CurContext);
216 TemplateMethod->setAccess(AS_public);
217 Method->setDescribedFunctionTemplate(TemplateMethod);
218 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000219
Douglas Gregorc6889e72012-02-14 22:28:59 +0000220 // Add parameters.
221 if (!Params.empty()) {
222 Method->setParams(Params);
223 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
224 const_cast<ParmVarDecl **>(Params.end()),
225 /*CheckParameterNames=*/false);
226
227 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
228 PEnd = Method->param_end();
229 P != PEnd; ++P)
230 (*P)->setOwningFunction(Method);
231 }
Richard Smithadb1d4c2012-07-22 23:45:10 +0000232
Eli Friedman07369dd2013-07-01 20:22:57 +0000233 Decl *ManglingContextDecl;
234 if (MangleNumberingContext *MCtx =
235 getCurrentMangleNumberContext(Class->getDeclContext(),
236 ManglingContextDecl)) {
237 unsigned ManglingNumber = MCtx->getManglingNumber(Method);
238 Class->setLambdaMangling(ManglingNumber, ManglingContextDecl);
Douglas Gregorf54486a2012-04-04 17:40:10 +0000239 }
240
Douglas Gregordfca6f52012-02-13 22:00:16 +0000241 return Method;
242}
243
Faisal Valifad9e132013-09-26 19:54:12 +0000244void Sema::buildLambdaScope(LambdaScopeInfo *LSI,
245 CXXMethodDecl *CallOperator,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000246 SourceRange IntroducerRange,
247 LambdaCaptureDefault CaptureDefault,
James Dennettf68af642013-08-09 23:08:25 +0000248 SourceLocation CaptureDefaultLoc,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000249 bool ExplicitParams,
250 bool ExplicitResultType,
251 bool Mutable) {
Faisal Valifad9e132013-09-26 19:54:12 +0000252 LSI->CallOperator = CallOperator;
Faisal Valibef582b2013-10-23 16:10:50 +0000253 CXXRecordDecl *LambdaClass = CallOperator->getParent();
254 LSI->Lambda = LambdaClass;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000255 if (CaptureDefault == LCD_ByCopy)
256 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
257 else if (CaptureDefault == LCD_ByRef)
258 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
James Dennettf68af642013-08-09 23:08:25 +0000259 LSI->CaptureDefaultLoc = CaptureDefaultLoc;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000260 LSI->IntroducerRange = IntroducerRange;
261 LSI->ExplicitParams = ExplicitParams;
262 LSI->Mutable = Mutable;
263
264 if (ExplicitResultType) {
265 LSI->ReturnType = CallOperator->getResultType();
Douglas Gregor53393f22012-02-14 21:20:44 +0000266
267 if (!LSI->ReturnType->isDependentType() &&
268 !LSI->ReturnType->isVoidType()) {
269 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
270 diag::err_lambda_incomplete_result)) {
271 // Do nothing.
Douglas Gregor53393f22012-02-14 21:20:44 +0000272 }
273 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000274 } else {
275 LSI->HasImplicitReturnType = true;
276 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000277}
278
279void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
280 LSI->finishedExplicitCaptures();
281}
282
Douglas Gregorc6889e72012-02-14 22:28:59 +0000283void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
Douglas Gregordfca6f52012-02-13 22:00:16 +0000284 // Introduce our parameters into the function scope
285 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
286 p < NumParams; ++p) {
287 ParmVarDecl *Param = CallOperator->getParamDecl(p);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000288
289 // If this has an identifier, add it to the scope stack.
290 if (CurScope && Param->getIdentifier()) {
291 CheckShadow(CurScope, Param);
292
293 PushOnScopeChains(Param, CurScope);
294 }
295 }
296}
297
John McCall41d01642013-03-09 00:54:31 +0000298/// If this expression is an enumerator-like expression of some type
299/// T, return the type T; otherwise, return null.
300///
301/// Pointer comparisons on the result here should always work because
302/// it's derived from either the parent of an EnumConstantDecl
303/// (i.e. the definition) or the declaration returned by
304/// EnumType::getDecl() (i.e. the definition).
305static EnumDecl *findEnumForBlockReturn(Expr *E) {
306 // An expression is an enumerator-like expression of type T if,
307 // ignoring parens and parens-like expressions:
308 E = E->IgnoreParens();
Jordan Rose7dd900e2012-07-02 21:19:23 +0000309
John McCall41d01642013-03-09 00:54:31 +0000310 // - it is an enumerator whose enum type is T or
311 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
312 if (EnumConstantDecl *D
313 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
314 return cast<EnumDecl>(D->getDeclContext());
315 }
316 return 0;
Jordan Rose7dd900e2012-07-02 21:19:23 +0000317 }
318
John McCall41d01642013-03-09 00:54:31 +0000319 // - it is a comma expression whose RHS is an enumerator-like
320 // expression of type T or
321 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
322 if (BO->getOpcode() == BO_Comma)
323 return findEnumForBlockReturn(BO->getRHS());
324 return 0;
325 }
Jordan Rose7dd900e2012-07-02 21:19:23 +0000326
John McCall41d01642013-03-09 00:54:31 +0000327 // - it is a statement-expression whose value expression is an
328 // enumerator-like expression of type T or
329 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
330 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
331 return findEnumForBlockReturn(last);
332 return 0;
333 }
334
335 // - it is a ternary conditional operator (not the GNU ?:
336 // extension) whose second and third operands are
337 // enumerator-like expressions of type T or
338 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
339 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
340 if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
341 return ED;
342 return 0;
343 }
344
345 // (implicitly:)
346 // - it is an implicit integral conversion applied to an
347 // enumerator-like expression of type T or
348 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall70133b52013-05-08 03:34:22 +0000349 // We can sometimes see integral conversions in valid
350 // enumerator-like expressions.
John McCall41d01642013-03-09 00:54:31 +0000351 if (ICE->getCastKind() == CK_IntegralCast)
352 return findEnumForBlockReturn(ICE->getSubExpr());
John McCall70133b52013-05-08 03:34:22 +0000353
354 // Otherwise, just rely on the type.
John McCall41d01642013-03-09 00:54:31 +0000355 }
356
357 // - it is an expression of that formal enum type.
358 if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
359 return ET->getDecl();
360 }
361
362 // Otherwise, nope.
363 return 0;
364}
365
366/// Attempt to find a type T for which the returned expression of the
367/// given statement is an enumerator-like expression of that type.
368static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
369 if (Expr *retValue = ret->getRetValue())
370 return findEnumForBlockReturn(retValue);
371 return 0;
372}
373
374/// Attempt to find a common type T for which all of the returned
375/// expressions in a block are enumerator-like expressions of that
376/// type.
377static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
378 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
379
380 // Try to find one for the first return.
381 EnumDecl *ED = findEnumForBlockReturn(*i);
382 if (!ED) return 0;
383
384 // Check that the rest of the returns have the same enum.
385 for (++i; i != e; ++i) {
386 if (findEnumForBlockReturn(*i) != ED)
387 return 0;
388 }
389
390 // Never infer an anonymous enum type.
391 if (!ED->hasNameForLinkage()) return 0;
392
393 return ED;
394}
395
396/// Adjust the given return statements so that they formally return
397/// the given type. It should require, at most, an IntegralCast.
398static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
399 QualType returnType) {
400 for (ArrayRef<ReturnStmt*>::iterator
401 i = returns.begin(), e = returns.end(); i != e; ++i) {
402 ReturnStmt *ret = *i;
403 Expr *retValue = ret->getRetValue();
404 if (S.Context.hasSameType(retValue->getType(), returnType))
405 continue;
406
407 // Right now we only support integral fixup casts.
408 assert(returnType->isIntegralOrUnscopedEnumerationType());
409 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
410
411 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
412
413 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
414 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast,
415 E, /*base path*/ 0, VK_RValue);
416 if (cleanups) {
417 cleanups->setSubExpr(E);
418 } else {
419 ret->setRetValue(E);
Jordan Rose7dd900e2012-07-02 21:19:23 +0000420 }
421 }
Jordan Rose7dd900e2012-07-02 21:19:23 +0000422}
423
424void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
Manuel Klimek152b4e42013-08-22 12:12:24 +0000425 assert(CSI.HasImplicitReturnType);
Faisal Valifad9e132013-09-26 19:54:12 +0000426 // If it was ever a placeholder, it had to been deduced to DependentTy.
427 assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
Jordan Rose7dd900e2012-07-02 21:19:23 +0000428
John McCall41d01642013-03-09 00:54:31 +0000429 // C++ Core Issue #975, proposed resolution:
430 // If a lambda-expression does not include a trailing-return-type,
431 // it is as if the trailing-return-type denotes the following type:
432 // - if there are no return statements in the compound-statement,
433 // or all return statements return either an expression of type
434 // void or no expression or braced-init-list, the type void;
435 // - otherwise, if all return statements return an expression
436 // and the types of the returned expressions after
437 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
438 // array-to-pointer conversion (4.2 [conv.array]), and
439 // function-to-pointer conversion (4.3 [conv.func]) are the
440 // same, that common type;
441 // - otherwise, the program is ill-formed.
442 //
443 // In addition, in blocks in non-C++ modes, if all of the return
444 // statements are enumerator-like expressions of some type T, where
445 // T has a name for linkage, then we infer the return type of the
446 // block to be that type.
447
Jordan Rose7dd900e2012-07-02 21:19:23 +0000448 // First case: no return statements, implicit void return type.
449 ASTContext &Ctx = getASTContext();
450 if (CSI.Returns.empty()) {
451 // It's possible there were simply no /valid/ return statements.
452 // In this case, the first one we found may have at least given us a type.
453 if (CSI.ReturnType.isNull())
454 CSI.ReturnType = Ctx.VoidTy;
455 return;
456 }
457
458 // Second case: at least one return statement has dependent type.
459 // Delay type checking until instantiation.
460 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
Manuel Klimek152b4e42013-08-22 12:12:24 +0000461 if (CSI.ReturnType->isDependentType())
Jordan Rose7dd900e2012-07-02 21:19:23 +0000462 return;
463
John McCall41d01642013-03-09 00:54:31 +0000464 // Try to apply the enum-fuzz rule.
465 if (!getLangOpts().CPlusPlus) {
466 assert(isa<BlockScopeInfo>(CSI));
467 const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
468 if (ED) {
469 CSI.ReturnType = Context.getTypeDeclType(ED);
470 adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
471 return;
472 }
473 }
474
Jordan Rose7dd900e2012-07-02 21:19:23 +0000475 // Third case: only one return statement. Don't bother doing extra work!
476 SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
477 E = CSI.Returns.end();
478 if (I+1 == E)
479 return;
480
481 // General case: many return statements.
482 // Check that they all have compatible return types.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000483
484 // We require the return types to strictly match here.
John McCall41d01642013-03-09 00:54:31 +0000485 // Note that we've already done the required promotions as part of
486 // processing the return statement.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000487 for (; I != E; ++I) {
488 const ReturnStmt *RS = *I;
489 const Expr *RetE = RS->getRetValue();
Jordan Rose7dd900e2012-07-02 21:19:23 +0000490
John McCall41d01642013-03-09 00:54:31 +0000491 QualType ReturnType = (RetE ? RetE->getType() : Context.VoidTy);
492 if (Context.hasSameType(ReturnType, CSI.ReturnType))
493 continue;
Jordan Rose7dd900e2012-07-02 21:19:23 +0000494
John McCall41d01642013-03-09 00:54:31 +0000495 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
496 // TODO: It's possible that the *first* return is the divergent one.
497 Diag(RS->getLocStart(),
498 diag::err_typecheck_missing_return_type_incompatible)
499 << ReturnType << CSI.ReturnType
500 << isa<LambdaScopeInfo>(CSI);
501 // Continue iterating so that we keep emitting diagnostics.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000502 }
503}
504
Richard Smith04fa7a32013-09-28 04:02:39 +0000505VarDecl *Sema::checkInitCapture(SourceLocation Loc, bool ByRef,
506 IdentifierInfo *Id, Expr *Init) {
Richard Smith0d8e9642013-05-16 06:20:58 +0000507 // C++1y [expr.prim.lambda]p11:
Richard Smith04fa7a32013-09-28 04:02:39 +0000508 // An init-capture behaves as if it declares and explicitly captures
509 // a variable of the form
510 // "auto init-capture;"
Richard Smith0d8e9642013-05-16 06:20:58 +0000511 QualType DeductType = Context.getAutoDeductType();
512 TypeLocBuilder TLB;
513 TLB.pushTypeSpec(DeductType).setNameLoc(Loc);
514 if (ByRef) {
515 DeductType = BuildReferenceType(DeductType, true, Loc, Id);
516 assert(!DeductType.isNull() && "can't build reference to auto");
517 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
518 }
Eli Friedman44ee0a72013-06-07 20:31:48 +0000519 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
Richard Smith0d8e9642013-05-16 06:20:58 +0000520
Richard Smith04fa7a32013-09-28 04:02:39 +0000521 // Create a dummy variable representing the init-capture. This is not actually
522 // used as a variable, and only exists as a way to name and refer to the
523 // init-capture.
524 // FIXME: Pass in separate source locations for '&' and identifier.
Richard Smith39edfeb2013-09-28 04:31:26 +0000525 VarDecl *NewVD = VarDecl::Create(Context, CurContext, Loc,
Richard Smith04fa7a32013-09-28 04:02:39 +0000526 Loc, Id, TSI->getType(), TSI, SC_Auto);
527 NewVD->setInitCapture(true);
528 NewVD->setReferenced(true);
529 NewVD->markUsed(Context);
Richard Smith0d8e9642013-05-16 06:20:58 +0000530
Richard Smith04fa7a32013-09-28 04:02:39 +0000531 // We do not need to distinguish between direct-list-initialization
532 // and copy-list-initialization here, because we will always deduce
533 // std::initializer_list<T>, and direct- and copy-list-initialization
534 // always behave the same for such a type.
535 // FIXME: We should model whether an '=' was present.
536 bool DirectInit = isa<ParenListExpr>(Init) || isa<InitListExpr>(Init);
537 AddInitializerToDecl(NewVD, Init, DirectInit, /*ContainsAuto*/true);
538 return NewVD;
539}
Richard Smith0d8e9642013-05-16 06:20:58 +0000540
Richard Smith04fa7a32013-09-28 04:02:39 +0000541FieldDecl *Sema::buildInitCaptureField(LambdaScopeInfo *LSI, VarDecl *Var) {
542 FieldDecl *Field = FieldDecl::Create(
543 Context, LSI->Lambda, Var->getLocation(), Var->getLocation(),
544 0, Var->getType(), Var->getTypeSourceInfo(), 0, false, ICIS_NoInit);
545 Field->setImplicit(true);
546 Field->setAccess(AS_private);
547 LSI->Lambda->addDecl(Field);
Richard Smith0d8e9642013-05-16 06:20:58 +0000548
Richard Smith04fa7a32013-09-28 04:02:39 +0000549 LSI->addCapture(Var, /*isBlock*/false, Var->getType()->isReferenceType(),
550 /*isNested*/false, Var->getLocation(), SourceLocation(),
551 Var->getType(), Var->getInit());
552 return Field;
Richard Smith0d8e9642013-05-16 06:20:58 +0000553}
554
Douglas Gregordfca6f52012-02-13 22:00:16 +0000555void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
Faisal Valifad9e132013-09-26 19:54:12 +0000556 Declarator &ParamInfo, Scope *CurScope) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000557 // Determine if we're within a context where we know that the lambda will
558 // be dependent, because there are template parameters in scope.
559 bool KnownDependent = false;
Faisal Valifad9e132013-09-26 19:54:12 +0000560 LambdaScopeInfo *const LSI = getCurLambda();
561 assert(LSI && "LambdaScopeInfo should be on stack!");
562 TemplateParameterList *TemplateParams =
563 getGenericLambdaTemplateParameterList(LSI, *this);
564
565 if (Scope *TmplScope = CurScope->getTemplateParamParent()) {
566 // Since we have our own TemplateParams, so check if an outer scope
567 // has template params, only then are we in a dependent scope.
568 if (TemplateParams) {
569 TmplScope = TmplScope->getParent();
570 TmplScope = TmplScope ? TmplScope->getTemplateParamParent() : 0;
571 }
572 if (TmplScope && !TmplScope->decl_empty())
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000573 KnownDependent = true;
Faisal Valifad9e132013-09-26 19:54:12 +0000574 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000575 // Determine the signature of the call operator.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000576 TypeSourceInfo *MethodTyInfo;
577 bool ExplicitParams = true;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000578 bool ExplicitResultType = true;
Richard Smith612409e2012-07-25 03:56:55 +0000579 bool ContainsUnexpandedParameterPack = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000580 SourceLocation EndLoc;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000581 SmallVector<ParmVarDecl *, 8> Params;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000582 if (ParamInfo.getNumTypeObjects() == 0) {
583 // C++11 [expr.prim.lambda]p4:
584 // If a lambda-expression does not include a lambda-declarator, it is as
585 // if the lambda-declarator were ().
Reid Kleckneref072032013-08-27 23:08:25 +0000586 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
587 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Richard Smitheefb3d52012-02-10 09:58:53 +0000588 EPI.HasTrailingReturn = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000589 EPI.TypeQuals |= DeclSpec::TQ_const;
Richard Smith41d09582013-09-25 05:02:54 +0000590 // C++1y [expr.prim.lambda]:
591 // The lambda return type is 'auto', which is replaced by the
592 // trailing-return type if provided and/or deduced from 'return'
593 // statements
594 // We don't do this before C++1y, because we don't support deduced return
595 // types there.
596 QualType DefaultTypeForNoTrailingReturn =
597 getLangOpts().CPlusPlus1y ? Context.getAutoDeductType()
598 : Context.DependentTy;
599 QualType MethodTy =
600 Context.getFunctionType(DefaultTypeForNoTrailingReturn, None, EPI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000601 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
602 ExplicitParams = false;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000603 ExplicitResultType = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000604 EndLoc = Intro.Range.getEnd();
605 } else {
606 assert(ParamInfo.isFunctionDeclarator() &&
607 "lambda-declarator is a function");
608 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
Richard Smith41d09582013-09-25 05:02:54 +0000609
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000610 // C++11 [expr.prim.lambda]p5:
611 // This function call operator is declared const (9.3.1) if and only if
612 // the lambda-expression's parameter-declaration-clause is not followed
613 // by mutable. It is neither virtual nor declared volatile. [...]
614 if (!FTI.hasMutableQualifier())
615 FTI.TypeQuals |= DeclSpec::TQ_const;
Richard Smith41d09582013-09-25 05:02:54 +0000616
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000617 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000618 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000619 EndLoc = ParamInfo.getSourceRange().getEnd();
Richard Smith41d09582013-09-25 05:02:54 +0000620
621 ExplicitResultType = FTI.hasTrailingReturnType();
Manuel Klimek152b4e42013-08-22 12:12:24 +0000622
Eli Friedman7c3c6bc2012-09-20 01:40:23 +0000623 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
624 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
625 // Empty arg list, don't push any params.
626 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
627 } else {
628 Params.reserve(FTI.NumArgs);
629 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
630 Params.push_back(cast<ParmVarDecl>(FTI.ArgInfo[i].Param));
631 }
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000632
633 // Check for unexpanded parameter packs in the method type.
Richard Smith612409e2012-07-25 03:56:55 +0000634 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
635 ContainsUnexpandedParameterPack = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000636 }
Eli Friedman8da8a662012-09-19 01:18:11 +0000637
638 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
Faisal Valibef582b2013-10-23 16:10:50 +0000639 KnownDependent, Intro.Default);
Eli Friedman8da8a662012-09-19 01:18:11 +0000640
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000641 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregorc6889e72012-02-14 22:28:59 +0000642 MethodTyInfo, EndLoc, Params);
Douglas Gregorc6889e72012-02-14 22:28:59 +0000643 if (ExplicitParams)
644 CheckCXXDefaultArguments(Method);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000645
Bill Wendlingad017fa2012-12-20 19:22:21 +0000646 // Attributes on the lambda apply to the method.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000647 ProcessDeclAttributes(CurScope, Method, ParamInfo);
648
Douglas Gregor503384f2012-02-09 00:47:04 +0000649 // Introduce the function call operator as the current declaration context.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000650 PushDeclContext(CurScope, Method);
651
Faisal Valifad9e132013-09-26 19:54:12 +0000652 // Build the lambda scope.
653 buildLambdaScope(LSI, Method,
James Dennettf68af642013-08-09 23:08:25 +0000654 Intro.Range,
655 Intro.Default, Intro.DefaultLoc,
656 ExplicitParams,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000657 ExplicitResultType,
David Blaikie4ef832f2012-08-10 00:55:35 +0000658 !Method->isConst());
Richard Smith0d8e9642013-05-16 06:20:58 +0000659
660 // Distinct capture names, for diagnostics.
661 llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
662
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000663 // Handle explicit captures.
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000664 SourceLocation PrevCaptureLoc
665 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Craig Topper09d19ef2013-07-04 03:08:24 +0000666 for (SmallVectorImpl<LambdaCapture>::const_iterator
667 C = Intro.Captures.begin(),
668 E = Intro.Captures.end();
669 C != E;
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000670 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000671 if (C->Kind == LCK_This) {
672 // C++11 [expr.prim.lambda]p8:
673 // An identifier or this shall not appear more than once in a
674 // lambda-capture.
675 if (LSI->isCXXThisCaptured()) {
676 Diag(C->Loc, diag::err_capture_more_than_once)
677 << "'this'"
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000678 << SourceRange(LSI->getCXXThisCapture().getLocation())
679 << FixItHint::CreateRemoval(
680 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000681 continue;
682 }
683
684 // C++11 [expr.prim.lambda]p8:
685 // If a lambda-capture includes a capture-default that is =, the
686 // lambda-capture shall not contain this [...].
687 if (Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000688 Diag(C->Loc, diag::err_this_capture_with_copy_default)
689 << FixItHint::CreateRemoval(
690 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000691 continue;
692 }
693
694 // C++11 [expr.prim.lambda]p12:
695 // If this is captured by a local lambda expression, its nearest
696 // enclosing function shall be a non-static member function.
697 QualType ThisCaptureType = getCurrentThisType();
698 if (ThisCaptureType.isNull()) {
699 Diag(C->Loc, diag::err_this_capture) << true;
700 continue;
701 }
702
703 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
704 continue;
705 }
706
Richard Smith0d8e9642013-05-16 06:20:58 +0000707 assert(C->Id && "missing identifier for capture");
708
Richard Smith0a664b82013-05-09 21:36:41 +0000709 if (C->Init.isInvalid())
710 continue;
Richard Smith0d8e9642013-05-16 06:20:58 +0000711
Richard Smith04fa7a32013-09-28 04:02:39 +0000712 VarDecl *Var;
713 if (C->Init.isUsable()) {
Richard Smith9beaf202013-09-28 05:38:27 +0000714 Diag(C->Loc, getLangOpts().CPlusPlus1y
715 ? diag::warn_cxx11_compat_init_capture
716 : diag::ext_init_capture);
717
Richard Smith0d8e9642013-05-16 06:20:58 +0000718 if (C->Init.get()->containsUnexpandedParameterPack())
719 ContainsUnexpandedParameterPack = true;
720
Richard Smith04fa7a32013-09-28 04:02:39 +0000721 Var = checkInitCapture(C->Loc, C->Kind == LCK_ByRef,
722 C->Id, C->Init.take());
Richard Smith0d8e9642013-05-16 06:20:58 +0000723 // C++1y [expr.prim.lambda]p11:
Richard Smith04fa7a32013-09-28 04:02:39 +0000724 // An init-capture behaves as if it declares and explicitly
725 // captures a variable [...] whose declarative region is the
726 // lambda-expression's compound-statement
727 if (Var)
728 PushOnScopeChains(Var, CurScope, false);
729 } else {
730 // C++11 [expr.prim.lambda]p8:
731 // If a lambda-capture includes a capture-default that is &, the
732 // identifiers in the lambda-capture shall not be preceded by &.
733 // If a lambda-capture includes a capture-default that is =, [...]
734 // each identifier it contains shall be preceded by &.
735 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
736 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
737 << FixItHint::CreateRemoval(
738 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000739 continue;
Richard Smith04fa7a32013-09-28 04:02:39 +0000740 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
741 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
742 << FixItHint::CreateRemoval(
743 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
744 continue;
745 }
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000746
Richard Smith04fa7a32013-09-28 04:02:39 +0000747 // C++11 [expr.prim.lambda]p10:
748 // The identifiers in a capture-list are looked up using the usual
749 // rules for unqualified name lookup (3.4.1)
750 DeclarationNameInfo Name(C->Id, C->Loc);
751 LookupResult R(*this, Name, LookupOrdinaryName);
752 LookupName(R, CurScope);
753 if (R.isAmbiguous())
754 continue;
755 if (R.empty()) {
756 // FIXME: Disable corrections that would add qualification?
757 CXXScopeSpec ScopeSpec;
758 DeclFilterCCC<VarDecl> Validator;
759 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
760 continue;
761 }
762
763 Var = R.getAsSingle<VarDecl>();
764 }
Richard Smith0d8e9642013-05-16 06:20:58 +0000765
766 // C++11 [expr.prim.lambda]p8:
767 // An identifier or this shall not appear more than once in a
768 // lambda-capture.
769 if (!CaptureNames.insert(C->Id)) {
770 if (Var && LSI->isCaptured(Var)) {
771 Diag(C->Loc, diag::err_capture_more_than_once)
772 << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
773 << FixItHint::CreateRemoval(
774 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
775 } else
Richard Smith04fa7a32013-09-28 04:02:39 +0000776 // Previous capture captured something different (one or both was
777 // an init-cpature): no fixit.
Richard Smith0d8e9642013-05-16 06:20:58 +0000778 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
779 continue;
780 }
781
782 // C++11 [expr.prim.lambda]p10:
783 // [...] each such lookup shall find a variable with automatic storage
784 // duration declared in the reaching scope of the local lambda expression.
785 // Note that the 'reaching scope' check happens in tryCaptureVariable().
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000786 if (!Var) {
787 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
788 continue;
789 }
790
Eli Friedman9cd5b242012-09-18 21:11:30 +0000791 // Ignore invalid decls; they'll just confuse the code later.
792 if (Var->isInvalidDecl())
793 continue;
794
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000795 if (!Var->hasLocalStorage()) {
796 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
797 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
798 continue;
799 }
800
Douglas Gregora7365242012-02-14 19:27:52 +0000801 // C++11 [expr.prim.lambda]p23:
802 // A capture followed by an ellipsis is a pack expansion (14.5.3).
803 SourceLocation EllipsisLoc;
804 if (C->EllipsisLoc.isValid()) {
805 if (Var->isParameterPack()) {
806 EllipsisLoc = C->EllipsisLoc;
807 } else {
808 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
809 << SourceRange(C->Loc);
810
811 // Just ignore the ellipsis.
812 }
813 } else if (Var->isParameterPack()) {
Richard Smith612409e2012-07-25 03:56:55 +0000814 ContainsUnexpandedParameterPack = true;
Douglas Gregora7365242012-02-14 19:27:52 +0000815 }
Richard Smith04fa7a32013-09-28 04:02:39 +0000816
817 if (C->Init.isUsable()) {
818 buildInitCaptureField(LSI, Var);
819 } else {
820 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
821 TryCapture_ExplicitByVal;
822 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
823 }
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000824 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000825 finishLambdaExplicitCaptures(LSI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000826
Richard Smith612409e2012-07-25 03:56:55 +0000827 LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
828
Douglas Gregorc6889e72012-02-14 22:28:59 +0000829 // Add lambda parameters into scope.
830 addLambdaParameters(Method, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000831
Douglas Gregordfca6f52012-02-13 22:00:16 +0000832 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor503384f2012-02-09 00:47:04 +0000833 // cleanups from the enclosing full-expression.
834 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000835}
836
Douglas Gregordfca6f52012-02-13 22:00:16 +0000837void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
838 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000839 // Leave the expression-evaluation context.
840 DiscardCleanupsInEvaluationContext();
841 PopExpressionEvaluationContext();
842
843 // Leave the context of the lambda.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000844 if (!IsInstantiation)
845 PopDeclContext();
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000846
847 // Finalize the lambda.
848 LambdaScopeInfo *LSI = getCurLambda();
849 CXXRecordDecl *Class = LSI->Lambda;
850 Class->setInvalidDecl();
David Blaikie262bc182012-04-30 02:36:29 +0000851 SmallVector<Decl*, 4> Fields;
852 for (RecordDecl::field_iterator i = Class->field_begin(),
853 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +0000854 Fields.push_back(*i);
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000855 ActOnFields(0, Class->getLocation(), Class, Fields,
856 SourceLocation(), SourceLocation(), 0);
857 CheckCompletedCXXClass(Class);
858
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000859 PopFunctionScopeInfo();
860}
861
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000862/// \brief Add a lambda's conversion to function pointer, as described in
863/// C++11 [expr.prim.lambda]p6.
864static void addFunctionPointerConversion(Sema &S,
865 SourceRange IntroducerRange,
866 CXXRecordDecl *Class,
867 CXXMethodDecl *CallOperator) {
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000868 // Add the conversion to function pointer.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000869 const FunctionProtoType *Proto
870 = CallOperator->getType()->getAs<FunctionProtoType>();
871 QualType FunctionPtrTy;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000872 QualType FunctionTy;
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000873 {
874 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
Reid Kleckneref072032013-08-27 23:08:25 +0000875 CallingConv CC = S.Context.getDefaultCallingConvention(
876 Proto->isVariadic(), /*IsCXXMethod=*/false);
877 ExtInfo.ExtInfo = ExtInfo.ExtInfo.withCallingConv(CC);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000878 ExtInfo.TypeQuals = 0;
Reid Kleckner0567a792013-06-10 20:51:09 +0000879 FunctionTy = S.Context.getFunctionType(Proto->getResultType(),
880 Proto->getArgTypes(), ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000881 FunctionPtrTy = S.Context.getPointerType(FunctionTy);
882 }
Reid Kleckneref072032013-08-27 23:08:25 +0000883
884 FunctionProtoType::ExtProtoInfo ExtInfo(S.Context.getDefaultCallingConvention(
885 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000886 ExtInfo.TypeQuals = Qualifiers::Const;
Reid Kleckneref072032013-08-27 23:08:25 +0000887 QualType ConvTy = S.Context.getFunctionType(FunctionPtrTy, None, ExtInfo);
888
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000889 SourceLocation Loc = IntroducerRange.getBegin();
890 DeclarationName Name
891 = S.Context.DeclarationNames.getCXXConversionFunctionName(
892 S.Context.getCanonicalType(FunctionPtrTy));
893 DeclarationNameLoc NameLoc;
894 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
895 Loc);
896 CXXConversionDecl *Conversion
897 = CXXConversionDecl::Create(S.Context, Class, Loc,
898 DeclarationNameInfo(Name, Loc, NameLoc),
899 ConvTy,
900 S.Context.getTrivialTypeSourceInfo(ConvTy,
901 Loc),
Eli Friedman38fa9612013-06-13 19:39:48 +0000902 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000903 /*isConstexpr=*/false,
904 CallOperator->getBody()->getLocEnd());
905 Conversion->setAccess(AS_public);
906 Conversion->setImplicit(true);
Faisal Valid6992ab2013-09-29 08:45:24 +0000907
908 if (Class->isGenericLambda()) {
909 // Create a template version of the conversion operator, using the template
910 // parameter list of the function call operator.
911 FunctionTemplateDecl *TemplateCallOperator =
912 CallOperator->getDescribedFunctionTemplate();
913 FunctionTemplateDecl *ConversionTemplate =
914 FunctionTemplateDecl::Create(S.Context, Class,
915 Loc, Name,
916 TemplateCallOperator->getTemplateParameters(),
917 Conversion);
918 ConversionTemplate->setAccess(AS_public);
919 ConversionTemplate->setImplicit(true);
920 Conversion->setDescribedFunctionTemplate(ConversionTemplate);
921 Class->addDecl(ConversionTemplate);
922 } else
923 Class->addDecl(Conversion);
Faisal Valifad9e132013-09-26 19:54:12 +0000924 // Add a non-static member function that will be the result of
925 // the conversion with a certain unique ID.
926 Name = &S.Context.Idents.get(getLambdaStaticInvokerName());
Faisal Valid6992ab2013-09-29 08:45:24 +0000927 // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
928 // we should get a prebuilt TrivialTypeSourceInfo from Context
929 // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
930 // then rewire the parameters accordingly, by hoisting up the InvokeParams
931 // loop below and then use its Params to set Invoke->setParams(...) below.
932 // This would avoid the 'const' qualifier of the calloperator from
933 // contaminating the type of the invoker, which is currently adjusted
934 // in SemaTemplateDeduction.cpp:DeduceTemplateArguments.
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000935 CXXMethodDecl *Invoke
936 = CXXMethodDecl::Create(S.Context, Class, Loc,
937 DeclarationNameInfo(Name, Loc), FunctionTy,
938 CallOperator->getTypeSourceInfo(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000939 SC_Static, /*IsInline=*/true,
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000940 /*IsConstexpr=*/false,
941 CallOperator->getBody()->getLocEnd());
942 SmallVector<ParmVarDecl *, 4> InvokeParams;
943 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
944 ParmVarDecl *From = CallOperator->getParamDecl(I);
945 InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
946 From->getLocStart(),
947 From->getLocation(),
948 From->getIdentifier(),
949 From->getType(),
950 From->getTypeSourceInfo(),
951 From->getStorageClass(),
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000952 /*DefaultArg=*/0));
953 }
954 Invoke->setParams(InvokeParams);
955 Invoke->setAccess(AS_private);
956 Invoke->setImplicit(true);
Faisal Valid6992ab2013-09-29 08:45:24 +0000957 if (Class->isGenericLambda()) {
958 FunctionTemplateDecl *TemplateCallOperator =
959 CallOperator->getDescribedFunctionTemplate();
960 FunctionTemplateDecl *StaticInvokerTemplate = FunctionTemplateDecl::Create(
961 S.Context, Class, Loc, Name,
962 TemplateCallOperator->getTemplateParameters(),
963 Invoke);
964 StaticInvokerTemplate->setAccess(AS_private);
965 StaticInvokerTemplate->setImplicit(true);
966 Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
967 Class->addDecl(StaticInvokerTemplate);
968 } else
969 Class->addDecl(Invoke);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000970}
971
Douglas Gregorc2956e52012-02-15 22:08:38 +0000972/// \brief Add a lambda's conversion to block pointer.
973static void addBlockPointerConversion(Sema &S,
974 SourceRange IntroducerRange,
975 CXXRecordDecl *Class,
976 CXXMethodDecl *CallOperator) {
977 const FunctionProtoType *Proto
978 = CallOperator->getType()->getAs<FunctionProtoType>();
979 QualType BlockPtrTy;
980 {
981 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
982 ExtInfo.TypeQuals = 0;
Reid Kleckner0567a792013-06-10 20:51:09 +0000983 QualType FunctionTy = S.Context.getFunctionType(
984 Proto->getResultType(), Proto->getArgTypes(), ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +0000985 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
986 }
Reid Kleckneref072032013-08-27 23:08:25 +0000987
988 FunctionProtoType::ExtProtoInfo ExtInfo(S.Context.getDefaultCallingConvention(
989 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Douglas Gregorc2956e52012-02-15 22:08:38 +0000990 ExtInfo.TypeQuals = Qualifiers::Const;
Dmitri Gribenko55431692013-05-05 00:41:58 +0000991 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +0000992
993 SourceLocation Loc = IntroducerRange.getBegin();
994 DeclarationName Name
995 = S.Context.DeclarationNames.getCXXConversionFunctionName(
996 S.Context.getCanonicalType(BlockPtrTy));
997 DeclarationNameLoc NameLoc;
998 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
999 CXXConversionDecl *Conversion
1000 = CXXConversionDecl::Create(S.Context, Class, Loc,
1001 DeclarationNameInfo(Name, Loc, NameLoc),
1002 ConvTy,
1003 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
Eli Friedman95099ef2013-06-13 20:56:27 +00001004 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregorc2956e52012-02-15 22:08:38 +00001005 /*isConstexpr=*/false,
1006 CallOperator->getBody()->getLocEnd());
1007 Conversion->setAccess(AS_public);
1008 Conversion->setImplicit(true);
1009 Class->addDecl(Conversion);
1010}
Douglas Gregor5878cbc2012-02-21 04:17:39 +00001011
Douglas Gregordfca6f52012-02-13 22:00:16 +00001012ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00001013 Scope *CurScope,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00001014 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001015 // Collect information from the lambda scope.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001016 SmallVector<LambdaExpr::Capture, 4> Captures;
1017 SmallVector<Expr *, 4> CaptureInits;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001018 LambdaCaptureDefault CaptureDefault;
James Dennettf68af642013-08-09 23:08:25 +00001019 SourceLocation CaptureDefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001020 CXXRecordDecl *Class;
Douglas Gregoref7d78b2012-02-10 08:36:38 +00001021 CXXMethodDecl *CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001022 SourceRange IntroducerRange;
1023 bool ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +00001024 bool ExplicitResultType;
Douglas Gregor503384f2012-02-09 00:47:04 +00001025 bool LambdaExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +00001026 bool ContainsUnexpandedParameterPack;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001027 SmallVector<VarDecl *, 4> ArrayIndexVars;
1028 SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001029 {
1030 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregoref7d78b2012-02-10 08:36:38 +00001031 CallOperator = LSI->CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001032 Class = LSI->Lambda;
1033 IntroducerRange = LSI->IntroducerRange;
1034 ExplicitParams = LSI->ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +00001035 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor503384f2012-02-09 00:47:04 +00001036 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +00001037 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +00001038 ArrayIndexVars.swap(LSI->ArrayIndexVars);
1039 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
1040
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001041 // Translate captures.
1042 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
1043 LambdaScopeInfo::Capture From = LSI->Captures[I];
1044 assert(!From.isBlockCapture() && "Cannot capture __block variables");
1045 bool IsImplicit = I >= LSI->NumExplicitCaptures;
1046
1047 // Handle 'this' capture.
1048 if (From.isThisCapture()) {
1049 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
1050 IsImplicit,
1051 LCK_This));
1052 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
1053 getCurrentThisType(),
1054 /*isImplicit=*/true));
1055 continue;
1056 }
1057
1058 VarDecl *Var = From.getVariable();
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001059 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
1060 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregora7365242012-02-14 19:27:52 +00001061 Kind, Var, From.getEllipsisLoc()));
Richard Smith0d8e9642013-05-16 06:20:58 +00001062 CaptureInits.push_back(From.getInitExpr());
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001063 }
1064
1065 switch (LSI->ImpCaptureStyle) {
1066 case CapturingScopeInfo::ImpCap_None:
1067 CaptureDefault = LCD_None;
1068 break;
1069
1070 case CapturingScopeInfo::ImpCap_LambdaByval:
1071 CaptureDefault = LCD_ByCopy;
1072 break;
1073
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00001074 case CapturingScopeInfo::ImpCap_CapturedRegion:
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001075 case CapturingScopeInfo::ImpCap_LambdaByref:
1076 CaptureDefault = LCD_ByRef;
1077 break;
1078
1079 case CapturingScopeInfo::ImpCap_Block:
1080 llvm_unreachable("block capture in lambda");
1081 break;
1082 }
James Dennettf68af642013-08-09 23:08:25 +00001083 CaptureDefaultLoc = LSI->CaptureDefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001084
Douglas Gregor54042f12012-02-09 10:18:50 +00001085 // C++11 [expr.prim.lambda]p4:
1086 // If a lambda-expression does not include a
1087 // trailing-return-type, it is as if the trailing-return-type
1088 // denotes the following type:
Richard Smith41d09582013-09-25 05:02:54 +00001089 //
1090 // Skip for C++1y return type deduction semantics which uses
1091 // different machinery.
1092 // FIXME: Refactor and Merge the return type deduction machinery.
Douglas Gregor54042f12012-02-09 10:18:50 +00001093 // FIXME: Assumes current resolution to core issue 975.
Richard Smith41d09582013-09-25 05:02:54 +00001094 if (LSI->HasImplicitReturnType && !getLangOpts().CPlusPlus1y) {
Jordan Rose7dd900e2012-07-02 21:19:23 +00001095 deduceClosureReturnType(*LSI);
1096
Douglas Gregor54042f12012-02-09 10:18:50 +00001097 // - if there are no return statements in the
1098 // compound-statement, or all return statements return
1099 // either an expression of type void or no expression or
1100 // braced-init-list, the type void;
1101 if (LSI->ReturnType.isNull()) {
1102 LSI->ReturnType = Context.VoidTy;
Douglas Gregor54042f12012-02-09 10:18:50 +00001103 }
1104
1105 // Create a function type with the inferred return type.
1106 const FunctionProtoType *Proto
1107 = CallOperator->getType()->getAs<FunctionProtoType>();
Reid Kleckner0567a792013-06-10 20:51:09 +00001108 QualType FunctionTy = Context.getFunctionType(
1109 LSI->ReturnType, Proto->getArgTypes(), Proto->getExtProtoInfo());
Douglas Gregor54042f12012-02-09 10:18:50 +00001110 CallOperator->setType(FunctionTy);
1111 }
Douglas Gregor215e4e12012-02-12 17:34:23 +00001112 // C++ [expr.prim.lambda]p7:
1113 // The lambda-expression's compound-statement yields the
1114 // function-body (8.4) of the function call operator [...].
Douglas Gregordfca6f52012-02-13 22:00:16 +00001115 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor215e4e12012-02-12 17:34:23 +00001116 CallOperator->setLexicalDeclContext(Class);
Faisal Valifad9e132013-09-26 19:54:12 +00001117 Decl *TemplateOrNonTemplateCallOperatorDecl =
1118 CallOperator->getDescribedFunctionTemplate()
1119 ? CallOperator->getDescribedFunctionTemplate()
1120 : cast<Decl>(CallOperator);
1121
1122 TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
1123 Class->addDecl(TemplateOrNonTemplateCallOperatorDecl);
1124
Douglas Gregorb09ab8c2012-02-21 20:05:31 +00001125 PopExpressionEvaluationContext();
Douglas Gregor215e4e12012-02-12 17:34:23 +00001126
Douglas Gregorb5559712012-02-10 16:13:20 +00001127 // C++11 [expr.prim.lambda]p6:
1128 // The closure type for a lambda-expression with no lambda-capture
1129 // has a public non-virtual non-explicit const conversion function
1130 // to pointer to function having the same parameter and return
1131 // types as the closure type's function call operator.
Douglas Gregorc25d1c92012-02-15 22:00:51 +00001132 if (Captures.empty() && CaptureDefault == LCD_None)
1133 addFunctionPointerConversion(*this, IntroducerRange, Class,
1134 CallOperator);
Douglas Gregor503384f2012-02-09 00:47:04 +00001135
Douglas Gregorc2956e52012-02-15 22:08:38 +00001136 // Objective-C++:
1137 // The closure type for a lambda-expression has a public non-virtual
1138 // non-explicit const conversion function to a block pointer having the
1139 // same parameter and return types as the closure type's function call
1140 // operator.
Faisal Valid6992ab2013-09-29 08:45:24 +00001141 // FIXME: Fix generic lambda to block conversions.
1142 if (getLangOpts().Blocks && getLangOpts().ObjC1 &&
1143 !Class->isGenericLambda())
Douglas Gregorc2956e52012-02-15 22:08:38 +00001144 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
1145
Douglas Gregorb5559712012-02-10 16:13:20 +00001146 // Finalize the lambda class.
David Blaikie262bc182012-04-30 02:36:29 +00001147 SmallVector<Decl*, 4> Fields;
1148 for (RecordDecl::field_iterator i = Class->field_begin(),
1149 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +00001150 Fields.push_back(*i);
Douglas Gregorb5559712012-02-10 16:13:20 +00001151 ActOnFields(0, Class->getLocation(), Class, Fields,
1152 SourceLocation(), SourceLocation(), 0);
1153 CheckCompletedCXXClass(Class);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001154 }
1155
Douglas Gregor503384f2012-02-09 00:47:04 +00001156 if (LambdaExprNeedsCleanups)
1157 ExprNeedsCleanups = true;
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00001158
Douglas Gregore2c59132012-02-09 08:14:43 +00001159 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
James Dennettf68af642013-08-09 23:08:25 +00001160 CaptureDefault, CaptureDefaultLoc,
1161 Captures,
Douglas Gregordfca6f52012-02-13 22:00:16 +00001162 ExplicitParams, ExplicitResultType,
1163 CaptureInits, ArrayIndexVars,
Richard Smith612409e2012-07-25 03:56:55 +00001164 ArrayIndexStarts, Body->getLocEnd(),
1165 ContainsUnexpandedParameterPack);
Douglas Gregore2c59132012-02-09 08:14:43 +00001166 // C++11 [expr.prim.lambda]p2:
1167 // A lambda-expression shall not appear in an unevaluated operand
1168 // (Clause 5).
Douglas Gregord5387e82012-02-14 00:00:48 +00001169 if (!CurContext->isDependentContext()) {
1170 switch (ExprEvalContexts.back().Context) {
1171 case Unevaluated:
John McCallaeeacf72013-05-03 00:10:13 +00001172 case UnevaluatedAbstract:
Douglas Gregord5387e82012-02-14 00:00:48 +00001173 // We don't actually diagnose this case immediately, because we
1174 // could be within a context where we might find out later that
1175 // the expression is potentially evaluated (e.g., for typeid).
1176 ExprEvalContexts.back().Lambdas.push_back(Lambda);
1177 break;
Douglas Gregore2c59132012-02-09 08:14:43 +00001178
Douglas Gregord5387e82012-02-14 00:00:48 +00001179 case ConstantEvaluated:
1180 case PotentiallyEvaluated:
1181 case PotentiallyEvaluatedIfUsed:
1182 break;
1183 }
Douglas Gregore2c59132012-02-09 08:14:43 +00001184 }
Faisal Valifad9e132013-09-26 19:54:12 +00001185 // TODO: Implement capturing.
1186 if (Lambda->isGenericLambda()) {
Faisal Valid6992ab2013-09-29 08:45:24 +00001187 if (!Captures.empty() || Lambda->getCaptureDefault() != LCD_None) {
Faisal Valifad9e132013-09-26 19:54:12 +00001188 Diag(Lambda->getIntroducerRange().getBegin(),
1189 diag::err_glambda_not_fully_implemented)
1190 << " capturing not implemented yet";
1191 return ExprError();
1192 }
1193 }
Douglas Gregor503384f2012-02-09 00:47:04 +00001194 return MaybeBindToTemporary(Lambda);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001195}
Eli Friedman23f02672012-03-01 04:01:32 +00001196
1197ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
1198 SourceLocation ConvLocation,
1199 CXXConversionDecl *Conv,
1200 Expr *Src) {
1201 // Make sure that the lambda call operator is marked used.
1202 CXXRecordDecl *Lambda = Conv->getParent();
1203 CXXMethodDecl *CallOperator
1204 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00001205 Lambda->lookup(
1206 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Eli Friedman23f02672012-03-01 04:01:32 +00001207 CallOperator->setReferenced();
Eli Friedman86164e82013-09-05 00:02:25 +00001208 CallOperator->markUsed(Context);
Eli Friedman23f02672012-03-01 04:01:32 +00001209
1210 ExprResult Init = PerformCopyInitialization(
1211 InitializedEntity::InitializeBlock(ConvLocation,
1212 Src->getType(),
1213 /*NRVO=*/false),
1214 CurrentLocation, Src);
1215 if (!Init.isInvalid())
1216 Init = ActOnFinishFullExpr(Init.take());
1217
1218 if (Init.isInvalid())
1219 return ExprError();
1220
1221 // Create the new block to be returned.
1222 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
1223
1224 // Set the type information.
1225 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
1226 Block->setIsVariadic(CallOperator->isVariadic());
1227 Block->setBlockMissingReturnType(false);
1228
1229 // Add parameters.
1230 SmallVector<ParmVarDecl *, 4> BlockParams;
1231 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1232 ParmVarDecl *From = CallOperator->getParamDecl(I);
1233 BlockParams.push_back(ParmVarDecl::Create(Context, Block,
1234 From->getLocStart(),
1235 From->getLocation(),
1236 From->getIdentifier(),
1237 From->getType(),
1238 From->getTypeSourceInfo(),
1239 From->getStorageClass(),
Eli Friedman23f02672012-03-01 04:01:32 +00001240 /*DefaultArg=*/0));
1241 }
1242 Block->setParams(BlockParams);
1243
1244 Block->setIsConversionFromLambda(true);
1245
1246 // Add capture. The capture uses a fake variable, which doesn't correspond
1247 // to any actual memory location. However, the initializer copy-initializes
1248 // the lambda object.
1249 TypeSourceInfo *CapVarTSI =
1250 Context.getTrivialTypeSourceInfo(Src->getType());
1251 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1252 ConvLocation, 0,
1253 Src->getType(), CapVarTSI,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001254 SC_None);
Eli Friedman23f02672012-03-01 04:01:32 +00001255 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
1256 /*Nested=*/false, /*Copy=*/Init.take());
1257 Block->setCaptures(Context, &Capture, &Capture + 1,
1258 /*CapturesCXXThis=*/false);
1259
1260 // Add a fake function body to the block. IR generation is responsible
1261 // for filling in the actual body, which cannot be expressed as an AST.
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00001262 Block->setBody(new (Context) CompoundStmt(ConvLocation));
Eli Friedman23f02672012-03-01 04:01:32 +00001263
1264 // Create the block literal expression.
1265 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1266 ExprCleanupObjects.push_back(Block);
1267 ExprNeedsCleanups = true;
1268
1269 return BuildBlock;
1270}