blob: 7b729e70181eabfc1b62c2e354162f6b718004a8 [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"
14#include "clang/Sema/Initialization.h"
15#include "clang/Sema/Lookup.h"
16#include "clang/Sema/ScopeInfo.h"
17#include "clang/Sema/SemaInternal.h"
Douglas Gregor3ac109c2012-02-10 17:46:20 +000018#include "clang/Lex/Preprocessor.h"
Douglas Gregore2a7ad02012-02-08 21:18:48 +000019#include "clang/AST/ExprCXX.h"
20using namespace clang;
21using namespace sema;
22
Douglas Gregordfca6f52012-02-13 22:00:16 +000023CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +000024 DeclContext *DC = CurContext;
25 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
26 DC = DC->getParent();
Douglas Gregordfca6f52012-02-13 22:00:16 +000027
Douglas Gregore2a7ad02012-02-08 21:18:48 +000028 // Start constructing the lambda class.
Douglas Gregorda8962a2012-02-13 15:44:47 +000029 CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC,
Douglas Gregordfca6f52012-02-13 22:00:16 +000030 IntroducerRange.getBegin());
Douglas Gregorfa07ab52012-02-20 20:47:06 +000031 DC->addDecl(Class);
Douglas Gregordfca6f52012-02-13 22:00:16 +000032
33 return Class;
34}
Douglas Gregore2a7ad02012-02-08 21:18:48 +000035
Douglas Gregordfca6f52012-02-13 22:00:16 +000036CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class,
37 SourceRange IntroducerRange,
38 TypeSourceInfo *MethodType,
Douglas Gregorc6889e72012-02-14 22:28:59 +000039 SourceLocation EndLoc,
40 llvm::ArrayRef<ParmVarDecl *> Params) {
Douglas Gregordfca6f52012-02-13 22:00:16 +000041 // C++11 [expr.prim.lambda]p5:
42 // The closure type for a lambda-expression has a public inline function
43 // call operator (13.5.4) whose parameters and return type are described by
44 // the lambda-expression's parameter-declaration-clause and
45 // trailing-return-type respectively.
46 DeclarationName MethodName
47 = Context.DeclarationNames.getCXXOperatorName(OO_Call);
48 DeclarationNameLoc MethodNameLoc;
49 MethodNameLoc.CXXOperatorName.BeginOpNameLoc
50 = IntroducerRange.getBegin().getRawEncoding();
51 MethodNameLoc.CXXOperatorName.EndOpNameLoc
52 = IntroducerRange.getEnd().getRawEncoding();
53 CXXMethodDecl *Method
54 = CXXMethodDecl::Create(Context, Class, EndLoc,
55 DeclarationNameInfo(MethodName,
56 IntroducerRange.getBegin(),
57 MethodNameLoc),
58 MethodType->getType(), MethodType,
59 /*isStatic=*/false,
60 SC_None,
61 /*isInline=*/true,
62 /*isConstExpr=*/false,
63 EndLoc);
64 Method->setAccess(AS_public);
65
66 // Temporarily set the lexical declaration context to the current
67 // context, so that the Scope stack matches the lexical nesting.
Douglas Gregorfa07ab52012-02-20 20:47:06 +000068 Method->setLexicalDeclContext(CurContext);
Douglas Gregordfca6f52012-02-13 22:00:16 +000069
Douglas Gregorc6889e72012-02-14 22:28:59 +000070 // Add parameters.
71 if (!Params.empty()) {
72 Method->setParams(Params);
73 CheckParmsForFunctionDef(const_cast<ParmVarDecl **>(Params.begin()),
74 const_cast<ParmVarDecl **>(Params.end()),
75 /*CheckParameterNames=*/false);
76
77 for (CXXMethodDecl::param_iterator P = Method->param_begin(),
78 PEnd = Method->param_end();
79 P != PEnd; ++P)
80 (*P)->setOwningFunction(Method);
81 }
82
Douglas Gregordfca6f52012-02-13 22:00:16 +000083 return Method;
84}
85
86LambdaScopeInfo *Sema::enterLambdaScope(CXXMethodDecl *CallOperator,
87 SourceRange IntroducerRange,
88 LambdaCaptureDefault CaptureDefault,
89 bool ExplicitParams,
90 bool ExplicitResultType,
91 bool Mutable) {
92 PushLambdaScope(CallOperator->getParent(), CallOperator);
93 LambdaScopeInfo *LSI = getCurLambda();
94 if (CaptureDefault == LCD_ByCopy)
95 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
96 else if (CaptureDefault == LCD_ByRef)
97 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
98 LSI->IntroducerRange = IntroducerRange;
99 LSI->ExplicitParams = ExplicitParams;
100 LSI->Mutable = Mutable;
101
102 if (ExplicitResultType) {
103 LSI->ReturnType = CallOperator->getResultType();
Douglas Gregor53393f22012-02-14 21:20:44 +0000104
105 if (!LSI->ReturnType->isDependentType() &&
106 !LSI->ReturnType->isVoidType()) {
107 if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType,
108 diag::err_lambda_incomplete_result)) {
109 // Do nothing.
110 } else if (LSI->ReturnType->isObjCObjectOrInterfaceType()) {
111 Diag(CallOperator->getLocStart(), diag::err_lambda_objc_object_result)
112 << LSI->ReturnType;
113 }
114 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000115 } else {
116 LSI->HasImplicitReturnType = true;
117 }
118
119 return LSI;
120}
121
122void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) {
123 LSI->finishedExplicitCaptures();
124}
125
Douglas Gregorc6889e72012-02-14 22:28:59 +0000126void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) {
Douglas Gregordfca6f52012-02-13 22:00:16 +0000127 // Introduce our parameters into the function scope
128 for (unsigned p = 0, NumParams = CallOperator->getNumParams();
129 p < NumParams; ++p) {
130 ParmVarDecl *Param = CallOperator->getParamDecl(p);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000131
132 // If this has an identifier, add it to the scope stack.
133 if (CurScope && Param->getIdentifier()) {
134 CheckShadow(CurScope, Param);
135
136 PushOnScopeChains(Param, CurScope);
137 }
138 }
139}
140
141void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro,
142 Declarator &ParamInfo,
143 Scope *CurScope) {
144 CXXRecordDecl *Class = createLambdaClosureType(Intro.Range);
145
146 // Determine the signature of the call operator.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000147 TypeSourceInfo *MethodTyInfo;
148 bool ExplicitParams = true;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000149 bool ExplicitResultType = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000150 SourceLocation EndLoc;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000151 llvm::ArrayRef<ParmVarDecl *> Params;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000152 if (ParamInfo.getNumTypeObjects() == 0) {
153 // C++11 [expr.prim.lambda]p4:
154 // If a lambda-expression does not include a lambda-declarator, it is as
155 // if the lambda-declarator were ().
156 FunctionProtoType::ExtProtoInfo EPI;
Richard Smitheefb3d52012-02-10 09:58:53 +0000157 EPI.HasTrailingReturn = true;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000158 EPI.TypeQuals |= DeclSpec::TQ_const;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000159 QualType MethodTy = Context.getFunctionType(Context.DependentTy,
160 /*Args=*/0, /*NumArgs=*/0, EPI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000161 MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy);
162 ExplicitParams = false;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000163 ExplicitResultType = false;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000164 EndLoc = Intro.Range.getEnd();
165 } else {
166 assert(ParamInfo.isFunctionDeclarator() &&
167 "lambda-declarator is a function");
168 DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo();
169
170 // C++11 [expr.prim.lambda]p5:
171 // This function call operator is declared const (9.3.1) if and only if
172 // the lambda-expression's parameter-declaration-clause is not followed
173 // by mutable. It is neither virtual nor declared volatile. [...]
174 if (!FTI.hasMutableQualifier())
175 FTI.TypeQuals |= DeclSpec::TQ_const;
176
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000177 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000178 assert(MethodTyInfo && "no type from lambda-declarator");
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000179 EndLoc = ParamInfo.getSourceRange().getEnd();
Douglas Gregordfca6f52012-02-13 22:00:16 +0000180
181 ExplicitResultType
182 = MethodTyInfo->getType()->getAs<FunctionType>()->getResultType()
183 != Context.DependentTy;
Douglas Gregorc6889e72012-02-14 22:28:59 +0000184
185 TypeLoc TL = MethodTyInfo->getTypeLoc();
186 FunctionProtoTypeLoc Proto = cast<FunctionProtoTypeLoc>(TL);
187 Params = llvm::ArrayRef<ParmVarDecl *>(Proto.getParmArray(),
188 Proto.getNumArgs());
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000189 }
190
Douglas Gregordfca6f52012-02-13 22:00:16 +0000191 CXXMethodDecl *Method = startLambdaDefinition(Class, Intro.Range,
Douglas Gregorc6889e72012-02-14 22:28:59 +0000192 MethodTyInfo, EndLoc, Params);
193
194 if (ExplicitParams)
195 CheckCXXDefaultArguments(Method);
Douglas Gregordfca6f52012-02-13 22:00:16 +0000196
Douglas Gregor503384f2012-02-09 00:47:04 +0000197 // Attributes on the lambda apply to the method.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000198 ProcessDeclAttributes(CurScope, Method, ParamInfo);
199
Douglas Gregor503384f2012-02-09 00:47:04 +0000200 // Introduce the function call operator as the current declaration context.
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000201 PushDeclContext(CurScope, Method);
202
203 // Introduce the lambda scope.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000204 LambdaScopeInfo *LSI
205 = enterLambdaScope(Method, Intro.Range, Intro.Default, ExplicitParams,
206 ExplicitResultType,
207 (Method->getTypeQualifiers() & Qualifiers::Const) == 0);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000208
209 // Handle explicit captures.
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000210 SourceLocation PrevCaptureLoc
211 = Intro.Default == LCD_None? Intro.Range.getBegin() : Intro.DefaultLoc;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000212 for (llvm::SmallVector<LambdaCapture, 4>::const_iterator
213 C = Intro.Captures.begin(),
214 E = Intro.Captures.end();
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000215 C != E;
216 PrevCaptureLoc = C->Loc, ++C) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000217 if (C->Kind == LCK_This) {
218 // C++11 [expr.prim.lambda]p8:
219 // An identifier or this shall not appear more than once in a
220 // lambda-capture.
221 if (LSI->isCXXThisCaptured()) {
222 Diag(C->Loc, diag::err_capture_more_than_once)
223 << "'this'"
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000224 << SourceRange(LSI->getCXXThisCapture().getLocation())
225 << FixItHint::CreateRemoval(
226 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000227 continue;
228 }
229
230 // C++11 [expr.prim.lambda]p8:
231 // If a lambda-capture includes a capture-default that is =, the
232 // lambda-capture shall not contain this [...].
233 if (Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000234 Diag(C->Loc, diag::err_this_capture_with_copy_default)
235 << FixItHint::CreateRemoval(
236 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000237 continue;
238 }
239
240 // C++11 [expr.prim.lambda]p12:
241 // If this is captured by a local lambda expression, its nearest
242 // enclosing function shall be a non-static member function.
243 QualType ThisCaptureType = getCurrentThisType();
244 if (ThisCaptureType.isNull()) {
245 Diag(C->Loc, diag::err_this_capture) << true;
246 continue;
247 }
248
249 CheckCXXThisCapture(C->Loc, /*Explicit=*/true);
250 continue;
251 }
252
253 assert(C->Id && "missing identifier for capture");
254
255 // C++11 [expr.prim.lambda]p8:
256 // If a lambda-capture includes a capture-default that is &, the
257 // identifiers in the lambda-capture shall not be preceded by &.
258 // If a lambda-capture includes a capture-default that is =, [...]
259 // each identifier it contains shall be preceded by &.
260 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000261 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
262 << FixItHint::CreateRemoval(
263 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000264 continue;
265 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000266 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
267 << FixItHint::CreateRemoval(
268 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000269 continue;
270 }
271
272 DeclarationNameInfo Name(C->Id, C->Loc);
273 LookupResult R(*this, Name, LookupOrdinaryName);
274 LookupName(R, CurScope);
275 if (R.isAmbiguous())
276 continue;
277 if (R.empty()) {
278 // FIXME: Disable corrections that would add qualification?
279 CXXScopeSpec ScopeSpec;
280 DeclFilterCCC<VarDecl> Validator;
281 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
282 continue;
283 }
284
285 // C++11 [expr.prim.lambda]p10:
286 // The identifiers in a capture-list are looked up using the usual rules
287 // for unqualified name lookup (3.4.1); each such lookup shall find a
288 // variable with automatic storage duration declared in the reaching
289 // scope of the local lambda expression.
Douglas Gregor53393f22012-02-14 21:20:44 +0000290 //
Douglas Gregor999713e2012-02-18 09:37:24 +0000291 // Note that the 'reaching scope' check happens in tryCaptureVariable().
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000292 VarDecl *Var = R.getAsSingle<VarDecl>();
293 if (!Var) {
294 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
295 continue;
296 }
297
298 if (!Var->hasLocalStorage()) {
299 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
300 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
301 continue;
302 }
303
304 // C++11 [expr.prim.lambda]p8:
305 // An identifier or this shall not appear more than once in a
306 // lambda-capture.
307 if (LSI->isCaptured(Var)) {
308 Diag(C->Loc, diag::err_capture_more_than_once)
309 << C->Id
Douglas Gregor3ac109c2012-02-10 17:46:20 +0000310 << SourceRange(LSI->getCapture(Var).getLocation())
311 << FixItHint::CreateRemoval(
312 SourceRange(PP.getLocForEndOfToken(PrevCaptureLoc), C->Loc));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000313 continue;
314 }
315
Douglas Gregora7365242012-02-14 19:27:52 +0000316 // C++11 [expr.prim.lambda]p23:
317 // A capture followed by an ellipsis is a pack expansion (14.5.3).
318 SourceLocation EllipsisLoc;
319 if (C->EllipsisLoc.isValid()) {
320 if (Var->isParameterPack()) {
321 EllipsisLoc = C->EllipsisLoc;
322 } else {
323 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
324 << SourceRange(C->Loc);
325
326 // Just ignore the ellipsis.
327 }
328 } else if (Var->isParameterPack()) {
329 Diag(C->Loc, diag::err_lambda_unexpanded_pack);
330 continue;
331 }
332
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000333 TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef :
334 TryCapture_ExplicitByVal;
Douglas Gregor999713e2012-02-18 09:37:24 +0000335 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000336 }
Douglas Gregordfca6f52012-02-13 22:00:16 +0000337 finishLambdaExplicitCaptures(LSI);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000338
Douglas Gregorc6889e72012-02-14 22:28:59 +0000339 // Add lambda parameters into scope.
340 addLambdaParameters(Method, CurScope);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000341
Douglas Gregordfca6f52012-02-13 22:00:16 +0000342 // Enter a new evaluation context to insulate the lambda from any
Douglas Gregor503384f2012-02-09 00:47:04 +0000343 // cleanups from the enclosing full-expression.
344 PushExpressionEvaluationContext(PotentiallyEvaluated);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000345}
346
Douglas Gregordfca6f52012-02-13 22:00:16 +0000347void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope,
348 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000349 // Leave the expression-evaluation context.
350 DiscardCleanupsInEvaluationContext();
351 PopExpressionEvaluationContext();
352
353 // Leave the context of the lambda.
Douglas Gregordfca6f52012-02-13 22:00:16 +0000354 if (!IsInstantiation)
355 PopDeclContext();
Douglas Gregor630d5ff2012-02-09 01:28:42 +0000356
357 // Finalize the lambda.
358 LambdaScopeInfo *LSI = getCurLambda();
359 CXXRecordDecl *Class = LSI->Lambda;
360 Class->setInvalidDecl();
361 SmallVector<Decl*, 4> Fields(Class->field_begin(), Class->field_end());
362 ActOnFields(0, Class->getLocation(), Class, Fields,
363 SourceLocation(), SourceLocation(), 0);
364 CheckCompletedCXXClass(Class);
365
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000366 PopFunctionScopeInfo();
367}
368
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000369/// \brief Add a lambda's conversion to function pointer, as described in
370/// C++11 [expr.prim.lambda]p6.
371static void addFunctionPointerConversion(Sema &S,
372 SourceRange IntroducerRange,
373 CXXRecordDecl *Class,
374 CXXMethodDecl *CallOperator) {
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000375 // Add the conversion to function pointer.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000376 const FunctionProtoType *Proto
377 = CallOperator->getType()->getAs<FunctionProtoType>();
378 QualType FunctionPtrTy;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000379 QualType FunctionTy;
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000380 {
381 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
382 ExtInfo.TypeQuals = 0;
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000383 FunctionTy = S.Context.getFunctionType(Proto->getResultType(),
384 Proto->arg_type_begin(),
385 Proto->getNumArgs(),
386 ExtInfo);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000387 FunctionPtrTy = S.Context.getPointerType(FunctionTy);
388 }
389
390 FunctionProtoType::ExtProtoInfo ExtInfo;
391 ExtInfo.TypeQuals = Qualifiers::Const;
392 QualType ConvTy = S.Context.getFunctionType(FunctionPtrTy, 0, 0, ExtInfo);
393
394 SourceLocation Loc = IntroducerRange.getBegin();
395 DeclarationName Name
396 = S.Context.DeclarationNames.getCXXConversionFunctionName(
397 S.Context.getCanonicalType(FunctionPtrTy));
398 DeclarationNameLoc NameLoc;
399 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(FunctionPtrTy,
400 Loc);
401 CXXConversionDecl *Conversion
402 = CXXConversionDecl::Create(S.Context, Class, Loc,
403 DeclarationNameInfo(Name, Loc, NameLoc),
404 ConvTy,
405 S.Context.getTrivialTypeSourceInfo(ConvTy,
406 Loc),
407 /*isInline=*/false, /*isExplicit=*/false,
408 /*isConstexpr=*/false,
409 CallOperator->getBody()->getLocEnd());
410 Conversion->setAccess(AS_public);
411 Conversion->setImplicit(true);
412 Class->addDecl(Conversion);
Douglas Gregor27dd7d92012-02-17 03:02:34 +0000413
414 // Add a non-static member function "__invoke" that will be the result of
415 // the conversion.
416 Name = &S.Context.Idents.get("__invoke");
417 CXXMethodDecl *Invoke
418 = CXXMethodDecl::Create(S.Context, Class, Loc,
419 DeclarationNameInfo(Name, Loc), FunctionTy,
420 CallOperator->getTypeSourceInfo(),
421 /*IsStatic=*/true, SC_Static, /*IsInline=*/true,
422 /*IsConstexpr=*/false,
423 CallOperator->getBody()->getLocEnd());
424 SmallVector<ParmVarDecl *, 4> InvokeParams;
425 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
426 ParmVarDecl *From = CallOperator->getParamDecl(I);
427 InvokeParams.push_back(ParmVarDecl::Create(S.Context, Invoke,
428 From->getLocStart(),
429 From->getLocation(),
430 From->getIdentifier(),
431 From->getType(),
432 From->getTypeSourceInfo(),
433 From->getStorageClass(),
434 From->getStorageClassAsWritten(),
435 /*DefaultArg=*/0));
436 }
437 Invoke->setParams(InvokeParams);
438 Invoke->setAccess(AS_private);
439 Invoke->setImplicit(true);
440 Class->addDecl(Invoke);
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000441}
442
Douglas Gregorc2956e52012-02-15 22:08:38 +0000443/// \brief Add a lambda's conversion to block pointer.
444static void addBlockPointerConversion(Sema &S,
445 SourceRange IntroducerRange,
446 CXXRecordDecl *Class,
447 CXXMethodDecl *CallOperator) {
448 const FunctionProtoType *Proto
449 = CallOperator->getType()->getAs<FunctionProtoType>();
450 QualType BlockPtrTy;
451 {
452 FunctionProtoType::ExtProtoInfo ExtInfo = Proto->getExtProtoInfo();
453 ExtInfo.TypeQuals = 0;
454 QualType FunctionTy
455 = S.Context.getFunctionType(Proto->getResultType(),
456 Proto->arg_type_begin(),
457 Proto->getNumArgs(),
458 ExtInfo);
459 BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
460 }
461
462 FunctionProtoType::ExtProtoInfo ExtInfo;
463 ExtInfo.TypeQuals = Qualifiers::Const;
464 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, 0, 0, ExtInfo);
465
466 SourceLocation Loc = IntroducerRange.getBegin();
467 DeclarationName Name
468 = S.Context.DeclarationNames.getCXXConversionFunctionName(
469 S.Context.getCanonicalType(BlockPtrTy));
470 DeclarationNameLoc NameLoc;
471 NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc);
472 CXXConversionDecl *Conversion
473 = CXXConversionDecl::Create(S.Context, Class, Loc,
474 DeclarationNameInfo(Name, Loc, NameLoc),
475 ConvTy,
476 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
477 /*isInline=*/false, /*isExplicit=*/false,
478 /*isConstexpr=*/false,
479 CallOperator->getBody()->getLocEnd());
480 Conversion->setAccess(AS_public);
481 Conversion->setImplicit(true);
482 Class->addDecl(Conversion);
483}
484
Douglas Gregordfca6f52012-02-13 22:00:16 +0000485ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000486 Scope *CurScope,
487 llvm::Optional<unsigned> ManglingNumber,
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000488 Decl *ContextDecl,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000489 bool IsInstantiation) {
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000490 // Leave the expression-evaluation context.
491 DiscardCleanupsInEvaluationContext();
492 PopExpressionEvaluationContext();
493
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000494 // Collect information from the lambda scope.
495 llvm::SmallVector<LambdaExpr::Capture, 4> Captures;
496 llvm::SmallVector<Expr *, 4> CaptureInits;
497 LambdaCaptureDefault CaptureDefault;
498 CXXRecordDecl *Class;
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000499 CXXMethodDecl *CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000500 SourceRange IntroducerRange;
501 bool ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000502 bool ExplicitResultType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000503 bool LambdaExprNeedsCleanups;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000504 llvm::SmallVector<VarDecl *, 4> ArrayIndexVars;
505 llvm::SmallVector<unsigned, 4> ArrayIndexStarts;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000506 {
507 LambdaScopeInfo *LSI = getCurLambda();
Douglas Gregoref7d78b2012-02-10 08:36:38 +0000508 CallOperator = LSI->CallOperator;
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000509 Class = LSI->Lambda;
510 IntroducerRange = LSI->IntroducerRange;
511 ExplicitParams = LSI->ExplicitParams;
Douglas Gregordfca6f52012-02-13 22:00:16 +0000512 ExplicitResultType = !LSI->HasImplicitReturnType;
Douglas Gregor503384f2012-02-09 00:47:04 +0000513 LambdaExprNeedsCleanups = LSI->ExprNeedsCleanups;
Douglas Gregor9daa7bf2012-02-13 16:35:30 +0000514 ArrayIndexVars.swap(LSI->ArrayIndexVars);
515 ArrayIndexStarts.swap(LSI->ArrayIndexStarts);
516
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000517 // Translate captures.
518 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
519 LambdaScopeInfo::Capture From = LSI->Captures[I];
520 assert(!From.isBlockCapture() && "Cannot capture __block variables");
521 bool IsImplicit = I >= LSI->NumExplicitCaptures;
522
523 // Handle 'this' capture.
524 if (From.isThisCapture()) {
525 Captures.push_back(LambdaExpr::Capture(From.getLocation(),
526 IsImplicit,
527 LCK_This));
528 CaptureInits.push_back(new (Context) CXXThisExpr(From.getLocation(),
529 getCurrentThisType(),
530 /*isImplicit=*/true));
531 continue;
532 }
533
534 VarDecl *Var = From.getVariable();
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000535 LambdaCaptureKind Kind = From.isCopyCapture()? LCK_ByCopy : LCK_ByRef;
536 Captures.push_back(LambdaExpr::Capture(From.getLocation(), IsImplicit,
Douglas Gregora7365242012-02-14 19:27:52 +0000537 Kind, Var, From.getEllipsisLoc()));
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000538 CaptureInits.push_back(From.getCopyExpr());
539 }
540
541 switch (LSI->ImpCaptureStyle) {
542 case CapturingScopeInfo::ImpCap_None:
543 CaptureDefault = LCD_None;
544 break;
545
546 case CapturingScopeInfo::ImpCap_LambdaByval:
547 CaptureDefault = LCD_ByCopy;
548 break;
549
550 case CapturingScopeInfo::ImpCap_LambdaByref:
551 CaptureDefault = LCD_ByRef;
552 break;
553
554 case CapturingScopeInfo::ImpCap_Block:
555 llvm_unreachable("block capture in lambda");
556 break;
557 }
558
Douglas Gregor54042f12012-02-09 10:18:50 +0000559 // C++11 [expr.prim.lambda]p4:
560 // If a lambda-expression does not include a
561 // trailing-return-type, it is as if the trailing-return-type
562 // denotes the following type:
563 // FIXME: Assumes current resolution to core issue 975.
564 if (LSI->HasImplicitReturnType) {
565 // - if there are no return statements in the
566 // compound-statement, or all return statements return
567 // either an expression of type void or no expression or
568 // braced-init-list, the type void;
569 if (LSI->ReturnType.isNull()) {
570 LSI->ReturnType = Context.VoidTy;
571 } else {
572 // C++11 [expr.prim.lambda]p4:
573 // - if the compound-statement is of the form
574 //
575 // { attribute-specifier-seq[opt] return expression ; }
576 //
577 // the type of the returned expression after
578 // lvalue-to-rvalue conversion (4.1), array-to-pointer
579 // conver- sion (4.2), and function-to-pointer conversion
580 // (4.3);
581 //
582 // Since we're accepting the resolution to a post-C++11 core
583 // issue with a non-trivial extension, provide a warning (by
584 // default).
585 CompoundStmt *CompoundBody = cast<CompoundStmt>(Body);
586 if (!(CompoundBody->size() == 1 &&
587 isa<ReturnStmt>(*CompoundBody->body_begin())) &&
588 !Context.hasSameType(LSI->ReturnType, Context.VoidTy))
589 Diag(IntroducerRange.getBegin(),
590 diag::ext_lambda_implies_void_return);
591 }
592
593 // Create a function type with the inferred return type.
594 const FunctionProtoType *Proto
595 = CallOperator->getType()->getAs<FunctionProtoType>();
596 QualType FunctionTy
597 = Context.getFunctionType(LSI->ReturnType,
598 Proto->arg_type_begin(),
599 Proto->getNumArgs(),
600 Proto->getExtProtoInfo());
601 CallOperator->setType(FunctionTy);
602 }
603
Douglas Gregor215e4e12012-02-12 17:34:23 +0000604 // C++ [expr.prim.lambda]p7:
605 // The lambda-expression's compound-statement yields the
606 // function-body (8.4) of the function call operator [...].
Douglas Gregordfca6f52012-02-13 22:00:16 +0000607 ActOnFinishFunctionBody(CallOperator, Body, IsInstantiation);
Douglas Gregor215e4e12012-02-12 17:34:23 +0000608 CallOperator->setLexicalDeclContext(Class);
609 Class->addDecl(CallOperator);
610
Douglas Gregorb5559712012-02-10 16:13:20 +0000611 // C++11 [expr.prim.lambda]p6:
612 // The closure type for a lambda-expression with no lambda-capture
613 // has a public non-virtual non-explicit const conversion function
614 // to pointer to function having the same parameter and return
615 // types as the closure type's function call operator.
Douglas Gregorc25d1c92012-02-15 22:00:51 +0000616 if (Captures.empty() && CaptureDefault == LCD_None)
617 addFunctionPointerConversion(*this, IntroducerRange, Class,
618 CallOperator);
Douglas Gregor503384f2012-02-09 00:47:04 +0000619
Douglas Gregorc2956e52012-02-15 22:08:38 +0000620 // Objective-C++:
621 // The closure type for a lambda-expression has a public non-virtual
622 // non-explicit const conversion function to a block pointer having the
623 // same parameter and return types as the closure type's function call
624 // operator.
625 if (getLangOptions().Blocks)
626 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
627
Douglas Gregorb5559712012-02-10 16:13:20 +0000628 // Finalize the lambda class.
629 SmallVector<Decl*, 4> Fields(Class->field_begin(), Class->field_end());
Douglas Gregorb5559712012-02-10 16:13:20 +0000630 ActOnFields(0, Class->getLocation(), Class, Fields,
631 SourceLocation(), SourceLocation(), 0);
632 CheckCompletedCXXClass(Class);
633
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000634 }
635
Douglas Gregor503384f2012-02-09 00:47:04 +0000636 if (LambdaExprNeedsCleanups)
637 ExprNeedsCleanups = true;
638
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000639 // If we don't already have a mangling number for this lambda expression,
640 // allocate one now.
641 if (!ManglingNumber) {
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000642 ContextDecl = ExprEvalContexts.back().LambdaContextDecl;
643
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000644 enum ContextKind {
645 Normal,
Douglas Gregor552e2992012-02-21 02:22:07 +0000646 DefaultArgument,
647 DataMember
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000648 } Kind = Normal;
649
650 // Default arguments of member function parameters that appear in a class
Douglas Gregor552e2992012-02-21 02:22:07 +0000651 // definition, as well as the initializers of data members, receive special
652 // treatment. Identify them.
653 if (ContextDecl) {
654 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ContextDecl)) {
655 if (const DeclContext *LexicalDC
656 = Param->getDeclContext()->getLexicalParent())
657 if (LexicalDC->isRecord())
658 Kind = DefaultArgument;
659 } else if (VarDecl *Var = dyn_cast<VarDecl>(ContextDecl)) {
660 if (Var->getDeclContext()->isRecord())
661 Kind = DataMember;
662 } else if (isa<FieldDecl>(ContextDecl)) {
663 Kind = DataMember;
664 }
665 }
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000666
667 switch (Kind) {
668 case Normal:
669 ManglingNumber = Context.getLambdaManglingNumber(CallOperator);
670 ContextDecl = 0;
671 break;
672
673 case DefaultArgument:
Douglas Gregor552e2992012-02-21 02:22:07 +0000674 case DataMember:
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000675 ManglingNumber = ExprEvalContexts.back().getLambdaMangleContext()
676 .getManglingNumber(CallOperator);
677 break;
678 }
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000679 }
680
Douglas Gregore2c59132012-02-09 08:14:43 +0000681 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
682 CaptureDefault, Captures,
Douglas Gregordfca6f52012-02-13 22:00:16 +0000683 ExplicitParams, ExplicitResultType,
684 CaptureInits, ArrayIndexVars,
Douglas Gregor9e8c92a2012-02-20 19:44:39 +0000685 ArrayIndexStarts, Body->getLocEnd(),
Douglas Gregorccc1b5e2012-02-21 00:37:24 +0000686 *ManglingNumber, ContextDecl);
Douglas Gregore2c59132012-02-09 08:14:43 +0000687
688 // C++11 [expr.prim.lambda]p2:
689 // A lambda-expression shall not appear in an unevaluated operand
690 // (Clause 5).
Douglas Gregord5387e82012-02-14 00:00:48 +0000691 if (!CurContext->isDependentContext()) {
692 switch (ExprEvalContexts.back().Context) {
693 case Unevaluated:
694 // We don't actually diagnose this case immediately, because we
695 // could be within a context where we might find out later that
696 // the expression is potentially evaluated (e.g., for typeid).
697 ExprEvalContexts.back().Lambdas.push_back(Lambda);
698 break;
Douglas Gregore2c59132012-02-09 08:14:43 +0000699
Douglas Gregord5387e82012-02-14 00:00:48 +0000700 case ConstantEvaluated:
701 case PotentiallyEvaluated:
702 case PotentiallyEvaluatedIfUsed:
703 break;
704 }
Douglas Gregore2c59132012-02-09 08:14:43 +0000705 }
Douglas Gregord5387e82012-02-14 00:00:48 +0000706
Douglas Gregor503384f2012-02-09 00:47:04 +0000707 return MaybeBindToTemporary(Lambda);
Douglas Gregore2a7ad02012-02-08 21:18:48 +0000708}