blob: bc99d58d1415c6a93f2787791ee096da4536ffd2 [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"
Chandler Carruth55fc8732012-12-04 09:13:33 +000014#include "clang/AST/ExprCXX.h"
15#include "clang/Lex/Preprocessor.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000016#include "clang/Sema/Initialization.h"
17#include "clang/Sema/Lookup.h"
Douglas Gregor5878cbc2012-02-21 04:17:39 +000018#include "clang/Sema/Scope.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000019#include "clang/Sema/ScopeInfo.h"
20#include "clang/Sema/SemaInternal.h"
Richard Smith0d8e9642013-05-16 06:20:58 +000021#include "TypeLocBuilder.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000022using namespace clang;
23using namespace sema;
24
Douglas Gregorf4b7de12012-02-21 19:11:17 +000025CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
Eli Friedman8da8a662012-09-19 01:18:11 +000026 TypeSourceInfo *Info,
Douglas Gregorf4b7de12012-02-21 19:11:17 +000027 bool KnownDependent) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +000028 DeclContext *DC = CurContext;
29 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
30 DC = DC->getParent();
Douglas Gregordfca6f52012-02-13 22:00:16 +000031
Douglas Gregore2a7ad02012-02-08 21:18:48 +000032 // Start constructing the lambda class.
Eli Friedman8da8a662012-09-19 01:18:11 +000033 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info,
Douglas Gregorf4b7de12012-02-21 19:11:17 +000034 IntroducerRange.getBegin(),
35 KnownDependent);
Douglas Gregorfa07ab52012-02-20 20:47:06 +000036 DC->addDecl(Class);
Douglas Gregordfca6f52012-02-13 22:00:16 +000037
38 return Class;
39}
Douglas Gregore2a7ad02012-02-08 21:18:48 +000040
Douglas Gregorf54486a2012-04-04 17:40:10 +000041/// \brief Determine whether the given context is or is enclosed in an inline
42/// function.
43static bool isInInlineFunction(const DeclContext *DC) {
44 while (!DC->isFileContext()) {
45 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
46 if (FD->isInlined())
47 return true;
48
49 DC = DC->getLexicalParent();
50 }
51
52 return false;
53}
54
Eli Friedman07369dd2013-07-01 20:22:57 +000055MangleNumberingContext *
56Sema::getCurrentMangleNumberContext(DeclContext *DC,
57 Decl *&ManglingContextDecl) {
58 // Compute the context for allocating mangling numbers in the current
59 // expression, if the ABI requires them.
60 ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
61
62 enum ContextKind {
63 Normal,
64 DefaultArgument,
65 DataMember,
66 StaticDataMember
67 } Kind = Normal;
68
69 // Default arguments of member function parameters that appear in a class
70 // definition, as well as the initializers of data members, receive special
71 // treatment. Identify them.
72 if (ManglingContextDecl) {
73 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
74 if (const DeclContext *LexicalDC
75 = Param->getDeclContext()->getLexicalParent())
76 if (LexicalDC->isRecord())
77 Kind = DefaultArgument;
78 } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
79 if (Var->getDeclContext()->isRecord())
80 Kind = StaticDataMember;
81 } else if (isa<FieldDecl>(ManglingContextDecl)) {
82 Kind = DataMember;
83 }
84 }
85
86 // Itanium ABI [5.1.7]:
87 // In the following contexts [...] the one-definition rule requires closure
88 // types in different translation units to "correspond":
89 bool IsInNonspecializedTemplate =
90 !ActiveTemplateInstantiations.empty() || CurContext->isDependentContext();
91 switch (Kind) {
92 case Normal:
93 // -- the bodies of non-exported nonspecialized template functions
94 // -- the bodies of inline functions
95 if ((IsInNonspecializedTemplate &&
96 !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
97 isInInlineFunction(CurContext)) {
98 ManglingContextDecl = 0;
99 return &Context.getManglingNumberContext(DC);
100 }
101
102 ManglingContextDecl = 0;
103 return 0;
104
105 case StaticDataMember:
106 // -- the initializers of nonspecialized static members of template classes
107 if (!IsInNonspecializedTemplate) {
108 ManglingContextDecl = 0;
109 return 0;
110 }
111 // Fall through to get the current context.
112
113 case DataMember:
114 // -- the in-class initializers of class members
115 case DefaultArgument:
116 // -- default arguments appearing in class definitions
117 return &ExprEvalContexts.back().getMangleNumberingContext();
118 }
119}
120
Douglas Gregordfca6f52012-02-13 22:00:16 +0000121CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
Douglas Gregorf54486a2012-04-04 17:40:10 +0000122 SourceRange IntroducerRange,
123 TypeSourceInfo *MethodType,
124 SourceLocation EndLoc,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000125 ArrayRef<ParmVarDecl *> Params) {
Douglas Gregordfca6f52012-02-13 22:00:16 +0000126 // C++11 [expr.prim.lambda]p5:
127 // The closure type for a lambda-expression has a public inline function
128 // call operator (13.5.4) whose parameters and return type are described by
129 // the lambda-expression's parameter-declaration-clause and
130 // trailing-return-type respectively.
131 DeclarationName MethodName
132 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
133 DeclarationNameLoc MethodNameLoc;
134 MethodNameLoc.CXXOperatorName.BeginOpNameLoc
135 = IntroducerRange.getBegin().getRawEncoding();
136 MethodNameLoc.CXXOperatorName.EndOpNameLoc
137 = IntroducerRange.getEnd().getRawEncoding();
138 CXXMethodDecl *Method
139 = CXXMethodDecl::Create(Context, Class, EndLoc,
140 DeclarationNameInfo(MethodName,
141 IntroducerRange.getBegin(),
142 MethodNameLoc),
143 MethodType->getType(), MethodType,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000144 SC_None,
145 /*isInline=*/true,
146 /*isConstExpr=*/false,
147 EndLoc);
148 Method->setAccess(AS_public);
149
150 // Temporarily set the lexical declaration context to the current
151 // context, so that the Scope stack matches the lexical nesting.
Douglas Gregorfa07ab52012-02-20 20:47:06 +0000152 Method->setLexicalDeclContext(CurContext);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000153
Douglas Gregorc6889e72012-02-14 22:28:59 +0000154 // Add parameters.
155 if (!Params.empty()) {
156 Method->setParams(Params);
157 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
158 const_cast<ParmVarDecl **>(Params.end()),
159 /*CheckParameterNames=*/false);
160
161 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
162 PEnd = Method->param_end();
163 P != PEnd; ++P)
164 (*P)->setOwningFunction(Method);
165 }
Richard Smithadb1d4c2012-07-22 23:45:10 +0000166
Eli Friedman07369dd2013-07-01 20:22:57 +0000167 Decl *ManglingContextDecl;
168 if (MangleNumberingContext *MCtx =
169 getCurrentMangleNumberContext(Class->getDeclContext(),
170 ManglingContextDecl)) {
171 unsigned ManglingNumber = MCtx->getManglingNumber(Method);
172 Class->setLambdaMangling(ManglingNumber, ManglingContextDecl);
Douglas Gregorf54486a2012-04-04 17:40:10 +0000173 }
174
Douglas Gregordfca6f52012-02-13 22:00:16 +0000175 return Method;
176}
177
178LambdaScopeInfo *Sema::enterLambdaScope(CXXMethodDecl *CallOperator,
179 SourceRange IntroducerRange,
180 LambdaCaptureDefault CaptureDefault,
181 bool ExplicitParams,
182 bool ExplicitResultType,
183 bool Mutable) {
184 PushLambdaScope(CallOperator->getParent(), CallOperator);
185 LambdaScopeInfo *LSI = getCurLambda();
186 if (CaptureDefault == LCD_ByCopy)
187 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
188 else if (CaptureDefault == LCD_ByRef)
189 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
190 LSI->IntroducerRange = IntroducerRange;
191 LSI->ExplicitParams = ExplicitParams;
192 LSI->Mutable = Mutable;
193
194 if (ExplicitResultType) {
195 LSI->ReturnType = CallOperator->getResultType();
Douglas Gregor53393f22012-02-14 21:20:44 +0000196
197 if (!LSI->ReturnType->isDependentType() &&
198 !LSI->ReturnType->isVoidType()) {
199 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
200 diag::err_lambda_incomplete_result)) {
201 // Do nothing.
Douglas Gregor53393f22012-02-14 21:20:44 +0000202 }
203 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000204 } else {
205 LSI->HasImplicitReturnType = true;
206 }
207
208 return LSI;
209}
210
211void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
212 LSI->finishedExplicitCaptures();
213}
214
Douglas Gregorc6889e72012-02-14 22:28:59 +0000215void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
Douglas Gregordfca6f52012-02-13 22:00:16 +0000216 // Introduce our parameters into the function scope
217 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
218 p < NumParams; ++p) {
219 ParmVarDecl *Param = CallOperator->getParamDecl(p);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000220
221 // If this has an identifier, add it to the scope stack.
222 if (CurScope && Param->getIdentifier()) {
223 CheckShadow(CurScope, Param);
224
225 PushOnScopeChains(Param, CurScope);
226 }
227 }
228}
229
John McCall41d01642013-03-09 00:54:31 +0000230/// If this expression is an enumerator-like expression of some type
231/// T, return the type T; otherwise, return null.
232///
233/// Pointer comparisons on the result here should always work because
234/// it's derived from either the parent of an EnumConstantDecl
235/// (i.e. the definition) or the declaration returned by
236/// EnumType::getDecl() (i.e. the definition).
237static EnumDecl *findEnumForBlockReturn(Expr *E) {
238 // An expression is an enumerator-like expression of type T if,
239 // ignoring parens and parens-like expressions:
240 E = E->IgnoreParens();
Jordan Rose7dd900e2012-07-02 21:19:23 +0000241
John McCall41d01642013-03-09 00:54:31 +0000242 // - it is an enumerator whose enum type is T or
243 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
244 if (EnumConstantDecl *D
245 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
246 return cast<EnumDecl>(D->getDeclContext());
247 }
248 return 0;
Jordan Rose7dd900e2012-07-02 21:19:23 +0000249 }
250
John McCall41d01642013-03-09 00:54:31 +0000251 // - it is a comma expression whose RHS is an enumerator-like
252 // expression of type T or
253 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
254 if (BO->getOpcode() == BO_Comma)
255 return findEnumForBlockReturn(BO->getRHS());
256 return 0;
257 }
Jordan Rose7dd900e2012-07-02 21:19:23 +0000258
John McCall41d01642013-03-09 00:54:31 +0000259 // - it is a statement-expression whose value expression is an
260 // enumerator-like expression of type T or
261 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
262 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
263 return findEnumForBlockReturn(last);
264 return 0;
265 }
266
267 // - it is a ternary conditional operator (not the GNU ?:
268 // extension) whose second and third operands are
269 // enumerator-like expressions of type T or
270 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
271 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
272 if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
273 return ED;
274 return 0;
275 }
276
277 // (implicitly:)
278 // - it is an implicit integral conversion applied to an
279 // enumerator-like expression of type T or
280 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall70133b52013-05-08 03:34:22 +0000281 // We can sometimes see integral conversions in valid
282 // enumerator-like expressions.
John McCall41d01642013-03-09 00:54:31 +0000283 if (ICE->getCastKind() == CK_IntegralCast)
284 return findEnumForBlockReturn(ICE->getSubExpr());
John McCall70133b52013-05-08 03:34:22 +0000285
286 // Otherwise, just rely on the type.
John McCall41d01642013-03-09 00:54:31 +0000287 }
288
289 // - it is an expression of that formal enum type.
290 if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
291 return ET->getDecl();
292 }
293
294 // Otherwise, nope.
295 return 0;
296}
297
298/// Attempt to find a type T for which the returned expression of the
299/// given statement is an enumerator-like expression of that type.
300static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
301 if (Expr *retValue = ret->getRetValue())
302 return findEnumForBlockReturn(retValue);
303 return 0;
304}
305
306/// Attempt to find a common type T for which all of the returned
307/// expressions in a block are enumerator-like expressions of that
308/// type.
309static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
310 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
311
312 // Try to find one for the first return.
313 EnumDecl *ED = findEnumForBlockReturn(*i);
314 if (!ED) return 0;
315
316 // Check that the rest of the returns have the same enum.
317 for (++i; i != e; ++i) {
318 if (findEnumForBlockReturn(*i) != ED)
319 return 0;
320 }
321
322 // Never infer an anonymous enum type.
323 if (!ED->hasNameForLinkage()) return 0;
324
325 return ED;
326}
327
328/// Adjust the given return statements so that they formally return
329/// the given type. It should require, at most, an IntegralCast.
330static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
331 QualType returnType) {
332 for (ArrayRef<ReturnStmt*>::iterator
333 i = returns.begin(), e = returns.end(); i != e; ++i) {
334 ReturnStmt *ret = *i;
335 Expr *retValue = ret->getRetValue();
336 if (S.Context.hasSameType(retValue->getType(), returnType))
337 continue;
338
339 // Right now we only support integral fixup casts.
340 assert(returnType->isIntegralOrUnscopedEnumerationType());
341 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
342
343 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
344
345 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
346 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast,
347 E, /*base path*/ 0, VK_RValue);
348 if (cleanups) {
349 cleanups->setSubExpr(E);
350 } else {
351 ret->setRetValue(E);
Jordan Rose7dd900e2012-07-02 21:19:23 +0000352 }
353 }
Jordan Rose7dd900e2012-07-02 21:19:23 +0000354}
355
356void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
357 assert(CSI.HasImplicitReturnType);
358
John McCall41d01642013-03-09 00:54:31 +0000359 // C++ Core Issue #975, proposed resolution:
360 // If a lambda-expression does not include a trailing-return-type,
361 // it is as if the trailing-return-type denotes the following type:
362 // - if there are no return statements in the compound-statement,
363 // or all return statements return either an expression of type
364 // void or no expression or braced-init-list, the type void;
365 // - otherwise, if all return statements return an expression
366 // and the types of the returned expressions after
367 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
368 // array-to-pointer conversion (4.2 [conv.array]), and
369 // function-to-pointer conversion (4.3 [conv.func]) are the
370 // same, that common type;
371 // - otherwise, the program is ill-formed.
372 //
373 // In addition, in blocks in non-C++ modes, if all of the return
374 // statements are enumerator-like expressions of some type T, where
375 // T has a name for linkage, then we infer the return type of the
376 // block to be that type.
377
Jordan Rose7dd900e2012-07-02 21:19:23 +0000378 // First case: no return statements, implicit void return type.
379 ASTContext &Ctx = getASTContext();
380 if (CSI.Returns.empty()) {
381 // It's possible there were simply no /valid/ return statements.
382 // In this case, the first one we found may have at least given us a type.
383 if (CSI.ReturnType.isNull())
384 CSI.ReturnType = Ctx.VoidTy;
385 return;
386 }
387
388 // Second case: at least one return statement has dependent type.
389 // Delay type checking until instantiation.
390 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
391 if (CSI.ReturnType->isDependentType())
392 return;
393
John McCall41d01642013-03-09 00:54:31 +0000394 // Try to apply the enum-fuzz rule.
395 if (!getLangOpts().CPlusPlus) {
396 assert(isa<BlockScopeInfo>(CSI));
397 const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
398 if (ED) {
399 CSI.ReturnType = Context.getTypeDeclType(ED);
400 adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
401 return;
402 }
403 }
404
Jordan Rose7dd900e2012-07-02 21:19:23 +0000405 // Third case: only one return statement. Don't bother doing extra work!
406 SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
407 E = CSI.Returns.end();
408 if (I+1 == E)
409 return;
410
411 // General case: many return statements.
412 // Check that they all have compatible return types.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000413
414 // We require the return types to strictly match here.
John McCall41d01642013-03-09 00:54:31 +0000415 // Note that we've already done the required promotions as part of
416 // processing the return statement.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000417 for (; I != E; ++I) {
418 const ReturnStmt *RS = *I;
419 const Expr *RetE = RS->getRetValue();
Jordan Rose7dd900e2012-07-02 21:19:23 +0000420
John McCall41d01642013-03-09 00:54:31 +0000421 QualType ReturnType = (RetE ? RetE->getType() : Context.VoidTy);
422 if (Context.hasSameType(ReturnType, CSI.ReturnType))
423 continue;
Jordan Rose7dd900e2012-07-02 21:19:23 +0000424
John McCall41d01642013-03-09 00:54:31 +0000425 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
426 // TODO: It's possible that the *first* return is the divergent one.
427 Diag(RS->getLocStart(),
428 diag::err_typecheck_missing_return_type_incompatible)
429 << ReturnType << CSI.ReturnType
430 << isa<LambdaScopeInfo>(CSI);
431 // Continue iterating so that we keep emitting diagnostics.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000432 }
433}
434
Richard Smith0d8e9642013-05-16 06:20:58 +0000435FieldDecl *Sema::checkInitCapture(SourceLocation Loc, bool ByRef,
436 IdentifierInfo *Id, Expr *InitExpr) {
437 LambdaScopeInfo *LSI = getCurLambda();
438
439 // C++1y [expr.prim.lambda]p11:
440 // The type of [the] member corresponds to the type of a hypothetical
441 // variable declaration of the form "auto init-capture;"
442 QualType DeductType = Context.getAutoDeductType();
443 TypeLocBuilder TLB;
444 TLB.pushTypeSpec(DeductType).setNameLoc(Loc);
445 if (ByRef) {
446 DeductType = BuildReferenceType(DeductType, true, Loc, Id);
447 assert(!DeductType.isNull() && "can't build reference to auto");
448 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
449 }
Eli Friedman44ee0a72013-06-07 20:31:48 +0000450 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
Richard Smith0d8e9642013-05-16 06:20:58 +0000451
452 InitializationKind InitKind = InitializationKind::CreateDefault(Loc);
453 Expr *Init = InitExpr;
454 if (ParenListExpr *Parens = dyn_cast<ParenListExpr>(Init)) {
455 if (Parens->getNumExprs() == 1) {
456 Init = Parens->getExpr(0);
457 InitKind = InitializationKind::CreateDirect(
458 Loc, Parens->getLParenLoc(), Parens->getRParenLoc());
459 } else {
460 // C++1y [dcl.spec.auto]p3:
461 // In an initializer of the form ( expression-list ), the
462 // expression-list shall be a single assignment-expression.
463 if (Parens->getNumExprs() == 0)
464 Diag(Parens->getLocStart(), diag::err_init_capture_no_expression)
465 << Id;
466 else if (Parens->getNumExprs() > 1)
467 Diag(Parens->getExpr(1)->getLocStart(),
468 diag::err_init_capture_multiple_expressions)
469 << Id;
470 return 0;
471 }
472 } else if (isa<InitListExpr>(Init))
473 // We do not need to distinguish between direct-list-initialization
474 // and copy-list-initialization here, because we will always deduce
475 // std::initializer_list<T>, and direct- and copy-list-initialization
476 // always behave the same for such a type.
477 // FIXME: We should model whether an '=' was present.
478 InitKind = InitializationKind::CreateDirectList(Loc);
479 else
480 InitKind = InitializationKind::CreateCopy(Loc, Loc);
481 QualType DeducedType;
Eli Friedman44ee0a72013-06-07 20:31:48 +0000482 if (DeduceAutoType(TSI, Init, DeducedType) == DAR_Failed) {
Richard Smith0d8e9642013-05-16 06:20:58 +0000483 if (isa<InitListExpr>(Init))
484 Diag(Loc, diag::err_init_capture_deduction_failure_from_init_list)
485 << Id << Init->getSourceRange();
486 else
487 Diag(Loc, diag::err_init_capture_deduction_failure)
488 << Id << Init->getType() << Init->getSourceRange();
489 }
490 if (DeducedType.isNull())
491 return 0;
492
493 // [...] a non-static data member named by the identifier is declared in
494 // the closure type. This member is not a bit-field and not mutable.
495 // Core issue: the member is (probably...) public.
496 FieldDecl *NewFD = CheckFieldDecl(
Eli Friedman44ee0a72013-06-07 20:31:48 +0000497 Id, DeducedType, TSI, LSI->Lambda,
Richard Smith0d8e9642013-05-16 06:20:58 +0000498 Loc, /*Mutable*/ false, /*BitWidth*/ 0, ICIS_NoInit,
499 Loc, AS_public, /*PrevDecl*/ 0, /*Declarator*/ 0);
500 LSI->Lambda->addDecl(NewFD);
501
502 if (CurContext->isDependentContext()) {
503 LSI->addInitCapture(NewFD, InitExpr);
504 } else {
505 InitializedEntity Entity = InitializedEntity::InitializeMember(NewFD);
506 InitializationSequence InitSeq(*this, Entity, InitKind, Init);
507 if (!InitSeq.Diagnose(*this, Entity, InitKind, Init)) {
508 ExprResult InitResult = InitSeq.Perform(*this, Entity, InitKind, Init);
509 if (!InitResult.isInvalid())
510 LSI->addInitCapture(NewFD, InitResult.take());
511 }
512 }
513
514 return NewFD;
515}
516
Douglas Gregordfca6f52012-02-13 22:00:16 +0000517void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
518 Declarator &ParamInfo,
519 Scope *CurScope) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000520 // Determine if we're within a context where we know that the lambda will
521 // be dependent, because there are template parameters in scope.
522 bool KnownDependent = false;
523 if (Scope *TmplScope = CurScope->getTemplateParamParent())
524 if (!TmplScope->decl_empty())
525 KnownDependent = true;
526
Douglas Gregordfca6f52012-02-13 22:00:16 +0000527 // Determine the signature of the call operator.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000528 TypeSourceInfo *MethodTyInfo;
529 bool ExplicitParams = true;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000530 bool ExplicitResultType = true;
Richard Smith612409e2012-07-25 03:56:55 +0000531 bool ContainsUnexpandedParameterPack = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000532 SourceLocation EndLoc;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000533 SmallVector<ParmVarDecl *, 8> Params;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000534 if (ParamInfo.getNumTypeObjects() == 0) {
535 // C++11 [expr.prim.lambda]p4:
536 // If a lambda-expression does not include a lambda-declarator, it is as
537 // if the lambda-declarator were ().
538 FunctionProtoType::ExtProtoInfo EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +0000539 EPI.HasTrailingReturn = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000540 EPI.TypeQuals |= DeclSpec::TQ_const;
Dmitri Gribenko55431692013-05-05 00:41:58 +0000541 QualType MethodTy = Context.getFunctionType(Context.DependentTy, None,
Jordan Rosebea522f2013-03-08 21:51:21 +0000542 EPI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000543 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
544 ExplicitParams = false;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000545 ExplicitResultType = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000546 EndLoc = Intro.Range.getEnd();
547 } else {
548 assert(ParamInfo.isFunctionDeclarator() &&
549 "lambda-declarator is a function");
550 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
551
552 // C++11 [expr.prim.lambda]p5:
553 // This function call operator is declared const (9.3.1) if and only if
554 // the lambda-expression's parameter-declaration-clause is not followed
555 // by mutable. It is neither virtual nor declared volatile. [...]
556 if (!FTI.hasMutableQualifier())
557 FTI.TypeQuals |= DeclSpec::TQ_const;
558
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000559 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000560 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000561 EndLoc = ParamInfo.getSourceRange().getEnd();
Douglas Gregordfca6f52012-02-13 22:00:16 +0000562
563 ExplicitResultType
564 = MethodTyInfo->getType()->getAs<FunctionType>()->getResultType()
565 != Context.DependentTy;
Richard Smith3bc22262012-08-30 13:13:20 +0000566
Eli Friedman7c3c6bc2012-09-20 01:40:23 +0000567 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
568 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
569 // Empty arg list, don't push any params.
570 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
571 } else {
572 Params.reserve(FTI.NumArgs);
573 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
574 Params.push_back(cast<ParmVarDecl>(FTI.ArgInfo[i].Param));
575 }
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000576
577 // Check for unexpanded parameter packs in the method type.
Richard Smith612409e2012-07-25 03:56:55 +0000578 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
579 ContainsUnexpandedParameterPack = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000580 }
Eli Friedman8da8a662012-09-19 01:18:11 +0000581
582 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
583 KnownDependent);
584
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000585 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregorc6889e72012-02-14 22:28:59 +0000586 MethodTyInfo, EndLoc, Params);
587
588 if (ExplicitParams)
589 CheckCXXDefaultArguments(Method);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000590
Bill Wendlingad017fa2012-12-20 19:22:21 +0000591 // Attributes on the lambda apply to the method.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000592 ProcessDeclAttributes(CurScope, Method, ParamInfo);
593
Douglas Gregor503384f2012-02-09 00:47:04 +0000594 // Introduce the function call operator as the current declaration context.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000595 PushDeclContext(CurScope, Method);
596
597 // Introduce the lambda scope.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000598 LambdaScopeInfo *LSI
599 = enterLambdaScope(Method, Intro.Range, Intro.Default, ExplicitParams,
600 ExplicitResultType,
David Blaikie4ef832f2012-08-10 00:55:35 +0000601 !Method->isConst());
Richard Smith0d8e9642013-05-16 06:20:58 +0000602
603 // Distinct capture names, for diagnostics.
604 llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
605
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000606 // Handle explicit captures.
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000607 SourceLocation PrevCaptureLoc
608 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000609 for (SmallVector<LambdaCapture, 4>::const_iterator
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000610 C = Intro.Captures.begin(),
611 E = Intro.Captures.end();
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000612 C != E;
613 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000614 if (C->Kind == LCK_This) {
615 // C++11 [expr.prim.lambda]p8:
616 // An identifier or this shall not appear more than once in a
617 // lambda-capture.
618 if (LSI->isCXXThisCaptured()) {
619 Diag(C->Loc, diag::err_capture_more_than_once)
620 << "'this'"
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000621 << SourceRange(LSI->getCXXThisCapture().getLocation())
622 << FixItHint::CreateRemoval(
623 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000624 continue;
625 }
626
627 // C++11 [expr.prim.lambda]p8:
628 // If a lambda-capture includes a capture-default that is =, the
629 // lambda-capture shall not contain this [...].
630 if (Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000631 Diag(C->Loc, diag::err_this_capture_with_copy_default)
632 << FixItHint::CreateRemoval(
633 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000634 continue;
635 }
636
637 // C++11 [expr.prim.lambda]p12:
638 // If this is captured by a local lambda expression, its nearest
639 // enclosing function shall be a non-static member function.
640 QualType ThisCaptureType = getCurrentThisType();
641 if (ThisCaptureType.isNull()) {
642 Diag(C->Loc, diag::err_this_capture) << true;
643 continue;
644 }
645
646 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
647 continue;
648 }
649
Richard Smith0d8e9642013-05-16 06:20:58 +0000650 assert(C->Id && "missing identifier for capture");
651
Richard Smith0a664b82013-05-09 21:36:41 +0000652 if (C->Init.isInvalid())
653 continue;
654 if (C->Init.isUsable()) {
Richard Smith0d8e9642013-05-16 06:20:58 +0000655 // C++11 [expr.prim.lambda]p8:
656 // An identifier or this shall not appear more than once in a
657 // lambda-capture.
658 if (!CaptureNames.insert(C->Id))
659 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
660
661 if (C->Init.get()->containsUnexpandedParameterPack())
662 ContainsUnexpandedParameterPack = true;
663
664 FieldDecl *NewFD = checkInitCapture(C->Loc, C->Kind == LCK_ByRef,
665 C->Id, C->Init.take());
666 // C++1y [expr.prim.lambda]p11:
667 // Within the lambda-expression's lambda-declarator and
668 // compound-statement, the identifier in the init-capture
669 // hides any declaration of the same name in scopes enclosing
670 // the lambda-expression.
671 if (NewFD)
672 PushOnScopeChains(NewFD, CurScope, false);
Richard Smith0a664b82013-05-09 21:36:41 +0000673 continue;
674 }
675
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000676 // C++11 [expr.prim.lambda]p8:
677 // If a lambda-capture includes a capture-default that is &, the
678 // identifiers in the lambda-capture shall not be preceded by &.
679 // If a lambda-capture includes a capture-default that is =, [...]
680 // each identifier it contains shall be preceded by &.
681 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000682 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
683 << FixItHint::CreateRemoval(
684 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000685 continue;
686 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000687 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
688 << FixItHint::CreateRemoval(
689 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000690 continue;
691 }
692
Richard Smith0d8e9642013-05-16 06:20:58 +0000693 // C++11 [expr.prim.lambda]p10:
694 // The identifiers in a capture-list are looked up using the usual
695 // rules for unqualified name lookup (3.4.1)
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000696 DeclarationNameInfo Name(C->Id, C->Loc);
697 LookupResult R(*this, Name, LookupOrdinaryName);
698 LookupName(R, CurScope);
699 if (R.isAmbiguous())
700 continue;
701 if (R.empty()) {
702 // FIXME: Disable corrections that would add qualification?
703 CXXScopeSpec ScopeSpec;
704 DeclFilterCCC<VarDecl> Validator;
705 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
706 continue;
707 }
708
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000709 VarDecl *Var = R.getAsSingle<VarDecl>();
Richard Smith0d8e9642013-05-16 06:20:58 +0000710
711 // C++11 [expr.prim.lambda]p8:
712 // An identifier or this shall not appear more than once in a
713 // lambda-capture.
714 if (!CaptureNames.insert(C->Id)) {
715 if (Var && LSI->isCaptured(Var)) {
716 Diag(C->Loc, diag::err_capture_more_than_once)
717 << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
718 << FixItHint::CreateRemoval(
719 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
720 } else
721 // Previous capture was an init-capture: no fixit.
722 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
723 continue;
724 }
725
726 // C++11 [expr.prim.lambda]p10:
727 // [...] each such lookup shall find a variable with automatic storage
728 // duration declared in the reaching scope of the local lambda expression.
729 // Note that the 'reaching scope' check happens in tryCaptureVariable().
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000730 if (!Var) {
731 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
732 continue;
733 }
734
Eli Friedman9cd5b242012-09-18 21:11:30 +0000735 // Ignore invalid decls; they'll just confuse the code later.
736 if (Var->isInvalidDecl())
737 continue;
738
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000739 if (!Var->hasLocalStorage()) {
740 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
741 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
742 continue;
743 }
744
Douglas Gregora7365242012-02-14 19:27:52 +0000745 // C++11 [expr.prim.lambda]p23:
746 // A capture followed by an ellipsis is a pack expansion (14.5.3).
747 SourceLocation EllipsisLoc;
748 if (C->EllipsisLoc.isValid()) {
749 if (Var->isParameterPack()) {
750 EllipsisLoc = C->EllipsisLoc;
751 } else {
752 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
753 << SourceRange(C->Loc);
754
755 // Just ignore the ellipsis.
756 }
757 } else if (Var->isParameterPack()) {
Richard Smith612409e2012-07-25 03:56:55 +0000758 ContainsUnexpandedParameterPack = true;
Douglas Gregora7365242012-02-14 19:27:52 +0000759 }
760
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000761 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
762 TryCapture_ExplicitByVal;
Douglas Gregor999713e2012-02-18 09:37:24 +0000763 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000764 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000765 finishLambdaExplicitCaptures(LSI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000766
Richard Smith612409e2012-07-25 03:56:55 +0000767 LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
768
Douglas Gregorc6889e72012-02-14 22:28:59 +0000769 // Add lambda parameters into scope.
770 addLambdaParameters(Method, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000771
Douglas Gregordfca6f52012-02-13 22:00:16 +0000772 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor503384f2012-02-09 00:47:04 +0000773 // cleanups from the enclosing full-expression.
774 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000775}
776
Douglas Gregordfca6f52012-02-13 22:00:16 +0000777void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
778 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000779 // Leave the expression-evaluation context.
780 DiscardCleanupsInEvaluationContext();
781 PopExpressionEvaluationContext();
782
783 // Leave the context of the lambda.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000784 if (!IsInstantiation)
785 PopDeclContext();
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000786
787 // Finalize the lambda.
788 LambdaScopeInfo *LSI = getCurLambda();
789 CXXRecordDecl *Class = LSI->Lambda;
790 Class->setInvalidDecl();
David Blaikie262bc182012-04-30 02:36:29 +0000791 SmallVector<Decl*, 4> Fields;
792 for (RecordDecl::field_iterator i = Class->field_begin(),
793 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +0000794 Fields.push_back(*i);
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000795 ActOnFields(0, Class->getLocation(), Class, Fields,
796 SourceLocation(), SourceLocation(), 0);
797 CheckCompletedCXXClass(Class);
798
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000799 PopFunctionScopeInfo();
800}
801
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000802/// \brief Add a lambda's conversion to function pointer, as described in
803/// C++11 [expr.prim.lambda]p6.
804static void addFunctionPointerConversion(Sema &S,
805 SourceRange IntroducerRange,
806 CXXRecordDecl *Class,
807 CXXMethodDecl *CallOperator) {
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000808 // Add the conversion to function pointer.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000809 const FunctionProtoType *Proto
810 = CallOperator->getType()->getAs<FunctionProtoType>();
811 QualType FunctionPtrTy;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000812 QualType FunctionTy;
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000813 {
814 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
815 ExtInfo.TypeQuals = 0;
Reid Kleckner0567a792013-06-10 20:51:09 +0000816 FunctionTy = S.Context.getFunctionType(Proto->getResultType(),
817 Proto->getArgTypes(), ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000818 FunctionPtrTy = S.Context.getPointerType(FunctionTy);
819 }
820
821 FunctionProtoType::ExtProtoInfo ExtInfo;
822 ExtInfo.TypeQuals = Qualifiers::Const;
Jordan Rosebea522f2013-03-08 21:51:21 +0000823 QualType ConvTy =
Dmitri Gribenko55431692013-05-05 00:41:58 +0000824 S.Context.getFunctionType(FunctionPtrTy, None, ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000825
826 SourceLocation Loc = IntroducerRange.getBegin();
827 DeclarationName Name
828 = S.Context.DeclarationNames.getCXXConversionFunctionName(
829 S.Context.getCanonicalType(FunctionPtrTy));
830 DeclarationNameLoc NameLoc;
831 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
832 Loc);
833 CXXConversionDecl *Conversion
834 = CXXConversionDecl::Create(S.Context, Class, Loc,
835 DeclarationNameInfo(Name, Loc, NameLoc),
836 ConvTy,
837 S.Context.getTrivialTypeSourceInfo(ConvTy,
838 Loc),
Eli Friedman38fa9612013-06-13 19:39:48 +0000839 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000840 /*isConstexpr=*/false,
841 CallOperator->getBody()->getLocEnd());
842 Conversion->setAccess(AS_public);
843 Conversion->setImplicit(true);
844 Class->addDecl(Conversion);
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000845
846 // Add a non-static member function "__invoke" that will be the result of
847 // the conversion.
848 Name = &S.Context.Idents.get("__invoke");
849 CXXMethodDecl *Invoke
850 = CXXMethodDecl::Create(S.Context, Class, Loc,
851 DeclarationNameInfo(Name, Loc), FunctionTy,
852 CallOperator->getTypeSourceInfo(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000853 SC_Static, /*IsInline=*/true,
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000854 /*IsConstexpr=*/false,
855 CallOperator->getBody()->getLocEnd());
856 SmallVector<ParmVarDecl *, 4> InvokeParams;
857 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
858 ParmVarDecl *From = CallOperator->getParamDecl(I);
859 InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
860 From->getLocStart(),
861 From->getLocation(),
862 From->getIdentifier(),
863 From->getType(),
864 From->getTypeSourceInfo(),
865 From->getStorageClass(),
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000866 /*DefaultArg=*/0));
867 }
868 Invoke->setParams(InvokeParams);
869 Invoke->setAccess(AS_private);
870 Invoke->setImplicit(true);
871 Class->addDecl(Invoke);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000872}
873
Douglas Gregorc2956e52012-02-15 22:08:38 +0000874/// \brief Add a lambda's conversion to block pointer.
875static void addBlockPointerConversion(Sema &S,
876 SourceRange IntroducerRange,
877 CXXRecordDecl *Class,
878 CXXMethodDecl *CallOperator) {
879 const FunctionProtoType *Proto
880 = CallOperator->getType()->getAs<FunctionProtoType>();
881 QualType BlockPtrTy;
882 {
883 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
884 ExtInfo.TypeQuals = 0;
Reid Kleckner0567a792013-06-10 20:51:09 +0000885 QualType FunctionTy = S.Context.getFunctionType(
886 Proto->getResultType(), Proto->getArgTypes(), ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +0000887 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
888 }
889
890 FunctionProtoType::ExtProtoInfo ExtInfo;
891 ExtInfo.TypeQuals = Qualifiers::Const;
Dmitri Gribenko55431692013-05-05 00:41:58 +0000892 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +0000893
894 SourceLocation Loc = IntroducerRange.getBegin();
895 DeclarationName Name
896 = S.Context.DeclarationNames.getCXXConversionFunctionName(
897 S.Context.getCanonicalType(BlockPtrTy));
898 DeclarationNameLoc NameLoc;
899 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
900 CXXConversionDecl *Conversion
901 = CXXConversionDecl::Create(S.Context, Class, Loc,
902 DeclarationNameInfo(Name, Loc, NameLoc),
903 ConvTy,
904 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
Eli Friedman95099ef2013-06-13 20:56:27 +0000905 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregorc2956e52012-02-15 22:08:38 +0000906 /*isConstexpr=*/false,
907 CallOperator->getBody()->getLocEnd());
908 Conversion->setAccess(AS_public);
909 Conversion->setImplicit(true);
910 Class->addDecl(Conversion);
911}
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000912
Douglas Gregordfca6f52012-02-13 22:00:16 +0000913ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000914 Scope *CurScope,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000915 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000916 // Collect information from the lambda scope.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000917 SmallVector<LambdaExpr::Capture, 4> Captures;
918 SmallVector<Expr *, 4> CaptureInits;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000919 LambdaCaptureDefault CaptureDefault;
920 CXXRecordDecl *Class;
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000921 CXXMethodDecl *CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000922 SourceRange IntroducerRange;
923 bool ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000924 bool ExplicitResultType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000925 bool LambdaExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +0000926 bool ContainsUnexpandedParameterPack;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000927 SmallVector<VarDecl *, 4> ArrayIndexVars;
928 SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000929 {
930 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000931 CallOperator = LSI->CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000932 Class = LSI->Lambda;
933 IntroducerRange = LSI->IntroducerRange;
934 ExplicitParams = LSI->ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000935 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000936 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +0000937 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000938 ArrayIndexVars.swap(LSI->ArrayIndexVars);
939 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
940
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000941 // Translate captures.
942 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
943 LambdaScopeInfo::Capture From = LSI->Captures[I];
944 assert(!From.isBlockCapture() && "Cannot capture __block variables");
945 bool IsImplicit = I >= LSI->NumExplicitCaptures;
946
947 // Handle 'this' capture.
948 if (From.isThisCapture()) {
949 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
950 IsImplicit,
951 LCK_This));
952 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
953 getCurrentThisType(),
954 /*isImplicit=*/true));
955 continue;
956 }
957
Richard Smith0d8e9642013-05-16 06:20:58 +0000958 if (From.isInitCapture()) {
959 Captures.push_back(LambdaExpr::Capture(From.getInitCaptureField()));
960 CaptureInits.push_back(From.getInitExpr());
961 continue;
962 }
963
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000964 VarDecl *Var = From.getVariable();
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000965 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
966 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregora7365242012-02-14 19:27:52 +0000967 Kind, Var, From.getEllipsisLoc()));
Richard Smith0d8e9642013-05-16 06:20:58 +0000968 CaptureInits.push_back(From.getInitExpr());
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000969 }
970
971 switch (LSI->ImpCaptureStyle) {
972 case CapturingScopeInfo::ImpCap_None:
973 CaptureDefault = LCD_None;
974 break;
975
976 case CapturingScopeInfo::ImpCap_LambdaByval:
977 CaptureDefault = LCD_ByCopy;
978 break;
979
Tareq A. Siraj6afcf882013-04-16 19:37:38 +0000980 case CapturingScopeInfo::ImpCap_CapturedRegion:
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000981 case CapturingScopeInfo::ImpCap_LambdaByref:
982 CaptureDefault = LCD_ByRef;
983 break;
984
985 case CapturingScopeInfo::ImpCap_Block:
986 llvm_unreachable("block capture in lambda");
987 break;
988 }
989
Douglas Gregor54042f12012-02-09 10:18:50 +0000990 // C++11 [expr.prim.lambda]p4:
991 // If a lambda-expression does not include a
992 // trailing-return-type, it is as if the trailing-return-type
993 // denotes the following type:
994 // FIXME: Assumes current resolution to core issue 975.
995 if (LSI->HasImplicitReturnType) {
Jordan Rose7dd900e2012-07-02 21:19:23 +0000996 deduceClosureReturnType(*LSI);
997
Douglas Gregor54042f12012-02-09 10:18:50 +0000998 // - if there are no return statements in the
999 // compound-statement, or all return statements return
1000 // either an expression of type void or no expression or
1001 // braced-init-list, the type void;
1002 if (LSI->ReturnType.isNull()) {
1003 LSI->ReturnType = Context.VoidTy;
Douglas Gregor54042f12012-02-09 10:18:50 +00001004 }
1005
1006 // Create a function type with the inferred return type.
1007 const FunctionProtoType *Proto
1008 = CallOperator->getType()->getAs<FunctionProtoType>();
Reid Kleckner0567a792013-06-10 20:51:09 +00001009 QualType FunctionTy = Context.getFunctionType(
1010 LSI->ReturnType, Proto->getArgTypes(), Proto->getExtProtoInfo());
Douglas Gregor54042f12012-02-09 10:18:50 +00001011 CallOperator->setType(FunctionTy);
1012 }
1013
Douglas Gregor215e4e12012-02-12 17:34:23 +00001014 // C++ [expr.prim.lambda]p7:
1015 // The lambda-expression's compound-statement yields the
1016 // function-body (8.4) of the function call operator [...].
Douglas Gregordfca6f52012-02-13 22:00:16 +00001017 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor215e4e12012-02-12 17:34:23 +00001018 CallOperator->setLexicalDeclContext(Class);
1019 Class->addDecl(CallOperator);
Douglas Gregorb09ab8c2012-02-21 20:05:31 +00001020 PopExpressionEvaluationContext();
Douglas Gregor215e4e12012-02-12 17:34:23 +00001021
Douglas Gregorb5559712012-02-10 16:13:20 +00001022 // C++11 [expr.prim.lambda]p6:
1023 // The closure type for a lambda-expression with no lambda-capture
1024 // has a public non-virtual non-explicit const conversion function
1025 // to pointer to function having the same parameter and return
1026 // types as the closure type's function call operator.
Douglas Gregorc25d1c92012-02-15 22:00:51 +00001027 if (Captures.empty() && CaptureDefault == LCD_None)
1028 addFunctionPointerConversion(*this, IntroducerRange, Class,
1029 CallOperator);
Douglas Gregor503384f2012-02-09 00:47:04 +00001030
Douglas Gregorc2956e52012-02-15 22:08:38 +00001031 // Objective-C++:
1032 // The closure type for a lambda-expression has a public non-virtual
1033 // non-explicit const conversion function to a block pointer having the
1034 // same parameter and return types as the closure type's function call
1035 // operator.
David Blaikie4e4d0842012-03-11 07:00:24 +00001036 if (getLangOpts().Blocks && getLangOpts().ObjC1)
Douglas Gregorc2956e52012-02-15 22:08:38 +00001037 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
1038
Douglas Gregorb5559712012-02-10 16:13:20 +00001039 // Finalize the lambda class.
David Blaikie262bc182012-04-30 02:36:29 +00001040 SmallVector<Decl*, 4> Fields;
1041 for (RecordDecl::field_iterator i = Class->field_begin(),
1042 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +00001043 Fields.push_back(*i);
Douglas Gregorb5559712012-02-10 16:13:20 +00001044 ActOnFields(0, Class->getLocation(), Class, Fields,
1045 SourceLocation(), SourceLocation(), 0);
1046 CheckCompletedCXXClass(Class);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001047 }
1048
Douglas Gregor503384f2012-02-09 00:47:04 +00001049 if (LambdaExprNeedsCleanups)
1050 ExprNeedsCleanups = true;
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00001051
Douglas Gregore2c59132012-02-09 08:14:43 +00001052 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
1053 CaptureDefault, Captures,
Douglas Gregordfca6f52012-02-13 22:00:16 +00001054 ExplicitParams, ExplicitResultType,
1055 CaptureInits, ArrayIndexVars,
Richard Smith612409e2012-07-25 03:56:55 +00001056 ArrayIndexStarts, Body->getLocEnd(),
1057 ContainsUnexpandedParameterPack);
Douglas Gregore2c59132012-02-09 08:14:43 +00001058
1059 // C++11 [expr.prim.lambda]p2:
1060 // A lambda-expression shall not appear in an unevaluated operand
1061 // (Clause 5).
Douglas Gregord5387e82012-02-14 00:00:48 +00001062 if (!CurContext->isDependentContext()) {
1063 switch (ExprEvalContexts.back().Context) {
1064 case Unevaluated:
John McCallaeeacf72013-05-03 00:10:13 +00001065 case UnevaluatedAbstract:
Douglas Gregord5387e82012-02-14 00:00:48 +00001066 // We don't actually diagnose this case immediately, because we
1067 // could be within a context where we might find out later that
1068 // the expression is potentially evaluated (e.g., for typeid).
1069 ExprEvalContexts.back().Lambdas.push_back(Lambda);
1070 break;
Douglas Gregore2c59132012-02-09 08:14:43 +00001071
Douglas Gregord5387e82012-02-14 00:00:48 +00001072 case ConstantEvaluated:
1073 case PotentiallyEvaluated:
1074 case PotentiallyEvaluatedIfUsed:
1075 break;
1076 }
Douglas Gregore2c59132012-02-09 08:14:43 +00001077 }
Douglas Gregord5387e82012-02-14 00:00:48 +00001078
Douglas Gregor503384f2012-02-09 00:47:04 +00001079 return MaybeBindToTemporary(Lambda);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001080}
Eli Friedman23f02672012-03-01 04:01:32 +00001081
1082ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
1083 SourceLocation ConvLocation,
1084 CXXConversionDecl *Conv,
1085 Expr *Src) {
1086 // Make sure that the lambda call operator is marked used.
1087 CXXRecordDecl *Lambda = Conv->getParent();
1088 CXXMethodDecl *CallOperator
1089 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00001090 Lambda->lookup(
1091 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Eli Friedman23f02672012-03-01 04:01:32 +00001092 CallOperator->setReferenced();
1093 CallOperator->setUsed();
1094
1095 ExprResult Init = PerformCopyInitialization(
1096 InitializedEntity::InitializeBlock(ConvLocation,
1097 Src->getType(),
1098 /*NRVO=*/false),
1099 CurrentLocation, Src);
1100 if (!Init.isInvalid())
1101 Init = ActOnFinishFullExpr(Init.take());
1102
1103 if (Init.isInvalid())
1104 return ExprError();
1105
1106 // Create the new block to be returned.
1107 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
1108
1109 // Set the type information.
1110 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
1111 Block->setIsVariadic(CallOperator->isVariadic());
1112 Block->setBlockMissingReturnType(false);
1113
1114 // Add parameters.
1115 SmallVector<ParmVarDecl *, 4> BlockParams;
1116 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1117 ParmVarDecl *From = CallOperator->getParamDecl(I);
1118 BlockParams.push_back(ParmVarDecl::Create(Context, Block,
1119 From->getLocStart(),
1120 From->getLocation(),
1121 From->getIdentifier(),
1122 From->getType(),
1123 From->getTypeSourceInfo(),
1124 From->getStorageClass(),
Eli Friedman23f02672012-03-01 04:01:32 +00001125 /*DefaultArg=*/0));
1126 }
1127 Block->setParams(BlockParams);
1128
1129 Block->setIsConversionFromLambda(true);
1130
1131 // Add capture. The capture uses a fake variable, which doesn't correspond
1132 // to any actual memory location. However, the initializer copy-initializes
1133 // the lambda object.
1134 TypeSourceInfo *CapVarTSI =
1135 Context.getTrivialTypeSourceInfo(Src->getType());
1136 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1137 ConvLocation, 0,
1138 Src->getType(), CapVarTSI,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001139 SC_None);
Eli Friedman23f02672012-03-01 04:01:32 +00001140 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
1141 /*Nested=*/false, /*Copy=*/Init.take());
1142 Block->setCaptures(Context, &Capture, &Capture + 1,
1143 /*CapturesCXXThis=*/false);
1144
1145 // Add a fake function body to the block. IR generation is responsible
1146 // for filling in the actual body, which cannot be expressed as an AST.
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00001147 Block->setBody(new (Context) CompoundStmt(ConvLocation));
Eli Friedman23f02672012-03-01 04:01:32 +00001148
1149 // Create the block literal expression.
1150 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1151 ExprCleanupObjects.push_back(Block);
1152 ExprNeedsCleanups = true;
1153
1154 return BuildBlock;
1155}