blob: ec69ef8ed0afa6f81bc7b45b9b8286ee1485dd81 [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"
Reid Kleckner942f9fe2013-09-10 20:14:30 +000015#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000016#include "clang/Lex/Preprocessor.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000017#include "clang/Sema/Initialization.h"
18#include "clang/Sema/Lookup.h"
Douglas Gregor5878cbc2012-02-21 04:17:39 +000019#include "clang/Sema/Scope.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000020#include "clang/Sema/ScopeInfo.h"
21#include "clang/Sema/SemaInternal.h"
Richard Smith0d8e9642013-05-16 06:20:58 +000022#include "TypeLocBuilder.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000023using namespace clang;
24using namespace sema;
25
Douglas Gregorf4b7de12012-02-21 19:11:17 +000026CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange,
Eli Friedman8da8a662012-09-19 01:18:11 +000027 TypeSourceInfo *Info,
Douglas Gregorf4b7de12012-02-21 19:11:17 +000028 bool KnownDependent) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +000029 DeclContext *DC = CurContext;
30 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
31 DC = DC->getParent();
Douglas Gregordfca6f52012-02-13 22:00:16 +000032
Douglas Gregore2a7ad02012-02-08 21:18:48 +000033 // Start constructing the lambda class.
Eli Friedman8da8a662012-09-19 01:18:11 +000034 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info,
Douglas Gregorf4b7de12012-02-21 19:11:17 +000035 IntroducerRange.getBegin(),
36 KnownDependent);
Douglas Gregorfa07ab52012-02-20 20:47:06 +000037 DC->addDecl(Class);
Douglas Gregordfca6f52012-02-13 22:00:16 +000038
39 return Class;
40}
Douglas Gregore2a7ad02012-02-08 21:18:48 +000041
Douglas Gregorf54486a2012-04-04 17:40:10 +000042/// \brief Determine whether the given context is or is enclosed in an inline
43/// function.
44static bool isInInlineFunction(const DeclContext *DC) {
45 while (!DC->isFileContext()) {
46 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
47 if (FD->isInlined())
48 return true;
49
50 DC = DC->getLexicalParent();
51 }
52
53 return false;
54}
55
Eli Friedman07369dd2013-07-01 20:22:57 +000056MangleNumberingContext *
Eli Friedman5e867c82013-07-10 00:30:46 +000057Sema::getCurrentMangleNumberContext(const DeclContext *DC,
Eli Friedman07369dd2013-07-01 20:22:57 +000058 Decl *&ManglingContextDecl) {
59 // Compute the context for allocating mangling numbers in the current
60 // expression, if the ABI requires them.
61 ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
62
63 enum ContextKind {
64 Normal,
65 DefaultArgument,
66 DataMember,
67 StaticDataMember
68 } Kind = Normal;
69
70 // Default arguments of member function parameters that appear in a class
71 // definition, as well as the initializers of data members, receive special
72 // treatment. Identify them.
73 if (ManglingContextDecl) {
74 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
75 if (const DeclContext *LexicalDC
76 = Param->getDeclContext()->getLexicalParent())
77 if (LexicalDC->isRecord())
78 Kind = DefaultArgument;
79 } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
80 if (Var->getDeclContext()->isRecord())
81 Kind = StaticDataMember;
82 } else if (isa<FieldDecl>(ManglingContextDecl)) {
83 Kind = DataMember;
84 }
85 }
86
87 // Itanium ABI [5.1.7]:
88 // In the following contexts [...] the one-definition rule requires closure
89 // types in different translation units to "correspond":
90 bool IsInNonspecializedTemplate =
91 !ActiveTemplateInstantiations.empty() || CurContext->isDependentContext();
92 switch (Kind) {
93 case Normal:
94 // -- the bodies of non-exported nonspecialized template functions
95 // -- the bodies of inline functions
96 if ((IsInNonspecializedTemplate &&
97 !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
98 isInInlineFunction(CurContext)) {
99 ManglingContextDecl = 0;
100 return &Context.getManglingNumberContext(DC);
101 }
102
103 ManglingContextDecl = 0;
104 return 0;
105
106 case StaticDataMember:
107 // -- the initializers of nonspecialized static members of template classes
108 if (!IsInNonspecializedTemplate) {
109 ManglingContextDecl = 0;
110 return 0;
111 }
112 // Fall through to get the current context.
113
114 case DataMember:
115 // -- the in-class initializers of class members
116 case DefaultArgument:
117 // -- default arguments appearing in class definitions
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000118 return &ExprEvalContexts.back().getMangleNumberingContext(Context);
Eli Friedman07369dd2013-07-01 20:22:57 +0000119 }
Andy Gibbsce9cd912013-07-02 16:01:56 +0000120
121 llvm_unreachable("unexpected context");
Eli Friedman07369dd2013-07-01 20:22:57 +0000122}
123
Reid Kleckner942f9fe2013-09-10 20:14:30 +0000124MangleNumberingContext &
125Sema::ExpressionEvaluationContextRecord::getMangleNumberingContext(
126 ASTContext &Ctx) {
127 assert(ManglingContextDecl && "Need to have a context declaration");
128 if (!MangleNumbering)
129 MangleNumbering = Ctx.createMangleNumberingContext();
130 return *MangleNumbering;
131}
132
Douglas Gregordfca6f52012-02-13 22:00:16 +0000133CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
Richard Smith41d09582013-09-25 05:02:54 +0000134 SourceRange IntroducerRange,
135 TypeSourceInfo *MethodTypeInfo,
136 SourceLocation EndLoc,
137 ArrayRef<ParmVarDecl *> Params) {
138 QualType MethodType = MethodTypeInfo->getType();
139
140 // If a lambda appears in a dependent context and has an 'auto' return type,
141 // deduce it to a dependent type.
142 // FIXME: Generic lambda call operators should also get this treatment.
143 if (Class->isDependentContext()) {
144 const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
145 QualType Result = FPT->getResultType();
146 if (Result->isUndeducedType()) {
147 Result = SubstAutoType(Result, Context.DependentTy);
148 MethodType = Context.getFunctionType(Result, FPT->getArgTypes(),
149 FPT->getExtProtoInfo());
150 }
151 }
152
Douglas Gregordfca6f52012-02-13 22:00:16 +0000153 // C++11 [expr.prim.lambda]p5:
154 // The closure type for a lambda-expression has a public inline function
155 // call operator (13.5.4) whose parameters and return type are described by
156 // the lambda-expression's parameter-declaration-clause and
157 // trailing-return-type respectively.
158 DeclarationName MethodName
159 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
160 DeclarationNameLoc MethodNameLoc;
161 MethodNameLoc.CXXOperatorName.BeginOpNameLoc
162 = IntroducerRange.getBegin().getRawEncoding();
163 MethodNameLoc.CXXOperatorName.EndOpNameLoc
164 = IntroducerRange.getEnd().getRawEncoding();
165 CXXMethodDecl *Method
166 = CXXMethodDecl::Create(Context, Class, EndLoc,
167 DeclarationNameInfo(MethodName,
168 IntroducerRange.getBegin(),
169 MethodNameLoc),
Richard Smith41d09582013-09-25 05:02:54 +0000170 MethodType, MethodTypeInfo,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000171 SC_None,
172 /*isInline=*/true,
173 /*isConstExpr=*/false,
174 EndLoc);
175 Method->setAccess(AS_public);
176
177 // Temporarily set the lexical declaration context to the current
178 // context, so that the Scope stack matches the lexical nesting.
Douglas Gregorfa07ab52012-02-20 20:47:06 +0000179 Method->setLexicalDeclContext(CurContext);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000180
Douglas Gregorc6889e72012-02-14 22:28:59 +0000181 // Add parameters.
182 if (!Params.empty()) {
183 Method->setParams(Params);
184 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
185 const_cast<ParmVarDecl **>(Params.end()),
186 /*CheckParameterNames=*/false);
187
188 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
189 PEnd = Method->param_end();
190 P != PEnd; ++P)
191 (*P)->setOwningFunction(Method);
192 }
Richard Smithadb1d4c2012-07-22 23:45:10 +0000193
Eli Friedman07369dd2013-07-01 20:22:57 +0000194 Decl *ManglingContextDecl;
195 if (MangleNumberingContext *MCtx =
196 getCurrentMangleNumberContext(Class->getDeclContext(),
197 ManglingContextDecl)) {
198 unsigned ManglingNumber = MCtx->getManglingNumber(Method);
199 Class->setLambdaMangling(ManglingNumber, ManglingContextDecl);
Douglas Gregorf54486a2012-04-04 17:40:10 +0000200 }
201
Douglas Gregordfca6f52012-02-13 22:00:16 +0000202 return Method;
203}
204
Manuel Klimek152b4e42013-08-22 12:12:24 +0000205LambdaScopeInfo *Sema::enterLambdaScope(CXXMethodDecl *CallOperator,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000206 SourceRange IntroducerRange,
207 LambdaCaptureDefault CaptureDefault,
James Dennettf68af642013-08-09 23:08:25 +0000208 SourceLocation CaptureDefaultLoc,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000209 bool ExplicitParams,
210 bool ExplicitResultType,
211 bool Mutable) {
Manuel Klimek152b4e42013-08-22 12:12:24 +0000212 PushLambdaScope(CallOperator->getParent(), CallOperator);
213 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregordfca6f52012-02-13 22:00:16 +0000214 if (CaptureDefault == LCD_ByCopy)
215 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
216 else if (CaptureDefault == LCD_ByRef)
217 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
James Dennettf68af642013-08-09 23:08:25 +0000218 LSI->CaptureDefaultLoc = CaptureDefaultLoc;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000219 LSI->IntroducerRange = IntroducerRange;
220 LSI->ExplicitParams = ExplicitParams;
221 LSI->Mutable = Mutable;
222
223 if (ExplicitResultType) {
224 LSI->ReturnType = CallOperator->getResultType();
Douglas Gregor53393f22012-02-14 21:20:44 +0000225
226 if (!LSI->ReturnType->isDependentType() &&
227 !LSI->ReturnType->isVoidType()) {
228 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
229 diag::err_lambda_incomplete_result)) {
230 // Do nothing.
Douglas Gregor53393f22012-02-14 21:20:44 +0000231 }
232 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000233 } else {
234 LSI->HasImplicitReturnType = true;
235 }
Manuel Klimek152b4e42013-08-22 12:12:24 +0000236
237 return LSI;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000238}
239
240void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
241 LSI->finishedExplicitCaptures();
242}
243
Douglas Gregorc6889e72012-02-14 22:28:59 +0000244void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
Douglas Gregordfca6f52012-02-13 22:00:16 +0000245 // Introduce our parameters into the function scope
246 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
247 p < NumParams; ++p) {
248 ParmVarDecl *Param = CallOperator->getParamDecl(p);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000249
250 // If this has an identifier, add it to the scope stack.
251 if (CurScope && Param->getIdentifier()) {
252 CheckShadow(CurScope, Param);
253
254 PushOnScopeChains(Param, CurScope);
255 }
256 }
257}
258
John McCall41d01642013-03-09 00:54:31 +0000259/// If this expression is an enumerator-like expression of some type
260/// T, return the type T; otherwise, return null.
261///
262/// Pointer comparisons on the result here should always work because
263/// it's derived from either the parent of an EnumConstantDecl
264/// (i.e. the definition) or the declaration returned by
265/// EnumType::getDecl() (i.e. the definition).
266static EnumDecl *findEnumForBlockReturn(Expr *E) {
267 // An expression is an enumerator-like expression of type T if,
268 // ignoring parens and parens-like expressions:
269 E = E->IgnoreParens();
Jordan Rose7dd900e2012-07-02 21:19:23 +0000270
John McCall41d01642013-03-09 00:54:31 +0000271 // - it is an enumerator whose enum type is T or
272 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
273 if (EnumConstantDecl *D
274 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
275 return cast<EnumDecl>(D->getDeclContext());
276 }
277 return 0;
Jordan Rose7dd900e2012-07-02 21:19:23 +0000278 }
279
John McCall41d01642013-03-09 00:54:31 +0000280 // - it is a comma expression whose RHS is an enumerator-like
281 // expression of type T or
282 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
283 if (BO->getOpcode() == BO_Comma)
284 return findEnumForBlockReturn(BO->getRHS());
285 return 0;
286 }
Jordan Rose7dd900e2012-07-02 21:19:23 +0000287
John McCall41d01642013-03-09 00:54:31 +0000288 // - it is a statement-expression whose value expression is an
289 // enumerator-like expression of type T or
290 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
291 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
292 return findEnumForBlockReturn(last);
293 return 0;
294 }
295
296 // - it is a ternary conditional operator (not the GNU ?:
297 // extension) whose second and third operands are
298 // enumerator-like expressions of type T or
299 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
300 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
301 if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
302 return ED;
303 return 0;
304 }
305
306 // (implicitly:)
307 // - it is an implicit integral conversion applied to an
308 // enumerator-like expression of type T or
309 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
John McCall70133b52013-05-08 03:34:22 +0000310 // We can sometimes see integral conversions in valid
311 // enumerator-like expressions.
John McCall41d01642013-03-09 00:54:31 +0000312 if (ICE->getCastKind() == CK_IntegralCast)
313 return findEnumForBlockReturn(ICE->getSubExpr());
John McCall70133b52013-05-08 03:34:22 +0000314
315 // Otherwise, just rely on the type.
John McCall41d01642013-03-09 00:54:31 +0000316 }
317
318 // - it is an expression of that formal enum type.
319 if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
320 return ET->getDecl();
321 }
322
323 // Otherwise, nope.
324 return 0;
325}
326
327/// Attempt to find a type T for which the returned expression of the
328/// given statement is an enumerator-like expression of that type.
329static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) {
330 if (Expr *retValue = ret->getRetValue())
331 return findEnumForBlockReturn(retValue);
332 return 0;
333}
334
335/// Attempt to find a common type T for which all of the returned
336/// expressions in a block are enumerator-like expressions of that
337/// type.
338static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) {
339 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
340
341 // Try to find one for the first return.
342 EnumDecl *ED = findEnumForBlockReturn(*i);
343 if (!ED) return 0;
344
345 // Check that the rest of the returns have the same enum.
346 for (++i; i != e; ++i) {
347 if (findEnumForBlockReturn(*i) != ED)
348 return 0;
349 }
350
351 // Never infer an anonymous enum type.
352 if (!ED->hasNameForLinkage()) return 0;
353
354 return ED;
355}
356
357/// Adjust the given return statements so that they formally return
358/// the given type. It should require, at most, an IntegralCast.
359static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns,
360 QualType returnType) {
361 for (ArrayRef<ReturnStmt*>::iterator
362 i = returns.begin(), e = returns.end(); i != e; ++i) {
363 ReturnStmt *ret = *i;
364 Expr *retValue = ret->getRetValue();
365 if (S.Context.hasSameType(retValue->getType(), returnType))
366 continue;
367
368 // Right now we only support integral fixup casts.
369 assert(returnType->isIntegralOrUnscopedEnumerationType());
370 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
371
372 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
373
374 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
375 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast,
376 E, /*base path*/ 0, VK_RValue);
377 if (cleanups) {
378 cleanups->setSubExpr(E);
379 } else {
380 ret->setRetValue(E);
Jordan Rose7dd900e2012-07-02 21:19:23 +0000381 }
382 }
Jordan Rose7dd900e2012-07-02 21:19:23 +0000383}
384
385void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) {
Manuel Klimek152b4e42013-08-22 12:12:24 +0000386 assert(CSI.HasImplicitReturnType);
Jordan Rose7dd900e2012-07-02 21:19:23 +0000387
John McCall41d01642013-03-09 00:54:31 +0000388 // C++ Core Issue #975, proposed resolution:
389 // If a lambda-expression does not include a trailing-return-type,
390 // it is as if the trailing-return-type denotes the following type:
391 // - if there are no return statements in the compound-statement,
392 // or all return statements return either an expression of type
393 // void or no expression or braced-init-list, the type void;
394 // - otherwise, if all return statements return an expression
395 // and the types of the returned expressions after
396 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
397 // array-to-pointer conversion (4.2 [conv.array]), and
398 // function-to-pointer conversion (4.3 [conv.func]) are the
399 // same, that common type;
400 // - otherwise, the program is ill-formed.
401 //
402 // In addition, in blocks in non-C++ modes, if all of the return
403 // statements are enumerator-like expressions of some type T, where
404 // T has a name for linkage, then we infer the return type of the
405 // block to be that type.
406
Jordan Rose7dd900e2012-07-02 21:19:23 +0000407 // First case: no return statements, implicit void return type.
408 ASTContext &Ctx = getASTContext();
409 if (CSI.Returns.empty()) {
410 // It's possible there were simply no /valid/ return statements.
411 // In this case, the first one we found may have at least given us a type.
412 if (CSI.ReturnType.isNull())
413 CSI.ReturnType = Ctx.VoidTy;
414 return;
415 }
416
417 // Second case: at least one return statement has dependent type.
418 // Delay type checking until instantiation.
419 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
Manuel Klimek152b4e42013-08-22 12:12:24 +0000420 if (CSI.ReturnType->isDependentType())
Jordan Rose7dd900e2012-07-02 21:19:23 +0000421 return;
422
John McCall41d01642013-03-09 00:54:31 +0000423 // Try to apply the enum-fuzz rule.
424 if (!getLangOpts().CPlusPlus) {
425 assert(isa<BlockScopeInfo>(CSI));
426 const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns);
427 if (ED) {
428 CSI.ReturnType = Context.getTypeDeclType(ED);
429 adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType);
430 return;
431 }
432 }
433
Jordan Rose7dd900e2012-07-02 21:19:23 +0000434 // Third case: only one return statement. Don't bother doing extra work!
435 SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(),
436 E = CSI.Returns.end();
437 if (I+1 == E)
438 return;
439
440 // General case: many return statements.
441 // Check that they all have compatible return types.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000442
443 // We require the return types to strictly match here.
John McCall41d01642013-03-09 00:54:31 +0000444 // Note that we've already done the required promotions as part of
445 // processing the return statement.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000446 for (; I != E; ++I) {
447 const ReturnStmt *RS = *I;
448 const Expr *RetE = RS->getRetValue();
Jordan Rose7dd900e2012-07-02 21:19:23 +0000449
John McCall41d01642013-03-09 00:54:31 +0000450 QualType ReturnType = (RetE ? RetE->getType() : Context.VoidTy);
451 if (Context.hasSameType(ReturnType, CSI.ReturnType))
452 continue;
Jordan Rose7dd900e2012-07-02 21:19:23 +0000453
John McCall41d01642013-03-09 00:54:31 +0000454 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
455 // TODO: It's possible that the *first* return is the divergent one.
456 Diag(RS->getLocStart(),
457 diag::err_typecheck_missing_return_type_incompatible)
458 << ReturnType << CSI.ReturnType
459 << isa<LambdaScopeInfo>(CSI);
460 // Continue iterating so that we keep emitting diagnostics.
Jordan Rose7dd900e2012-07-02 21:19:23 +0000461 }
462}
463
Richard Smith0d8e9642013-05-16 06:20:58 +0000464FieldDecl *Sema::checkInitCapture(SourceLocation Loc, bool ByRef,
465 IdentifierInfo *Id, Expr *InitExpr) {
466 LambdaScopeInfo *LSI = getCurLambda();
467
468 // C++1y [expr.prim.lambda]p11:
469 // The type of [the] member corresponds to the type of a hypothetical
470 // variable declaration of the form "auto init-capture;"
471 QualType DeductType = Context.getAutoDeductType();
472 TypeLocBuilder TLB;
473 TLB.pushTypeSpec(DeductType).setNameLoc(Loc);
474 if (ByRef) {
475 DeductType = BuildReferenceType(DeductType, true, Loc, Id);
476 assert(!DeductType.isNull() && "can't build reference to auto");
477 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
478 }
Eli Friedman44ee0a72013-06-07 20:31:48 +0000479 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
Richard Smith0d8e9642013-05-16 06:20:58 +0000480
481 InitializationKind InitKind = InitializationKind::CreateDefault(Loc);
482 Expr *Init = InitExpr;
483 if (ParenListExpr *Parens = dyn_cast<ParenListExpr>(Init)) {
484 if (Parens->getNumExprs() == 1) {
485 Init = Parens->getExpr(0);
486 InitKind = InitializationKind::CreateDirect(
487 Loc, Parens->getLParenLoc(), Parens->getRParenLoc());
488 } else {
489 // C++1y [dcl.spec.auto]p3:
490 // In an initializer of the form ( expression-list ), the
491 // expression-list shall be a single assignment-expression.
492 if (Parens->getNumExprs() == 0)
493 Diag(Parens->getLocStart(), diag::err_init_capture_no_expression)
494 << Id;
495 else if (Parens->getNumExprs() > 1)
496 Diag(Parens->getExpr(1)->getLocStart(),
497 diag::err_init_capture_multiple_expressions)
498 << Id;
499 return 0;
500 }
501 } else if (isa<InitListExpr>(Init))
502 // We do not need to distinguish between direct-list-initialization
503 // and copy-list-initialization here, because we will always deduce
504 // std::initializer_list<T>, and direct- and copy-list-initialization
505 // always behave the same for such a type.
506 // FIXME: We should model whether an '=' was present.
507 InitKind = InitializationKind::CreateDirectList(Loc);
508 else
509 InitKind = InitializationKind::CreateCopy(Loc, Loc);
510 QualType DeducedType;
Eli Friedman44ee0a72013-06-07 20:31:48 +0000511 if (DeduceAutoType(TSI, Init, DeducedType) == DAR_Failed) {
Richard Smith0d8e9642013-05-16 06:20:58 +0000512 if (isa<InitListExpr>(Init))
513 Diag(Loc, diag::err_init_capture_deduction_failure_from_init_list)
514 << Id << Init->getSourceRange();
515 else
516 Diag(Loc, diag::err_init_capture_deduction_failure)
517 << Id << Init->getType() << Init->getSourceRange();
518 }
519 if (DeducedType.isNull())
520 return 0;
521
522 // [...] a non-static data member named by the identifier is declared in
523 // the closure type. This member is not a bit-field and not mutable.
524 // Core issue: the member is (probably...) public.
525 FieldDecl *NewFD = CheckFieldDecl(
Eli Friedman44ee0a72013-06-07 20:31:48 +0000526 Id, DeducedType, TSI, LSI->Lambda,
Richard Smith0d8e9642013-05-16 06:20:58 +0000527 Loc, /*Mutable*/ false, /*BitWidth*/ 0, ICIS_NoInit,
528 Loc, AS_public, /*PrevDecl*/ 0, /*Declarator*/ 0);
529 LSI->Lambda->addDecl(NewFD);
530
531 if (CurContext->isDependentContext()) {
532 LSI->addInitCapture(NewFD, InitExpr);
533 } else {
534 InitializedEntity Entity = InitializedEntity::InitializeMember(NewFD);
535 InitializationSequence InitSeq(*this, Entity, InitKind, Init);
536 if (!InitSeq.Diagnose(*this, Entity, InitKind, Init)) {
537 ExprResult InitResult = InitSeq.Perform(*this, Entity, InitKind, Init);
538 if (!InitResult.isInvalid())
539 LSI->addInitCapture(NewFD, InitResult.take());
540 }
541 }
542
543 return NewFD;
544}
545
Douglas Gregordfca6f52012-02-13 22:00:16 +0000546void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
Manuel Klimek152b4e42013-08-22 12:12:24 +0000547 Declarator &ParamInfo,
548 Scope *CurScope) {
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000549 // Determine if we're within a context where we know that the lambda will
550 // be dependent, because there are template parameters in scope.
551 bool KnownDependent = false;
Manuel Klimek152b4e42013-08-22 12:12:24 +0000552 if (Scope *TmplScope = CurScope->getTemplateParamParent())
553 if (!TmplScope->decl_empty())
Douglas Gregorf4b7de12012-02-21 19:11:17 +0000554 KnownDependent = true;
Manuel Klimek152b4e42013-08-22 12:12:24 +0000555
Douglas Gregordfca6f52012-02-13 22:00:16 +0000556 // Determine the signature of the call operator.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000557 TypeSourceInfo *MethodTyInfo;
558 bool ExplicitParams = true;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000559 bool ExplicitResultType = true;
Richard Smith612409e2012-07-25 03:56:55 +0000560 bool ContainsUnexpandedParameterPack = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000561 SourceLocation EndLoc;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000562 SmallVector<ParmVarDecl *, 8> Params;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000563 if (ParamInfo.getNumTypeObjects() == 0) {
564 // C++11 [expr.prim.lambda]p4:
565 // If a lambda-expression does not include a lambda-declarator, it is as
566 // if the lambda-declarator were ().
Reid Kleckneref072032013-08-27 23:08:25 +0000567 FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention(
568 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Richard Smitheefb3d52012-02-10 09:58:53 +0000569 EPI.HasTrailingReturn = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000570 EPI.TypeQuals |= DeclSpec::TQ_const;
Richard Smith41d09582013-09-25 05:02:54 +0000571 // C++1y [expr.prim.lambda]:
572 // The lambda return type is 'auto', which is replaced by the
573 // trailing-return type if provided and/or deduced from 'return'
574 // statements
575 // We don't do this before C++1y, because we don't support deduced return
576 // types there.
577 QualType DefaultTypeForNoTrailingReturn =
578 getLangOpts().CPlusPlus1y ? Context.getAutoDeductType()
579 : Context.DependentTy;
580 QualType MethodTy =
581 Context.getFunctionType(DefaultTypeForNoTrailingReturn, None, EPI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000582 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
583 ExplicitParams = false;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000584 ExplicitResultType = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000585 EndLoc = Intro.Range.getEnd();
586 } else {
587 assert(ParamInfo.isFunctionDeclarator() &&
588 "lambda-declarator is a function");
589 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
Richard Smith41d09582013-09-25 05:02:54 +0000590
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000591 // C++11 [expr.prim.lambda]p5:
592 // This function call operator is declared const (9.3.1) if and only if
593 // the lambda-expression's parameter-declaration-clause is not followed
594 // by mutable. It is neither virtual nor declared volatile. [...]
595 if (!FTI.hasMutableQualifier())
596 FTI.TypeQuals |= DeclSpec::TQ_const;
Richard Smith41d09582013-09-25 05:02:54 +0000597
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000598 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000599 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000600 EndLoc = ParamInfo.getSourceRange().getEnd();
Richard Smith41d09582013-09-25 05:02:54 +0000601
602 ExplicitResultType = FTI.hasTrailingReturnType();
Manuel Klimek152b4e42013-08-22 12:12:24 +0000603
Eli Friedman7c3c6bc2012-09-20 01:40:23 +0000604 if (FTI.NumArgs == 1 && !FTI.isVariadic && FTI.ArgInfo[0].Ident == 0 &&
605 cast<ParmVarDecl>(FTI.ArgInfo[0].Param)->getType()->isVoidType()) {
606 // Empty arg list, don't push any params.
607 checkVoidParamDecl(cast<ParmVarDecl>(FTI.ArgInfo[0].Param));
608 } else {
609 Params.reserve(FTI.NumArgs);
610 for (unsigned i = 0, e = FTI.NumArgs; i != e; ++i)
611 Params.push_back(cast<ParmVarDecl>(FTI.ArgInfo[i].Param));
612 }
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000613
614 // Check for unexpanded parameter packs in the method type.
Richard Smith612409e2012-07-25 03:56:55 +0000615 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
616 ContainsUnexpandedParameterPack = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000617 }
Eli Friedman8da8a662012-09-19 01:18:11 +0000618
619 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo,
620 KnownDependent);
621
Douglas Gregor03f1eb02012-06-15 16:59:29 +0000622 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregorc6889e72012-02-14 22:28:59 +0000623 MethodTyInfo, EndLoc, Params);
Manuel Klimek152b4e42013-08-22 12:12:24 +0000624
Douglas Gregorc6889e72012-02-14 22:28:59 +0000625 if (ExplicitParams)
626 CheckCXXDefaultArguments(Method);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000627
Bill Wendlingad017fa2012-12-20 19:22:21 +0000628 // Attributes on the lambda apply to the method.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000629 ProcessDeclAttributes(CurScope, Method, ParamInfo);
630
Douglas Gregor503384f2012-02-09 00:47:04 +0000631 // Introduce the function call operator as the current declaration context.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000632 PushDeclContext(CurScope, Method);
633
Manuel Klimek152b4e42013-08-22 12:12:24 +0000634 // Introduce the lambda scope.
635 LambdaScopeInfo *LSI
636 = enterLambdaScope(Method,
James Dennettf68af642013-08-09 23:08:25 +0000637 Intro.Range,
638 Intro.Default, Intro.DefaultLoc,
639 ExplicitParams,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000640 ExplicitResultType,
David Blaikie4ef832f2012-08-10 00:55:35 +0000641 !Method->isConst());
Richard Smith0d8e9642013-05-16 06:20:58 +0000642
643 // Distinct capture names, for diagnostics.
644 llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
645
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000646 // Handle explicit captures.
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000647 SourceLocation PrevCaptureLoc
648 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Craig Topper09d19ef2013-07-04 03:08:24 +0000649 for (SmallVectorImpl<LambdaCapture>::const_iterator
650 C = Intro.Captures.begin(),
651 E = Intro.Captures.end();
652 C != E;
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000653 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000654 if (C->Kind == LCK_This) {
655 // C++11 [expr.prim.lambda]p8:
656 // An identifier or this shall not appear more than once in a
657 // lambda-capture.
658 if (LSI->isCXXThisCaptured()) {
659 Diag(C->Loc, diag::err_capture_more_than_once)
660 << "'this'"
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000661 << SourceRange(LSI->getCXXThisCapture().getLocation())
662 << FixItHint::CreateRemoval(
663 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000664 continue;
665 }
666
667 // C++11 [expr.prim.lambda]p8:
668 // If a lambda-capture includes a capture-default that is =, the
669 // lambda-capture shall not contain this [...].
670 if (Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000671 Diag(C->Loc, diag::err_this_capture_with_copy_default)
672 << FixItHint::CreateRemoval(
673 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000674 continue;
675 }
676
677 // C++11 [expr.prim.lambda]p12:
678 // If this is captured by a local lambda expression, its nearest
679 // enclosing function shall be a non-static member function.
680 QualType ThisCaptureType = getCurrentThisType();
681 if (ThisCaptureType.isNull()) {
682 Diag(C->Loc, diag::err_this_capture) << true;
683 continue;
684 }
685
686 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
687 continue;
688 }
689
Richard Smith0d8e9642013-05-16 06:20:58 +0000690 assert(C->Id && "missing identifier for capture");
691
Richard Smith0a664b82013-05-09 21:36:41 +0000692 if (C->Init.isInvalid())
693 continue;
694 if (C->Init.isUsable()) {
Richard Smith0d8e9642013-05-16 06:20:58 +0000695 // C++11 [expr.prim.lambda]p8:
696 // An identifier or this shall not appear more than once in a
697 // lambda-capture.
698 if (!CaptureNames.insert(C->Id))
699 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
700
701 if (C->Init.get()->containsUnexpandedParameterPack())
702 ContainsUnexpandedParameterPack = true;
703
704 FieldDecl *NewFD = checkInitCapture(C->Loc, C->Kind == LCK_ByRef,
705 C->Id, C->Init.take());
706 // C++1y [expr.prim.lambda]p11:
707 // Within the lambda-expression's lambda-declarator and
708 // compound-statement, the identifier in the init-capture
709 // hides any declaration of the same name in scopes enclosing
710 // the lambda-expression.
711 if (NewFD)
712 PushOnScopeChains(NewFD, CurScope, false);
Richard Smith0a664b82013-05-09 21:36:41 +0000713 continue;
714 }
715
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000716 // C++11 [expr.prim.lambda]p8:
717 // If a lambda-capture includes a capture-default that is &, the
718 // identifiers in the lambda-capture shall not be preceded by &.
719 // If a lambda-capture includes a capture-default that is =, [...]
720 // each identifier it contains shall be preceded by &.
721 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000722 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
723 << FixItHint::CreateRemoval(
724 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000725 continue;
726 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000727 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
728 << FixItHint::CreateRemoval(
729 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000730 continue;
731 }
732
Richard Smith0d8e9642013-05-16 06:20:58 +0000733 // C++11 [expr.prim.lambda]p10:
734 // The identifiers in a capture-list are looked up using the usual
735 // rules for unqualified name lookup (3.4.1)
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000736 DeclarationNameInfo Name(C->Id, C->Loc);
737 LookupResult R(*this, Name, LookupOrdinaryName);
738 LookupName(R, CurScope);
739 if (R.isAmbiguous())
740 continue;
741 if (R.empty()) {
742 // FIXME: Disable corrections that would add qualification?
743 CXXScopeSpec ScopeSpec;
744 DeclFilterCCC<VarDecl> Validator;
745 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
746 continue;
747 }
748
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000749 VarDecl *Var = R.getAsSingle<VarDecl>();
Richard Smith0d8e9642013-05-16 06:20:58 +0000750
751 // C++11 [expr.prim.lambda]p8:
752 // An identifier or this shall not appear more than once in a
753 // lambda-capture.
754 if (!CaptureNames.insert(C->Id)) {
755 if (Var && LSI->isCaptured(Var)) {
756 Diag(C->Loc, diag::err_capture_more_than_once)
757 << C->Id << SourceRange(LSI->getCapture(Var).getLocation())
758 << FixItHint::CreateRemoval(
759 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
760 } else
761 // Previous capture was an init-capture: no fixit.
762 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
763 continue;
764 }
765
766 // C++11 [expr.prim.lambda]p10:
767 // [...] each such lookup shall find a variable with automatic storage
768 // duration declared in the reaching scope of the local lambda expression.
769 // Note that the 'reaching scope' check happens in tryCaptureVariable().
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000770 if (!Var) {
771 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
772 continue;
773 }
774
Eli Friedman9cd5b242012-09-18 21:11:30 +0000775 // Ignore invalid decls; they'll just confuse the code later.
776 if (Var->isInvalidDecl())
777 continue;
778
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000779 if (!Var->hasLocalStorage()) {
780 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
781 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
782 continue;
783 }
784
Douglas Gregora7365242012-02-14 19:27:52 +0000785 // C++11 [expr.prim.lambda]p23:
786 // A capture followed by an ellipsis is a pack expansion (14.5.3).
787 SourceLocation EllipsisLoc;
788 if (C->EllipsisLoc.isValid()) {
789 if (Var->isParameterPack()) {
790 EllipsisLoc = C->EllipsisLoc;
791 } else {
792 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
793 << SourceRange(C->Loc);
794
795 // Just ignore the ellipsis.
796 }
797 } else if (Var->isParameterPack()) {
Richard Smith612409e2012-07-25 03:56:55 +0000798 ContainsUnexpandedParameterPack = true;
Douglas Gregora7365242012-02-14 19:27:52 +0000799 }
800
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000801 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
802 TryCapture_ExplicitByVal;
Douglas Gregor999713e2012-02-18 09:37:24 +0000803 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000804 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000805 finishLambdaExplicitCaptures(LSI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000806
Richard Smith612409e2012-07-25 03:56:55 +0000807 LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
808
Douglas Gregorc6889e72012-02-14 22:28:59 +0000809 // Add lambda parameters into scope.
810 addLambdaParameters(Method, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000811
Douglas Gregordfca6f52012-02-13 22:00:16 +0000812 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor503384f2012-02-09 00:47:04 +0000813 // cleanups from the enclosing full-expression.
814 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000815}
816
Douglas Gregordfca6f52012-02-13 22:00:16 +0000817void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
818 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000819 // Leave the expression-evaluation context.
820 DiscardCleanupsInEvaluationContext();
821 PopExpressionEvaluationContext();
822
823 // Leave the context of the lambda.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000824 if (!IsInstantiation)
825 PopDeclContext();
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000826
827 // Finalize the lambda.
828 LambdaScopeInfo *LSI = getCurLambda();
829 CXXRecordDecl *Class = LSI->Lambda;
830 Class->setInvalidDecl();
David Blaikie262bc182012-04-30 02:36:29 +0000831 SmallVector<Decl*, 4> Fields;
832 for (RecordDecl::field_iterator i = Class->field_begin(),
833 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +0000834 Fields.push_back(*i);
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000835 ActOnFields(0, Class->getLocation(), Class, Fields,
836 SourceLocation(), SourceLocation(), 0);
837 CheckCompletedCXXClass(Class);
838
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000839 PopFunctionScopeInfo();
840}
841
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000842/// \brief Add a lambda's conversion to function pointer, as described in
843/// C++11 [expr.prim.lambda]p6.
844static void addFunctionPointerConversion(Sema &S,
845 SourceRange IntroducerRange,
846 CXXRecordDecl *Class,
847 CXXMethodDecl *CallOperator) {
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000848 // Add the conversion to function pointer.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000849 const FunctionProtoType *Proto
850 = CallOperator->getType()->getAs<FunctionProtoType>();
851 QualType FunctionPtrTy;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000852 QualType FunctionTy;
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000853 {
854 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
Reid Kleckneref072032013-08-27 23:08:25 +0000855 CallingConv CC = S.Context.getDefaultCallingConvention(
856 Proto->isVariadic(), /*IsCXXMethod=*/false);
857 ExtInfo.ExtInfo = ExtInfo.ExtInfo.withCallingConv(CC);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000858 ExtInfo.TypeQuals = 0;
Reid Kleckner0567a792013-06-10 20:51:09 +0000859 FunctionTy = S.Context.getFunctionType(Proto->getResultType(),
860 Proto->getArgTypes(), ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000861 FunctionPtrTy = S.Context.getPointerType(FunctionTy);
862 }
Reid Kleckneref072032013-08-27 23:08:25 +0000863
864 FunctionProtoType::ExtProtoInfo ExtInfo(S.Context.getDefaultCallingConvention(
865 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000866 ExtInfo.TypeQuals = Qualifiers::Const;
Reid Kleckneref072032013-08-27 23:08:25 +0000867 QualType ConvTy = S.Context.getFunctionType(FunctionPtrTy, None, ExtInfo);
868
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000869 SourceLocation Loc = IntroducerRange.getBegin();
870 DeclarationName Name
871 = S.Context.DeclarationNames.getCXXConversionFunctionName(
872 S.Context.getCanonicalType(FunctionPtrTy));
873 DeclarationNameLoc NameLoc;
874 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
875 Loc);
876 CXXConversionDecl *Conversion
877 = CXXConversionDecl::Create(S.Context, Class, Loc,
878 DeclarationNameInfo(Name, Loc, NameLoc),
879 ConvTy,
880 S.Context.getTrivialTypeSourceInfo(ConvTy,
881 Loc),
Eli Friedman38fa9612013-06-13 19:39:48 +0000882 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000883 /*isConstexpr=*/false,
884 CallOperator->getBody()->getLocEnd());
885 Conversion->setAccess(AS_public);
886 Conversion->setImplicit(true);
887 Class->addDecl(Conversion);
Manuel Klimek152b4e42013-08-22 12:12:24 +0000888
889 // Add a non-static member function "__invoke" that will be the result of
890 // the conversion.
891 Name = &S.Context.Idents.get("__invoke");
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000892 CXXMethodDecl *Invoke
893 = CXXMethodDecl::Create(S.Context, Class, Loc,
894 DeclarationNameInfo(Name, Loc), FunctionTy,
895 CallOperator->getTypeSourceInfo(),
Rafael Espindolad2615cc2013-04-03 19:27:57 +0000896 SC_Static, /*IsInline=*/true,
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000897 /*IsConstexpr=*/false,
898 CallOperator->getBody()->getLocEnd());
899 SmallVector<ParmVarDecl *, 4> InvokeParams;
900 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
901 ParmVarDecl *From = CallOperator->getParamDecl(I);
902 InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
903 From->getLocStart(),
904 From->getLocation(),
905 From->getIdentifier(),
906 From->getType(),
907 From->getTypeSourceInfo(),
908 From->getStorageClass(),
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000909 /*DefaultArg=*/0));
910 }
911 Invoke->setParams(InvokeParams);
912 Invoke->setAccess(AS_private);
913 Invoke->setImplicit(true);
914 Class->addDecl(Invoke);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000915}
916
Douglas Gregorc2956e52012-02-15 22:08:38 +0000917/// \brief Add a lambda's conversion to block pointer.
918static void addBlockPointerConversion(Sema &S,
919 SourceRange IntroducerRange,
920 CXXRecordDecl *Class,
921 CXXMethodDecl *CallOperator) {
922 const FunctionProtoType *Proto
923 = CallOperator->getType()->getAs<FunctionProtoType>();
924 QualType BlockPtrTy;
925 {
926 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
927 ExtInfo.TypeQuals = 0;
Reid Kleckner0567a792013-06-10 20:51:09 +0000928 QualType FunctionTy = S.Context.getFunctionType(
929 Proto->getResultType(), Proto->getArgTypes(), ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +0000930 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
931 }
Reid Kleckneref072032013-08-27 23:08:25 +0000932
933 FunctionProtoType::ExtProtoInfo ExtInfo(S.Context.getDefaultCallingConvention(
934 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
Douglas Gregorc2956e52012-02-15 22:08:38 +0000935 ExtInfo.TypeQuals = Qualifiers::Const;
Dmitri Gribenko55431692013-05-05 00:41:58 +0000936 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ExtInfo);
Douglas Gregorc2956e52012-02-15 22:08:38 +0000937
938 SourceLocation Loc = IntroducerRange.getBegin();
939 DeclarationName Name
940 = S.Context.DeclarationNames.getCXXConversionFunctionName(
941 S.Context.getCanonicalType(BlockPtrTy));
942 DeclarationNameLoc NameLoc;
943 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
944 CXXConversionDecl *Conversion
945 = CXXConversionDecl::Create(S.Context, Class, Loc,
946 DeclarationNameInfo(Name, Loc, NameLoc),
947 ConvTy,
948 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
Eli Friedman95099ef2013-06-13 20:56:27 +0000949 /*isInline=*/true, /*isExplicit=*/false,
Douglas Gregorc2956e52012-02-15 22:08:38 +0000950 /*isConstexpr=*/false,
951 CallOperator->getBody()->getLocEnd());
952 Conversion->setAccess(AS_public);
953 Conversion->setImplicit(true);
954 Class->addDecl(Conversion);
955}
Douglas Gregor5878cbc2012-02-21 04:17:39 +0000956
Douglas Gregordfca6f52012-02-13 22:00:16 +0000957ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000958 Scope *CurScope,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000959 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000960 // Collect information from the lambda scope.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000961 SmallVector<LambdaExpr::Capture, 4> Captures;
962 SmallVector<Expr *, 4> CaptureInits;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000963 LambdaCaptureDefault CaptureDefault;
James Dennettf68af642013-08-09 23:08:25 +0000964 SourceLocation CaptureDefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000965 CXXRecordDecl *Class;
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000966 CXXMethodDecl *CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000967 SourceRange IntroducerRange;
968 bool ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000969 bool ExplicitResultType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000970 bool LambdaExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +0000971 bool ContainsUnexpandedParameterPack;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000972 SmallVector<VarDecl *, 4> ArrayIndexVars;
973 SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000974 {
975 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000976 CallOperator = LSI->CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000977 Class = LSI->Lambda;
978 IntroducerRange = LSI->IntroducerRange;
979 ExplicitParams = LSI->ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000980 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000981 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Richard Smith612409e2012-07-25 03:56:55 +0000982 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000983 ArrayIndexVars.swap(LSI->ArrayIndexVars);
984 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
985
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000986 // Translate captures.
987 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
988 LambdaScopeInfo::Capture From = LSI->Captures[I];
989 assert(!From.isBlockCapture() && "Cannot capture __block variables");
990 bool IsImplicit = I >= LSI->NumExplicitCaptures;
991
992 // Handle 'this' capture.
993 if (From.isThisCapture()) {
994 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
995 IsImplicit,
996 LCK_This));
997 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
998 getCurrentThisType(),
999 /*isImplicit=*/true));
1000 continue;
1001 }
1002
Richard Smith0d8e9642013-05-16 06:20:58 +00001003 if (From.isInitCapture()) {
1004 Captures.push_back(LambdaExpr::Capture(From.getInitCaptureField()));
1005 CaptureInits.push_back(From.getInitExpr());
1006 continue;
1007 }
1008
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001009 VarDecl *Var = From.getVariable();
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001010 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
1011 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregora7365242012-02-14 19:27:52 +00001012 Kind, Var, From.getEllipsisLoc()));
Richard Smith0d8e9642013-05-16 06:20:58 +00001013 CaptureInits.push_back(From.getInitExpr());
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001014 }
1015
1016 switch (LSI->ImpCaptureStyle) {
1017 case CapturingScopeInfo::ImpCap_None:
1018 CaptureDefault = LCD_None;
1019 break;
1020
1021 case CapturingScopeInfo::ImpCap_LambdaByval:
1022 CaptureDefault = LCD_ByCopy;
1023 break;
1024
Tareq A. Siraj6afcf882013-04-16 19:37:38 +00001025 case CapturingScopeInfo::ImpCap_CapturedRegion:
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001026 case CapturingScopeInfo::ImpCap_LambdaByref:
1027 CaptureDefault = LCD_ByRef;
1028 break;
1029
1030 case CapturingScopeInfo::ImpCap_Block:
1031 llvm_unreachable("block capture in lambda");
1032 break;
1033 }
James Dennettf68af642013-08-09 23:08:25 +00001034 CaptureDefaultLoc = LSI->CaptureDefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001035
Douglas Gregor54042f12012-02-09 10:18:50 +00001036 // C++11 [expr.prim.lambda]p4:
1037 // If a lambda-expression does not include a
1038 // trailing-return-type, it is as if the trailing-return-type
1039 // denotes the following type:
Richard Smith41d09582013-09-25 05:02:54 +00001040 //
1041 // Skip for C++1y return type deduction semantics which uses
1042 // different machinery.
1043 // FIXME: Refactor and Merge the return type deduction machinery.
Douglas Gregor54042f12012-02-09 10:18:50 +00001044 // FIXME: Assumes current resolution to core issue 975.
Richard Smith41d09582013-09-25 05:02:54 +00001045 if (LSI->HasImplicitReturnType && !getLangOpts().CPlusPlus1y) {
Jordan Rose7dd900e2012-07-02 21:19:23 +00001046 deduceClosureReturnType(*LSI);
1047
Douglas Gregor54042f12012-02-09 10:18:50 +00001048 // - if there are no return statements in the
1049 // compound-statement, or all return statements return
1050 // either an expression of type void or no expression or
1051 // braced-init-list, the type void;
1052 if (LSI->ReturnType.isNull()) {
1053 LSI->ReturnType = Context.VoidTy;
Douglas Gregor54042f12012-02-09 10:18:50 +00001054 }
1055
1056 // Create a function type with the inferred return type.
1057 const FunctionProtoType *Proto
1058 = CallOperator->getType()->getAs<FunctionProtoType>();
Reid Kleckner0567a792013-06-10 20:51:09 +00001059 QualType FunctionTy = Context.getFunctionType(
1060 LSI->ReturnType, Proto->getArgTypes(), Proto->getExtProtoInfo());
Douglas Gregor54042f12012-02-09 10:18:50 +00001061 CallOperator->setType(FunctionTy);
1062 }
Manuel Klimek152b4e42013-08-22 12:12:24 +00001063
Douglas Gregor215e4e12012-02-12 17:34:23 +00001064 // C++ [expr.prim.lambda]p7:
1065 // The lambda-expression's compound-statement yields the
1066 // function-body (8.4) of the function call operator [...].
Douglas Gregordfca6f52012-02-13 22:00:16 +00001067 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor215e4e12012-02-12 17:34:23 +00001068 CallOperator->setLexicalDeclContext(Class);
Manuel Klimek152b4e42013-08-22 12:12:24 +00001069 Class->addDecl(CallOperator);
Douglas Gregorb09ab8c2012-02-21 20:05:31 +00001070 PopExpressionEvaluationContext();
Douglas Gregor215e4e12012-02-12 17:34:23 +00001071
Douglas Gregorb5559712012-02-10 16:13:20 +00001072 // C++11 [expr.prim.lambda]p6:
1073 // The closure type for a lambda-expression with no lambda-capture
1074 // has a public non-virtual non-explicit const conversion function
1075 // to pointer to function having the same parameter and return
1076 // types as the closure type's function call operator.
Douglas Gregorc25d1c92012-02-15 22:00:51 +00001077 if (Captures.empty() && CaptureDefault == LCD_None)
1078 addFunctionPointerConversion(*this, IntroducerRange, Class,
1079 CallOperator);
Douglas Gregor503384f2012-02-09 00:47:04 +00001080
Douglas Gregorc2956e52012-02-15 22:08:38 +00001081 // Objective-C++:
1082 // The closure type for a lambda-expression has a public non-virtual
1083 // non-explicit const conversion function to a block pointer having the
1084 // same parameter and return types as the closure type's function call
1085 // operator.
David Blaikie4e4d0842012-03-11 07:00:24 +00001086 if (getLangOpts().Blocks && getLangOpts().ObjC1)
Douglas Gregorc2956e52012-02-15 22:08:38 +00001087 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
1088
Douglas Gregorb5559712012-02-10 16:13:20 +00001089 // Finalize the lambda class.
David Blaikie262bc182012-04-30 02:36:29 +00001090 SmallVector<Decl*, 4> Fields;
1091 for (RecordDecl::field_iterator i = Class->field_begin(),
1092 e = Class->field_end(); i != e; ++i)
David Blaikie581deb32012-06-06 20:45:41 +00001093 Fields.push_back(*i);
Douglas Gregorb5559712012-02-10 16:13:20 +00001094 ActOnFields(0, Class->getLocation(), Class, Fields,
1095 SourceLocation(), SourceLocation(), 0);
1096 CheckCompletedCXXClass(Class);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001097 }
1098
Douglas Gregor503384f2012-02-09 00:47:04 +00001099 if (LambdaExprNeedsCleanups)
1100 ExprNeedsCleanups = true;
Douglas Gregor9e8c92a2012-02-20 19:44:39 +00001101
Douglas Gregore2c59132012-02-09 08:14:43 +00001102 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
James Dennettf68af642013-08-09 23:08:25 +00001103 CaptureDefault, CaptureDefaultLoc,
1104 Captures,
Douglas Gregordfca6f52012-02-13 22:00:16 +00001105 ExplicitParams, ExplicitResultType,
1106 CaptureInits, ArrayIndexVars,
Richard Smith612409e2012-07-25 03:56:55 +00001107 ArrayIndexStarts, Body->getLocEnd(),
1108 ContainsUnexpandedParameterPack);
Manuel Klimek152b4e42013-08-22 12:12:24 +00001109
Douglas Gregore2c59132012-02-09 08:14:43 +00001110 // C++11 [expr.prim.lambda]p2:
1111 // A lambda-expression shall not appear in an unevaluated operand
1112 // (Clause 5).
Douglas Gregord5387e82012-02-14 00:00:48 +00001113 if (!CurContext->isDependentContext()) {
1114 switch (ExprEvalContexts.back().Context) {
1115 case Unevaluated:
John McCallaeeacf72013-05-03 00:10:13 +00001116 case UnevaluatedAbstract:
Douglas Gregord5387e82012-02-14 00:00:48 +00001117 // We don't actually diagnose this case immediately, because we
1118 // could be within a context where we might find out later that
1119 // the expression is potentially evaluated (e.g., for typeid).
1120 ExprEvalContexts.back().Lambdas.push_back(Lambda);
1121 break;
Douglas Gregore2c59132012-02-09 08:14:43 +00001122
Douglas Gregord5387e82012-02-14 00:00:48 +00001123 case ConstantEvaluated:
1124 case PotentiallyEvaluated:
1125 case PotentiallyEvaluatedIfUsed:
1126 break;
1127 }
Douglas Gregore2c59132012-02-09 08:14:43 +00001128 }
Manuel Klimek152b4e42013-08-22 12:12:24 +00001129
Douglas Gregor503384f2012-02-09 00:47:04 +00001130 return MaybeBindToTemporary(Lambda);
Douglas Gregore2a7ad02012-02-08 21:18:48 +00001131}
Eli Friedman23f02672012-03-01 04:01:32 +00001132
1133ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation,
1134 SourceLocation ConvLocation,
1135 CXXConversionDecl *Conv,
1136 Expr *Src) {
1137 // Make sure that the lambda call operator is marked used.
1138 CXXRecordDecl *Lambda = Conv->getParent();
1139 CXXMethodDecl *CallOperator
1140 = cast<CXXMethodDecl>(
David Blaikie3bc93e32012-12-19 00:45:41 +00001141 Lambda->lookup(
1142 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
Eli Friedman23f02672012-03-01 04:01:32 +00001143 CallOperator->setReferenced();
Eli Friedman86164e82013-09-05 00:02:25 +00001144 CallOperator->markUsed(Context);
Eli Friedman23f02672012-03-01 04:01:32 +00001145
1146 ExprResult Init = PerformCopyInitialization(
1147 InitializedEntity::InitializeBlock(ConvLocation,
1148 Src->getType(),
1149 /*NRVO=*/false),
1150 CurrentLocation, Src);
1151 if (!Init.isInvalid())
1152 Init = ActOnFinishFullExpr(Init.take());
1153
1154 if (Init.isInvalid())
1155 return ExprError();
1156
1157 // Create the new block to be returned.
1158 BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation);
1159
1160 // Set the type information.
1161 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
1162 Block->setIsVariadic(CallOperator->isVariadic());
1163 Block->setBlockMissingReturnType(false);
1164
1165 // Add parameters.
1166 SmallVector<ParmVarDecl *, 4> BlockParams;
1167 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1168 ParmVarDecl *From = CallOperator->getParamDecl(I);
1169 BlockParams.push_back(ParmVarDecl::Create(Context, Block,
1170 From->getLocStart(),
1171 From->getLocation(),
1172 From->getIdentifier(),
1173 From->getType(),
1174 From->getTypeSourceInfo(),
1175 From->getStorageClass(),
Eli Friedman23f02672012-03-01 04:01:32 +00001176 /*DefaultArg=*/0));
1177 }
1178 Block->setParams(BlockParams);
1179
1180 Block->setIsConversionFromLambda(true);
1181
1182 // Add capture. The capture uses a fake variable, which doesn't correspond
1183 // to any actual memory location. However, the initializer copy-initializes
1184 // the lambda object.
1185 TypeSourceInfo *CapVarTSI =
1186 Context.getTrivialTypeSourceInfo(Src->getType());
1187 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
1188 ConvLocation, 0,
1189 Src->getType(), CapVarTSI,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00001190 SC_None);
Eli Friedman23f02672012-03-01 04:01:32 +00001191 BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false,
1192 /*Nested=*/false, /*Copy=*/Init.take());
1193 Block->setCaptures(Context, &Capture, &Capture + 1,
1194 /*CapturesCXXThis=*/false);
1195
1196 // Add a fake function body to the block. IR generation is responsible
1197 // for filling in the actual body, which cannot be expressed as an AST.
Benjamin Kramer3a2d0fb2012-07-04 17:03:41 +00001198 Block->setBody(new (Context) CompoundStmt(ConvLocation));
Eli Friedman23f02672012-03-01 04:01:32 +00001199
1200 // Create the block literal expression.
1201 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
1202 ExprCleanupObjects.push_back(Block);
1203 ExprNeedsCleanups = true;
1204
1205 return BuildBlock;
1206}