/Users/buildslave/jenkins/sharedspace/clang-stage2-coverage-R@2/llvm/tools/clang/lib/Sema/SemaLambda.cpp
Line | Count | Source (jump to first uncovered line) |
1 | | //===--- 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 "TypeLocBuilder.h" |
15 | | #include "clang/AST/ASTLambda.h" |
16 | | #include "clang/AST/ExprCXX.h" |
17 | | #include "clang/Basic/TargetInfo.h" |
18 | | #include "clang/Sema/Initialization.h" |
19 | | #include "clang/Sema/Lookup.h" |
20 | | #include "clang/Sema/Scope.h" |
21 | | #include "clang/Sema/ScopeInfo.h" |
22 | | #include "clang/Sema/SemaInternal.h" |
23 | | #include "clang/Sema/SemaLambda.h" |
24 | | using namespace clang; |
25 | | using namespace sema; |
26 | | |
27 | | /// \brief Examines the FunctionScopeInfo stack to determine the nearest |
28 | | /// enclosing lambda (to the current lambda) that is 'capture-ready' for |
29 | | /// the variable referenced in the current lambda (i.e. \p VarToCapture). |
30 | | /// If successful, returns the index into Sema's FunctionScopeInfo stack |
31 | | /// of the capture-ready lambda's LambdaScopeInfo. |
32 | | /// |
33 | | /// Climbs down the stack of lambdas (deepest nested lambda - i.e. current |
34 | | /// lambda - is on top) to determine the index of the nearest enclosing/outer |
35 | | /// lambda that is ready to capture the \p VarToCapture being referenced in |
36 | | /// the current lambda. |
37 | | /// As we climb down the stack, we want the index of the first such lambda - |
38 | | /// that is the lambda with the highest index that is 'capture-ready'. |
39 | | /// |
40 | | /// A lambda 'L' is capture-ready for 'V' (var or this) if: |
41 | | /// - its enclosing context is non-dependent |
42 | | /// - and if the chain of lambdas between L and the lambda in which |
43 | | /// V is potentially used (i.e. the lambda at the top of the scope info |
44 | | /// stack), can all capture or have already captured V. |
45 | | /// If \p VarToCapture is 'null' then we are trying to capture 'this'. |
46 | | /// |
47 | | /// Note that a lambda that is deemed 'capture-ready' still needs to be checked |
48 | | /// for whether it is 'capture-capable' (see |
49 | | /// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly |
50 | | /// capture. |
51 | | /// |
52 | | /// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a |
53 | | /// LambdaScopeInfo inherits from). The current/deepest/innermost lambda |
54 | | /// is at the top of the stack and has the highest index. |
55 | | /// \param VarToCapture - the variable to capture. If NULL, capture 'this'. |
56 | | /// |
57 | | /// \returns An Optional<unsigned> Index that if evaluates to 'true' contains |
58 | | /// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda |
59 | | /// which is capture-ready. If the return value evaluates to 'false' then |
60 | | /// no lambda is capture-ready for \p VarToCapture. |
61 | | |
62 | | static inline Optional<unsigned> |
63 | | getStackIndexOfNearestEnclosingCaptureReadyLambda( |
64 | | ArrayRef<const clang::sema::FunctionScopeInfo *> FunctionScopes, |
65 | 317 | VarDecl *VarToCapture) { |
66 | 317 | // Label failure to capture. |
67 | 317 | const Optional<unsigned> NoLambdaIsCaptureReady; |
68 | 317 | |
69 | 317 | // Ignore all inner captured regions. |
70 | 317 | unsigned CurScopeIndex = FunctionScopes.size() - 1; |
71 | 322 | while (CurScopeIndex > 0 && 322 isa<clang::sema::CapturedRegionScopeInfo>( |
72 | 322 | FunctionScopes[CurScopeIndex])) |
73 | 5 | --CurScopeIndex; |
74 | 317 | assert( |
75 | 317 | isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) && |
76 | 317 | "The function on the top of sema's function-info stack must be a lambda"); |
77 | 317 | |
78 | 317 | // If VarToCapture is null, we are attempting to capture 'this'. |
79 | 317 | const bool IsCapturingThis = !VarToCapture; |
80 | 317 | const bool IsCapturingVariable = !IsCapturingThis; |
81 | 317 | |
82 | 317 | // Start with the current lambda at the top of the stack (highest index). |
83 | 317 | DeclContext *EnclosingDC = |
84 | 317 | cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator; |
85 | 317 | |
86 | 489 | do { |
87 | 489 | const clang::sema::LambdaScopeInfo *LSI = |
88 | 489 | cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]); |
89 | 489 | // IF we have climbed down to an intervening enclosing lambda that contains |
90 | 489 | // the variable declaration - it obviously can/must not capture the |
91 | 489 | // variable. |
92 | 489 | // Since its enclosing DC is dependent, all the lambdas between it and the |
93 | 489 | // innermost nested lambda are dependent (otherwise we wouldn't have |
94 | 489 | // arrived here) - so we don't yet have a lambda that can capture the |
95 | 489 | // variable. |
96 | 489 | if (IsCapturingVariable && |
97 | 449 | VarToCapture->getDeclContext()->Equals(EnclosingDC)) |
98 | 74 | return NoLambdaIsCaptureReady; |
99 | 415 | |
100 | 415 | // For an enclosing lambda to be capture ready for an entity, all |
101 | 415 | // intervening lambda's have to be able to capture that entity. If even |
102 | 415 | // one of the intervening lambda's is not capable of capturing the entity |
103 | 415 | // then no enclosing lambda can ever capture that entity. |
104 | 415 | // For e.g. |
105 | 415 | // const int x = 10; |
106 | 415 | // [=](auto a) { #1 |
107 | 415 | // [](auto b) { #2 <-- an intervening lambda that can never capture 'x' |
108 | 415 | // [=](auto c) { #3 |
109 | 415 | // f(x, c); <-- can not lead to x's speculative capture by #1 or #2 |
110 | 415 | // }; }; }; |
111 | 415 | // If they do not have a default implicit capture, check to see |
112 | 415 | // if the entity has already been explicitly captured. |
113 | 415 | // If even a single dependent enclosing lambda lacks the capability |
114 | 415 | // to ever capture this variable, there is no further enclosing |
115 | 415 | // non-dependent lambda that can capture this variable. |
116 | 415 | if (415 LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None415 ) { |
117 | 104 | if (IsCapturingVariable && 104 !LSI->isCaptured(VarToCapture)91 ) |
118 | 50 | return NoLambdaIsCaptureReady; |
119 | 54 | if (54 IsCapturingThis && 54 !LSI->isCXXThisCaptured()13 ) |
120 | 12 | return NoLambdaIsCaptureReady; |
121 | 353 | } |
122 | 353 | EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC); |
123 | 353 | |
124 | 353 | assert(CurScopeIndex); |
125 | 353 | --CurScopeIndex; |
126 | 317 | } while (!EnclosingDC->isTranslationUnit() && |
127 | 353 | EnclosingDC->isDependentContext() && |
128 | 248 | isLambdaCallOperator(EnclosingDC)); |
129 | 317 | |
130 | 181 | assert(CurScopeIndex < (FunctionScopes.size() - 1)); |
131 | 181 | // If the enclosingDC is not dependent, then the immediately nested lambda |
132 | 181 | // (one index above) is capture-ready. |
133 | 181 | if (!EnclosingDC->isDependentContext()) |
134 | 105 | return CurScopeIndex + 1; |
135 | 76 | return NoLambdaIsCaptureReady; |
136 | 76 | } |
137 | | |
138 | | /// \brief Examines the FunctionScopeInfo stack to determine the nearest |
139 | | /// enclosing lambda (to the current lambda) that is 'capture-capable' for |
140 | | /// the variable referenced in the current lambda (i.e. \p VarToCapture). |
141 | | /// If successful, returns the index into Sema's FunctionScopeInfo stack |
142 | | /// of the capture-capable lambda's LambdaScopeInfo. |
143 | | /// |
144 | | /// Given the current stack of lambdas being processed by Sema and |
145 | | /// the variable of interest, to identify the nearest enclosing lambda (to the |
146 | | /// current lambda at the top of the stack) that can truly capture |
147 | | /// a variable, it has to have the following two properties: |
148 | | /// a) 'capture-ready' - be the innermost lambda that is 'capture-ready': |
149 | | /// - climb down the stack (i.e. starting from the innermost and examining |
150 | | /// each outer lambda step by step) checking if each enclosing |
151 | | /// lambda can either implicitly or explicitly capture the variable. |
152 | | /// Record the first such lambda that is enclosed in a non-dependent |
153 | | /// context. If no such lambda currently exists return failure. |
154 | | /// b) 'capture-capable' - make sure the 'capture-ready' lambda can truly |
155 | | /// capture the variable by checking all its enclosing lambdas: |
156 | | /// - check if all outer lambdas enclosing the 'capture-ready' lambda |
157 | | /// identified above in 'a' can also capture the variable (this is done |
158 | | /// via tryCaptureVariable for variables and CheckCXXThisCapture for |
159 | | /// 'this' by passing in the index of the Lambda identified in step 'a') |
160 | | /// |
161 | | /// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a |
162 | | /// LambdaScopeInfo inherits from). The current/deepest/innermost lambda |
163 | | /// is at the top of the stack. |
164 | | /// |
165 | | /// \param VarToCapture - the variable to capture. If NULL, capture 'this'. |
166 | | /// |
167 | | /// |
168 | | /// \returns An Optional<unsigned> Index that if evaluates to 'true' contains |
169 | | /// the index (into Sema's FunctionScopeInfo stack) of the innermost lambda |
170 | | /// which is capture-capable. If the return value evaluates to 'false' then |
171 | | /// no lambda is capture-capable for \p VarToCapture. |
172 | | |
173 | | Optional<unsigned> clang::getStackIndexOfNearestEnclosingCaptureCapableLambda( |
174 | | ArrayRef<const sema::FunctionScopeInfo *> FunctionScopes, |
175 | 317 | VarDecl *VarToCapture, Sema &S) { |
176 | 317 | |
177 | 317 | const Optional<unsigned> NoLambdaIsCaptureCapable; |
178 | 317 | |
179 | 317 | const Optional<unsigned> OptionalStackIndex = |
180 | 317 | getStackIndexOfNearestEnclosingCaptureReadyLambda(FunctionScopes, |
181 | 317 | VarToCapture); |
182 | 317 | if (!OptionalStackIndex) |
183 | 212 | return NoLambdaIsCaptureCapable; |
184 | 105 | |
185 | 105 | const unsigned IndexOfCaptureReadyLambda = OptionalStackIndex.getValue(); |
186 | 105 | assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) || |
187 | 105 | S.getCurGenericLambda()) && |
188 | 105 | "The capture ready lambda for a potential capture can only be the " |
189 | 105 | "current lambda if it is a generic lambda"); |
190 | 105 | |
191 | 105 | const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI = |
192 | 105 | cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]); |
193 | 105 | |
194 | 105 | // If VarToCapture is null, we are attempting to capture 'this' |
195 | 105 | const bool IsCapturingThis = !VarToCapture; |
196 | 105 | const bool IsCapturingVariable = !IsCapturingThis; |
197 | 105 | |
198 | 105 | if (IsCapturingVariable105 ) { |
199 | 100 | // Check if the capture-ready lambda can truly capture the variable, by |
200 | 100 | // checking whether all enclosing lambdas of the capture-ready lambda allow |
201 | 100 | // the capture - i.e. make sure it is capture-capable. |
202 | 100 | QualType CaptureType, DeclRefType; |
203 | 100 | const bool CanCaptureVariable = |
204 | 100 | !S.tryCaptureVariable(VarToCapture, |
205 | 100 | /*ExprVarIsUsedInLoc*/ SourceLocation(), |
206 | 100 | clang::Sema::TryCapture_Implicit, |
207 | 100 | /*EllipsisLoc*/ SourceLocation(), |
208 | 100 | /*BuildAndDiagnose*/ false, CaptureType, |
209 | 100 | DeclRefType, &IndexOfCaptureReadyLambda); |
210 | 100 | if (!CanCaptureVariable) |
211 | 7 | return NoLambdaIsCaptureCapable; |
212 | 5 | } else { |
213 | 5 | // Check if the capture-ready lambda can truly capture 'this' by checking |
214 | 5 | // whether all enclosing lambdas of the capture-ready lambda can capture |
215 | 5 | // 'this'. |
216 | 5 | const bool CanCaptureThis = |
217 | 5 | !S.CheckCXXThisCapture( |
218 | 5 | CaptureReadyLambdaLSI->PotentialThisCaptureLocation, |
219 | 5 | /*Explicit*/ false, /*BuildAndDiagnose*/ false, |
220 | 5 | &IndexOfCaptureReadyLambda); |
221 | 5 | if (!CanCaptureThis) |
222 | 1 | return NoLambdaIsCaptureCapable; |
223 | 97 | } |
224 | 97 | return IndexOfCaptureReadyLambda; |
225 | 97 | } |
226 | | |
227 | | static inline TemplateParameterList * |
228 | 7.95k | getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef) { |
229 | 7.95k | if (LSI->GLTemplateParameterList) |
230 | 1.96k | return LSI->GLTemplateParameterList; |
231 | 5.98k | |
232 | 5.98k | if (5.98k !LSI->AutoTemplateParams.empty()5.98k ) { |
233 | 811 | SourceRange IntroRange = LSI->IntroducerRange; |
234 | 811 | SourceLocation LAngleLoc = IntroRange.getBegin(); |
235 | 811 | SourceLocation RAngleLoc = IntroRange.getEnd(); |
236 | 811 | LSI->GLTemplateParameterList = TemplateParameterList::Create( |
237 | 811 | SemaRef.Context, |
238 | 811 | /*Template kw loc*/ SourceLocation(), LAngleLoc, |
239 | 811 | llvm::makeArrayRef((NamedDecl *const *)LSI->AutoTemplateParams.data(), |
240 | 811 | LSI->AutoTemplateParams.size()), |
241 | 811 | RAngleLoc, nullptr); |
242 | 811 | } |
243 | 7.95k | return LSI->GLTemplateParameterList; |
244 | 7.95k | } |
245 | | |
246 | | CXXRecordDecl *Sema::createLambdaClosureType(SourceRange IntroducerRange, |
247 | | TypeSourceInfo *Info, |
248 | | bool KnownDependent, |
249 | 3.97k | LambdaCaptureDefault CaptureDefault) { |
250 | 3.97k | DeclContext *DC = CurContext; |
251 | 3.98k | while (!(DC->isFunctionOrMethod() || 3.98k DC->isRecord()468 || DC->isFileContext()212 )) |
252 | 6 | DC = DC->getParent(); |
253 | 3.97k | bool IsGenericLambda = getGenericLambdaTemplateParameterList(getCurLambda(), |
254 | 3.97k | *this); |
255 | 3.97k | // Start constructing the lambda class. |
256 | 3.97k | CXXRecordDecl *Class = CXXRecordDecl::CreateLambda(Context, DC, Info, |
257 | 3.97k | IntroducerRange.getBegin(), |
258 | 3.97k | KnownDependent, |
259 | 3.97k | IsGenericLambda, |
260 | 3.97k | CaptureDefault); |
261 | 3.97k | DC->addDecl(Class); |
262 | 3.97k | |
263 | 3.97k | return Class; |
264 | 3.97k | } |
265 | | |
266 | | /// \brief Determine whether the given context is or is enclosed in an inline |
267 | | /// function. |
268 | 319k | static bool isInInlineFunction(const DeclContext *DC) { |
269 | 381k | while (!DC->isFileContext()381k ) { |
270 | 69.7k | if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC)) |
271 | 12.0k | if (12.0k FD->isInlined()12.0k ) |
272 | 7.87k | return true; |
273 | 61.8k | |
274 | 61.8k | DC = DC->getLexicalParent(); |
275 | 61.8k | } |
276 | 319k | |
277 | 311k | return false; |
278 | 319k | } |
279 | | |
280 | | MangleNumberingContext * |
281 | | Sema::getCurrentMangleNumberContext(const DeclContext *DC, |
282 | 322k | Decl *&ManglingContextDecl) { |
283 | 322k | // Compute the context for allocating mangling numbers in the current |
284 | 322k | // expression, if the ABI requires them. |
285 | 322k | ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl; |
286 | 322k | |
287 | 322k | enum ContextKind { |
288 | 322k | Normal, |
289 | 322k | DefaultArgument, |
290 | 322k | DataMember, |
291 | 322k | StaticDataMember, |
292 | 322k | InlineVariable, |
293 | 322k | VariableTemplate |
294 | 322k | } Kind = Normal; |
295 | 322k | |
296 | 322k | // Default arguments of member function parameters that appear in a class |
297 | 322k | // definition, as well as the initializers of data members, receive special |
298 | 322k | // treatment. Identify them. |
299 | 322k | if (ManglingContextDecl322k ) { |
300 | 963 | if (ParmVarDecl *Param963 = dyn_cast<ParmVarDecl>(ManglingContextDecl)) { |
301 | 146 | if (const DeclContext *LexicalDC |
302 | 146 | = Param->getDeclContext()->getLexicalParent()) |
303 | 121 | if (121 LexicalDC->isRecord()121 ) |
304 | 92 | Kind = DefaultArgument; |
305 | 963 | } else if (VarDecl *817 Var817 = dyn_cast<VarDecl>(ManglingContextDecl)) { |
306 | 727 | if (Var->getDeclContext()->isRecord()) |
307 | 21 | Kind = StaticDataMember; |
308 | 706 | else if (706 Var->getMostRecentDecl()->isInline()706 ) |
309 | 2 | Kind = InlineVariable; |
310 | 704 | else if (704 Var->getDescribedVarTemplate()704 ) |
311 | 5 | Kind = VariableTemplate; |
312 | 699 | else if (auto *699 VTS699 = dyn_cast<VarTemplateSpecializationDecl>(Var)) { |
313 | 5 | if (!VTS->isExplicitSpecialization()) |
314 | 5 | Kind = VariableTemplate; |
315 | 706 | } |
316 | 817 | } else if (90 isa<FieldDecl>(ManglingContextDecl)90 ) { |
317 | 90 | Kind = DataMember; |
318 | 90 | } |
319 | 963 | } |
320 | 322k | |
321 | 322k | // Itanium ABI [5.1.7]: |
322 | 322k | // In the following contexts [...] the one-definition rule requires closure |
323 | 322k | // types in different translation units to "correspond": |
324 | 322k | bool IsInNonspecializedTemplate = |
325 | 321k | inTemplateInstantiation() || CurContext->isDependentContext(); |
326 | 322k | switch (Kind) { |
327 | 322k | case Normal: { |
328 | 322k | // -- the bodies of non-exported nonspecialized template functions |
329 | 322k | // -- the bodies of inline functions |
330 | 322k | if ((IsInNonspecializedTemplate && |
331 | 3.30k | !(ManglingContextDecl && 3.30k isa<ParmVarDecl>(ManglingContextDecl)504 )) || |
332 | 322k | isInInlineFunction(CurContext)319k ) { |
333 | 11.1k | ManglingContextDecl = nullptr; |
334 | 11.4k | while (auto *CD = dyn_cast<CapturedDecl>(DC)) |
335 | 310 | DC = CD->getParent(); |
336 | 11.1k | return &Context.getManglingNumberContext(DC); |
337 | 11.1k | } |
338 | 311k | |
339 | 311k | ManglingContextDecl = nullptr; |
340 | 311k | return nullptr; |
341 | 311k | } |
342 | 311k | |
343 | 21 | case StaticDataMember: |
344 | 21 | // -- the initializers of nonspecialized static members of template classes |
345 | 21 | if (!IsInNonspecializedTemplate21 ) { |
346 | 2 | ManglingContextDecl = nullptr; |
347 | 2 | return nullptr; |
348 | 2 | } |
349 | 19 | // Fall through to get the current context. |
350 | 19 | LLVM_FALLTHROUGH19 ; |
351 | 19 | |
352 | 213 | case DataMember: |
353 | 213 | // -- the in-class initializers of class members |
354 | 213 | case DefaultArgument: |
355 | 213 | // -- default arguments appearing in class definitions |
356 | 213 | case InlineVariable: |
357 | 213 | // -- the initializers of inline variables |
358 | 213 | case VariableTemplate: |
359 | 213 | // -- the initializers of templated variables |
360 | 213 | return &ExprEvalContexts.back().getMangleNumberingContext(Context); |
361 | 0 | } |
362 | 0 |
|
363 | 0 | llvm_unreachable0 ("unexpected context"); |
364 | 0 | } |
365 | | |
366 | | MangleNumberingContext & |
367 | | Sema::ExpressionEvaluationContextRecord::getMangleNumberingContext( |
368 | 213 | ASTContext &Ctx) { |
369 | 213 | assert(ManglingContextDecl && "Need to have a context declaration"); |
370 | 213 | if (!MangleNumbering) |
371 | 201 | MangleNumbering = Ctx.createMangleNumberingContext(); |
372 | 213 | return *MangleNumbering; |
373 | 213 | } |
374 | | |
375 | | CXXMethodDecl *Sema::startLambdaDefinition(CXXRecordDecl *Class, |
376 | | SourceRange IntroducerRange, |
377 | | TypeSourceInfo *MethodTypeInfo, |
378 | | SourceLocation EndLoc, |
379 | | ArrayRef<ParmVarDecl *> Params, |
380 | 3.97k | const bool IsConstexprSpecified) { |
381 | 3.97k | QualType MethodType = MethodTypeInfo->getType(); |
382 | 3.97k | TemplateParameterList *TemplateParams = |
383 | 3.97k | getGenericLambdaTemplateParameterList(getCurLambda(), *this); |
384 | 3.97k | // If a lambda appears in a dependent context or is a generic lambda (has |
385 | 3.97k | // template parameters) and has an 'auto' return type, deduce it to a |
386 | 3.97k | // dependent type. |
387 | 3.97k | if (Class->isDependentContext() || 3.97k TemplateParams2.92k ) { |
388 | 1.94k | const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>(); |
389 | 1.94k | QualType Result = FPT->getReturnType(); |
390 | 1.94k | if (Result->isUndeducedType()1.94k ) { |
391 | 1.30k | Result = SubstAutoType(Result, Context.DependentTy); |
392 | 1.30k | MethodType = Context.getFunctionType(Result, FPT->getParamTypes(), |
393 | 1.30k | FPT->getExtProtoInfo()); |
394 | 1.30k | } |
395 | 1.94k | } |
396 | 3.97k | |
397 | 3.97k | // C++11 [expr.prim.lambda]p5: |
398 | 3.97k | // The closure type for a lambda-expression has a public inline function |
399 | 3.97k | // call operator (13.5.4) whose parameters and return type are described by |
400 | 3.97k | // the lambda-expression's parameter-declaration-clause and |
401 | 3.97k | // trailing-return-type respectively. |
402 | 3.97k | DeclarationName MethodName |
403 | 3.97k | = Context.DeclarationNames.getCXXOperatorName(OO_Call); |
404 | 3.97k | DeclarationNameLoc MethodNameLoc; |
405 | 3.97k | MethodNameLoc.CXXOperatorName.BeginOpNameLoc |
406 | 3.97k | = IntroducerRange.getBegin().getRawEncoding(); |
407 | 3.97k | MethodNameLoc.CXXOperatorName.EndOpNameLoc |
408 | 3.97k | = IntroducerRange.getEnd().getRawEncoding(); |
409 | 3.97k | CXXMethodDecl *Method |
410 | 3.97k | = CXXMethodDecl::Create(Context, Class, EndLoc, |
411 | 3.97k | DeclarationNameInfo(MethodName, |
412 | 3.97k | IntroducerRange.getBegin(), |
413 | 3.97k | MethodNameLoc), |
414 | 3.97k | MethodType, MethodTypeInfo, |
415 | 3.97k | SC_None, |
416 | 3.97k | /*isInline=*/true, |
417 | 3.97k | IsConstexprSpecified, |
418 | 3.97k | EndLoc); |
419 | 3.97k | Method->setAccess(AS_public); |
420 | 3.97k | |
421 | 3.97k | // Temporarily set the lexical declaration context to the current |
422 | 3.97k | // context, so that the Scope stack matches the lexical nesting. |
423 | 3.97k | Method->setLexicalDeclContext(CurContext); |
424 | 3.97k | // Create a function template if we have a template parameter list |
425 | 3.97k | FunctionTemplateDecl *const TemplateMethod = TemplateParams ? |
426 | 1.38k | FunctionTemplateDecl::Create(Context, Class, |
427 | 1.38k | Method->getLocation(), MethodName, |
428 | 1.38k | TemplateParams, |
429 | 3.97k | Method) : nullptr; |
430 | 3.97k | if (TemplateMethod3.97k ) { |
431 | 1.38k | TemplateMethod->setLexicalDeclContext(CurContext); |
432 | 1.38k | TemplateMethod->setAccess(AS_public); |
433 | 1.38k | Method->setDescribedFunctionTemplate(TemplateMethod); |
434 | 1.38k | } |
435 | 3.97k | |
436 | 3.97k | // Add parameters. |
437 | 3.97k | if (!Params.empty()3.97k ) { |
438 | 2.09k | Method->setParams(Params); |
439 | 2.09k | CheckParmsForFunctionDef(Params, |
440 | 2.09k | /*CheckParameterNames=*/false); |
441 | 2.09k | |
442 | 2.09k | for (auto P : Method->parameters()) |
443 | 2.48k | P->setOwningFunction(Method); |
444 | 2.09k | } |
445 | 3.97k | |
446 | 3.97k | Decl *ManglingContextDecl; |
447 | 3.97k | if (MangleNumberingContext *MCtx = |
448 | 3.97k | getCurrentMangleNumberContext(Class->getDeclContext(), |
449 | 2.65k | ManglingContextDecl)) { |
450 | 2.65k | unsigned ManglingNumber = MCtx->getManglingNumber(Method); |
451 | 2.65k | Class->setLambdaMangling(ManglingNumber, ManglingContextDecl); |
452 | 2.65k | } |
453 | 3.97k | |
454 | 3.97k | return Method; |
455 | 3.97k | } |
456 | | |
457 | | void Sema::buildLambdaScope(LambdaScopeInfo *LSI, |
458 | | CXXMethodDecl *CallOperator, |
459 | | SourceRange IntroducerRange, |
460 | | LambdaCaptureDefault CaptureDefault, |
461 | | SourceLocation CaptureDefaultLoc, |
462 | | bool ExplicitParams, |
463 | | bool ExplicitResultType, |
464 | 3.97k | bool Mutable) { |
465 | 3.97k | LSI->CallOperator = CallOperator; |
466 | 3.97k | CXXRecordDecl *LambdaClass = CallOperator->getParent(); |
467 | 3.97k | LSI->Lambda = LambdaClass; |
468 | 3.97k | if (CaptureDefault == LCD_ByCopy) |
469 | 440 | LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval; |
470 | 3.53k | else if (3.53k CaptureDefault == LCD_ByRef3.53k ) |
471 | 589 | LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref; |
472 | 3.97k | LSI->CaptureDefaultLoc = CaptureDefaultLoc; |
473 | 3.97k | LSI->IntroducerRange = IntroducerRange; |
474 | 3.97k | LSI->ExplicitParams = ExplicitParams; |
475 | 3.97k | LSI->Mutable = Mutable; |
476 | 3.97k | |
477 | 3.97k | if (ExplicitResultType3.97k ) { |
478 | 757 | LSI->ReturnType = CallOperator->getReturnType(); |
479 | 757 | |
480 | 757 | if (!LSI->ReturnType->isDependentType() && |
481 | 757 | !LSI->ReturnType->isVoidType()574 ) { |
482 | 348 | if (RequireCompleteType(CallOperator->getLocStart(), LSI->ReturnType, |
483 | 348 | diag::err_lambda_incomplete_result)) { |
484 | 2 | // Do nothing. |
485 | 2 | } |
486 | 348 | } |
487 | 3.97k | } else { |
488 | 3.22k | LSI->HasImplicitReturnType = true; |
489 | 3.22k | } |
490 | 3.97k | } |
491 | | |
492 | 3.97k | void Sema::finishLambdaExplicitCaptures(LambdaScopeInfo *LSI) { |
493 | 3.97k | LSI->finishedExplicitCaptures(); |
494 | 3.97k | } |
495 | | |
496 | 2.80k | void Sema::addLambdaParameters(CXXMethodDecl *CallOperator, Scope *CurScope) { |
497 | 2.80k | // Introduce our parameters into the function scope |
498 | 2.80k | for (unsigned p = 0, NumParams = CallOperator->getNumParams(); |
499 | 4.11k | p < NumParams4.11k ; ++p1.30k ) { |
500 | 1.30k | ParmVarDecl *Param = CallOperator->getParamDecl(p); |
501 | 1.30k | |
502 | 1.30k | // If this has an identifier, add it to the scope stack. |
503 | 1.30k | if (CurScope && 1.30k Param->getIdentifier()1.30k ) { |
504 | 1.24k | CheckShadow(CurScope, Param); |
505 | 1.24k | |
506 | 1.24k | PushOnScopeChains(Param, CurScope); |
507 | 1.24k | } |
508 | 1.30k | } |
509 | 2.80k | } |
510 | | |
511 | | /// If this expression is an enumerator-like expression of some type |
512 | | /// T, return the type T; otherwise, return null. |
513 | | /// |
514 | | /// Pointer comparisons on the result here should always work because |
515 | | /// it's derived from either the parent of an EnumConstantDecl |
516 | | /// (i.e. the definition) or the declaration returned by |
517 | | /// EnumType::getDecl() (i.e. the definition). |
518 | 359 | static EnumDecl *findEnumForBlockReturn(Expr *E) { |
519 | 359 | // An expression is an enumerator-like expression of type T if, |
520 | 359 | // ignoring parens and parens-like expressions: |
521 | 359 | E = E->IgnoreParens(); |
522 | 359 | |
523 | 359 | // - it is an enumerator whose enum type is T or |
524 | 359 | if (DeclRefExpr *DRE359 = dyn_cast<DeclRefExpr>(E)) { |
525 | 27 | if (EnumConstantDecl *D |
526 | 27 | = dyn_cast<EnumConstantDecl>(DRE->getDecl())) { |
527 | 27 | return cast<EnumDecl>(D->getDeclContext()); |
528 | 27 | } |
529 | 0 | return nullptr; |
530 | 0 | } |
531 | 332 | |
532 | 332 | // - it is a comma expression whose RHS is an enumerator-like |
533 | 332 | // expression of type T or |
534 | 332 | if (BinaryOperator *332 BO332 = dyn_cast<BinaryOperator>(E)) { |
535 | 24 | if (BO->getOpcode() == BO_Comma) |
536 | 1 | return findEnumForBlockReturn(BO->getRHS()); |
537 | 23 | return nullptr; |
538 | 23 | } |
539 | 308 | |
540 | 308 | // - it is a statement-expression whose value expression is an |
541 | 308 | // enumerator-like expression of type T or |
542 | 308 | if (StmtExpr *308 SE308 = dyn_cast<StmtExpr>(E)) { |
543 | 1 | if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back())) |
544 | 1 | return findEnumForBlockReturn(last); |
545 | 0 | return nullptr; |
546 | 0 | } |
547 | 307 | |
548 | 307 | // - it is a ternary conditional operator (not the GNU ?: |
549 | 307 | // extension) whose second and third operands are |
550 | 307 | // enumerator-like expressions of type T or |
551 | 307 | if (ConditionalOperator *307 CO307 = dyn_cast<ConditionalOperator>(E)) { |
552 | 3 | if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr())) |
553 | 3 | if (3 ED == findEnumForBlockReturn(CO->getFalseExpr())3 ) |
554 | 3 | return ED; |
555 | 0 | return nullptr; |
556 | 0 | } |
557 | 304 | |
558 | 304 | // (implicitly:) |
559 | 304 | // - it is an implicit integral conversion applied to an |
560 | 304 | // enumerator-like expression of type T or |
561 | 304 | if (ImplicitCastExpr *304 ICE304 = dyn_cast<ImplicitCastExpr>(E)) { |
562 | 129 | // We can sometimes see integral conversions in valid |
563 | 129 | // enumerator-like expressions. |
564 | 129 | if (ICE->getCastKind() == CK_IntegralCast) |
565 | 3 | return findEnumForBlockReturn(ICE->getSubExpr()); |
566 | 301 | |
567 | 301 | // Otherwise, just rely on the type. |
568 | 301 | } |
569 | 301 | |
570 | 301 | // - it is an expression of that formal enum type. |
571 | 301 | if (const EnumType *301 ET301 = E->getType()->getAs<EnumType>()) { |
572 | 15 | return ET->getDecl(); |
573 | 15 | } |
574 | 286 | |
575 | 286 | // Otherwise, nope. |
576 | 286 | return nullptr; |
577 | 286 | } |
578 | | |
579 | | /// Attempt to find a type T for which the returned expression of the |
580 | | /// given statement is an enumerator-like expression of that type. |
581 | 425 | static EnumDecl *findEnumForBlockReturn(ReturnStmt *ret) { |
582 | 425 | if (Expr *retValue = ret->getRetValue()) |
583 | 348 | return findEnumForBlockReturn(retValue); |
584 | 77 | return nullptr; |
585 | 77 | } |
586 | | |
587 | | /// Attempt to find a common type T for which all of the returned |
588 | | /// expressions in a block are enumerator-like expressions of that |
589 | | /// type. |
590 | 410 | static EnumDecl *findCommonEnumForBlockReturns(ArrayRef<ReturnStmt*> returns) { |
591 | 410 | ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end(); |
592 | 410 | |
593 | 410 | // Try to find one for the first return. |
594 | 410 | EnumDecl *ED = findEnumForBlockReturn(*i); |
595 | 410 | if (!ED410 ) return nullptr384 ; |
596 | 26 | |
597 | 26 | // Check that the rest of the returns have the same enum. |
598 | 39 | for (++i; 26 i != e39 ; ++i13 ) { |
599 | 15 | if (findEnumForBlockReturn(*i) != ED) |
600 | 2 | return nullptr; |
601 | 15 | } |
602 | 26 | |
603 | 26 | // Never infer an anonymous enum type. |
604 | 24 | if (24 !ED->hasNameForLinkage()24 ) return nullptr3 ; |
605 | 21 | |
606 | 21 | return ED; |
607 | 21 | } |
608 | | |
609 | | /// Adjust the given return statements so that they formally return |
610 | | /// the given type. It should require, at most, an IntegralCast. |
611 | | static void adjustBlockReturnsToEnum(Sema &S, ArrayRef<ReturnStmt*> returns, |
612 | 21 | QualType returnType) { |
613 | 21 | for (ArrayRef<ReturnStmt*>::iterator |
614 | 55 | i = returns.begin(), e = returns.end(); i != e55 ; ++i34 ) { |
615 | 34 | ReturnStmt *ret = *i; |
616 | 34 | Expr *retValue = ret->getRetValue(); |
617 | 34 | if (S.Context.hasSameType(retValue->getType(), returnType)) |
618 | 14 | continue; |
619 | 20 | |
620 | 20 | // Right now we only support integral fixup casts. |
621 | 34 | assert(returnType->isIntegralOrUnscopedEnumerationType()); |
622 | 20 | assert(retValue->getType()->isIntegralOrUnscopedEnumerationType()); |
623 | 20 | |
624 | 20 | ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue); |
625 | 20 | |
626 | 20 | Expr *E = (cleanups ? cleanups->getSubExpr()0 : retValue20 ); |
627 | 20 | E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast, |
628 | 20 | E, /*base path*/ nullptr, VK_RValue); |
629 | 20 | if (cleanups20 ) { |
630 | 0 | cleanups->setSubExpr(E); |
631 | 20 | } else { |
632 | 20 | ret->setRetValue(E); |
633 | 20 | } |
634 | 34 | } |
635 | 21 | } |
636 | | |
637 | 2.75k | void Sema::deduceClosureReturnType(CapturingScopeInfo &CSI) { |
638 | 2.75k | assert(CSI.HasImplicitReturnType); |
639 | 2.75k | // If it was ever a placeholder, it had to been deduced to DependentTy. |
640 | 2.75k | assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType()); |
641 | 2.75k | assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) && |
642 | 2.75k | "lambda expressions use auto deduction in C++14 onwards"); |
643 | 2.75k | |
644 | 2.75k | // C++ core issue 975: |
645 | 2.75k | // If a lambda-expression does not include a trailing-return-type, |
646 | 2.75k | // it is as if the trailing-return-type denotes the following type: |
647 | 2.75k | // - if there are no return statements in the compound-statement, |
648 | 2.75k | // or all return statements return either an expression of type |
649 | 2.75k | // void or no expression or braced-init-list, the type void; |
650 | 2.75k | // - otherwise, if all return statements return an expression |
651 | 2.75k | // and the types of the returned expressions after |
652 | 2.75k | // lvalue-to-rvalue conversion (4.1 [conv.lval]), |
653 | 2.75k | // array-to-pointer conversion (4.2 [conv.array]), and |
654 | 2.75k | // function-to-pointer conversion (4.3 [conv.func]) are the |
655 | 2.75k | // same, that common type; |
656 | 2.75k | // - otherwise, the program is ill-formed. |
657 | 2.75k | // |
658 | 2.75k | // C++ core issue 1048 additionally removes top-level cv-qualifiers |
659 | 2.75k | // from the types of returned expressions to match the C++14 auto |
660 | 2.75k | // deduction rules. |
661 | 2.75k | // |
662 | 2.75k | // In addition, in blocks in non-C++ modes, if all of the return |
663 | 2.75k | // statements are enumerator-like expressions of some type T, where |
664 | 2.75k | // T has a name for linkage, then we infer the return type of the |
665 | 2.75k | // block to be that type. |
666 | 2.75k | |
667 | 2.75k | // First case: no return statements, implicit void return type. |
668 | 2.75k | ASTContext &Ctx = getASTContext(); |
669 | 2.75k | if (CSI.Returns.empty()2.75k ) { |
670 | 1.98k | // It's possible there were simply no /valid/ return statements. |
671 | 1.98k | // In this case, the first one we found may have at least given us a type. |
672 | 1.98k | if (CSI.ReturnType.isNull()) |
673 | 1.98k | CSI.ReturnType = Ctx.VoidTy; |
674 | 1.98k | return; |
675 | 1.98k | } |
676 | 775 | |
677 | 775 | // Second case: at least one return statement has dependent type. |
678 | 775 | // Delay type checking until instantiation. |
679 | 2.75k | assert(!CSI.ReturnType.isNull() && "We should have a tentative return type."); |
680 | 775 | if (CSI.ReturnType->isDependentType()) |
681 | 49 | return; |
682 | 726 | |
683 | 726 | // Try to apply the enum-fuzz rule. |
684 | 726 | if (726 !getLangOpts().CPlusPlus726 ) { |
685 | 410 | assert(isa<BlockScopeInfo>(CSI)); |
686 | 410 | const EnumDecl *ED = findCommonEnumForBlockReturns(CSI.Returns); |
687 | 410 | if (ED410 ) { |
688 | 21 | CSI.ReturnType = Context.getTypeDeclType(ED); |
689 | 21 | adjustBlockReturnsToEnum(*this, CSI.Returns, CSI.ReturnType); |
690 | 21 | return; |
691 | 21 | } |
692 | 705 | } |
693 | 705 | |
694 | 705 | // Third case: only one return statement. Don't bother doing extra work! |
695 | 705 | SmallVectorImpl<ReturnStmt*>::iterator I = CSI.Returns.begin(), |
696 | 705 | E = CSI.Returns.end(); |
697 | 705 | if (I+1 == E) |
698 | 684 | return; |
699 | 21 | |
700 | 21 | // General case: many return statements. |
701 | 21 | // Check that they all have compatible return types. |
702 | 21 | |
703 | 21 | // We require the return types to strictly match here. |
704 | 21 | // Note that we've already done the required promotions as part of |
705 | 21 | // processing the return statement. |
706 | 68 | for (; 21 I != E68 ; ++I47 ) { |
707 | 47 | const ReturnStmt *RS = *I; |
708 | 47 | const Expr *RetE = RS->getRetValue(); |
709 | 47 | |
710 | 47 | QualType ReturnType = |
711 | 47 | (RetE ? RetE->getType()42 : Context.VoidTy5 ).getUnqualifiedType(); |
712 | 47 | if (Context.getCanonicalFunctionResultType(ReturnType) == |
713 | 47 | Context.getCanonicalFunctionResultType(CSI.ReturnType)) |
714 | 38 | continue; |
715 | 9 | |
716 | 9 | // FIXME: This is a poor diagnostic for ReturnStmts without expressions. |
717 | 9 | // TODO: It's possible that the *first* return is the divergent one. |
718 | 9 | Diag(RS->getLocStart(), |
719 | 9 | diag::err_typecheck_missing_return_type_incompatible) |
720 | 9 | << ReturnType << CSI.ReturnType |
721 | 9 | << isa<LambdaScopeInfo>(CSI); |
722 | 9 | // Continue iterating so that we keep emitting diagnostics. |
723 | 9 | } |
724 | 2.75k | } |
725 | | |
726 | | QualType Sema::buildLambdaInitCaptureInitialization(SourceLocation Loc, |
727 | | bool ByRef, |
728 | | IdentifierInfo *Id, |
729 | | bool IsDirectInit, |
730 | 265 | Expr *&Init) { |
731 | 265 | // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to |
732 | 265 | // deduce against. |
733 | 265 | QualType DeductType = Context.getAutoDeductType(); |
734 | 265 | TypeLocBuilder TLB; |
735 | 265 | TLB.pushTypeSpec(DeductType).setNameLoc(Loc); |
736 | 265 | if (ByRef265 ) { |
737 | 49 | DeductType = BuildReferenceType(DeductType, true, Loc, Id); |
738 | 49 | assert(!DeductType.isNull() && "can't build reference to auto"); |
739 | 49 | TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc); |
740 | 49 | } |
741 | 265 | TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType); |
742 | 265 | |
743 | 265 | // Deduce the type of the init capture. |
744 | 265 | QualType DeducedType = deduceVarTypeFromInitializer( |
745 | 265 | /*VarDecl*/nullptr, DeclarationName(Id), DeductType, TSI, |
746 | 265 | SourceRange(Loc, Loc), IsDirectInit, Init); |
747 | 265 | if (DeducedType.isNull()) |
748 | 31 | return QualType(); |
749 | 234 | |
750 | 234 | // Are we a non-list direct initialization? |
751 | 234 | ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init); |
752 | 234 | |
753 | 234 | // Perform initialization analysis and ensure any implicit conversions |
754 | 234 | // (such as lvalue-to-rvalue) are enforced. |
755 | 234 | InitializedEntity Entity = |
756 | 234 | InitializedEntity::InitializeLambdaCapture(Id, DeducedType, Loc); |
757 | 234 | InitializationKind Kind = |
758 | 234 | IsDirectInit |
759 | 88 | ? (CXXDirectInit ? 88 InitializationKind::CreateDirect( |
760 | 84 | Loc, Init->getLocStart(), Init->getLocEnd()) |
761 | 88 | : InitializationKind::CreateDirectList(Loc)) |
762 | 146 | : InitializationKind::CreateCopy(Loc, Init->getLocStart()); |
763 | 234 | |
764 | 234 | MultiExprArg Args = Init; |
765 | 234 | if (CXXDirectInit) |
766 | 84 | Args = |
767 | 84 | MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs()); |
768 | 234 | QualType DclT; |
769 | 234 | InitializationSequence InitSeq(*this, Entity, Kind, Args); |
770 | 234 | ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT); |
771 | 234 | |
772 | 234 | if (Result.isInvalid()) |
773 | 2 | return QualType(); |
774 | 232 | Init = Result.getAs<Expr>(); |
775 | 232 | |
776 | 232 | // The init-capture initialization is a full-expression that must be |
777 | 232 | // processed as one before we enter the declcontext of the lambda's |
778 | 232 | // call-operator. |
779 | 232 | Result = ActOnFinishFullExpr(Init, Loc, /*DiscardedValue*/ false, |
780 | 232 | /*IsConstexpr*/ false, |
781 | 232 | /*IsLambdaInitCaptureInitializer*/ true); |
782 | 232 | if (Result.isInvalid()) |
783 | 0 | return QualType(); |
784 | 232 | |
785 | 232 | Init = Result.getAs<Expr>(); |
786 | 232 | return DeducedType; |
787 | 232 | } |
788 | | |
789 | | VarDecl *Sema::createLambdaInitCaptureVarDecl(SourceLocation Loc, |
790 | | QualType InitCaptureType, |
791 | | IdentifierInfo *Id, |
792 | 224 | unsigned InitStyle, Expr *Init) { |
793 | 224 | TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType, |
794 | 224 | Loc); |
795 | 224 | // Create a dummy variable representing the init-capture. This is not actually |
796 | 224 | // used as a variable, and only exists as a way to name and refer to the |
797 | 224 | // init-capture. |
798 | 224 | // FIXME: Pass in separate source locations for '&' and identifier. |
799 | 224 | VarDecl *NewVD = VarDecl::Create(Context, CurContext, Loc, |
800 | 224 | Loc, Id, InitCaptureType, TSI, SC_Auto); |
801 | 224 | NewVD->setInitCapture(true); |
802 | 224 | NewVD->setReferenced(true); |
803 | 224 | // FIXME: Pass in a VarDecl::InitializationStyle. |
804 | 224 | NewVD->setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle)); |
805 | 224 | NewVD->markUsed(Context); |
806 | 224 | NewVD->setInit(Init); |
807 | 224 | return NewVD; |
808 | 224 | } |
809 | | |
810 | 222 | FieldDecl *Sema::buildInitCaptureField(LambdaScopeInfo *LSI, VarDecl *Var) { |
811 | 222 | FieldDecl *Field = FieldDecl::Create( |
812 | 222 | Context, LSI->Lambda, Var->getLocation(), Var->getLocation(), |
813 | 222 | nullptr, Var->getType(), Var->getTypeSourceInfo(), nullptr, false, |
814 | 222 | ICIS_NoInit); |
815 | 222 | Field->setImplicit(true); |
816 | 222 | Field->setAccess(AS_private); |
817 | 222 | LSI->Lambda->addDecl(Field); |
818 | 222 | |
819 | 222 | LSI->addCapture(Var, /*isBlock*/false, Var->getType()->isReferenceType(), |
820 | 222 | /*isNested*/false, Var->getLocation(), SourceLocation(), |
821 | 222 | Var->getType(), Var->getInit()); |
822 | 222 | return Field; |
823 | 222 | } |
824 | | |
825 | | void Sema::ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, |
826 | | Declarator &ParamInfo, |
827 | 2.80k | Scope *CurScope) { |
828 | 2.80k | // Determine if we're within a context where we know that the lambda will |
829 | 2.80k | // be dependent, because there are template parameters in scope. |
830 | 2.80k | bool KnownDependent = false; |
831 | 2.80k | LambdaScopeInfo *const LSI = getCurLambda(); |
832 | 2.80k | assert(LSI && "LambdaScopeInfo should be on stack!"); |
833 | 2.80k | |
834 | 2.80k | // The lambda-expression's closure type might be dependent even if its |
835 | 2.80k | // semantic context isn't, if it appears within a default argument of a |
836 | 2.80k | // function template. |
837 | 2.80k | if (CurScope->getTemplateParamParent()) |
838 | 558 | KnownDependent = true; |
839 | 2.80k | |
840 | 2.80k | // Determine the signature of the call operator. |
841 | 2.80k | TypeSourceInfo *MethodTyInfo; |
842 | 2.80k | bool ExplicitParams = true; |
843 | 2.80k | bool ExplicitResultType = true; |
844 | 2.80k | bool ContainsUnexpandedParameterPack = false; |
845 | 2.80k | SourceLocation EndLoc; |
846 | 2.80k | SmallVector<ParmVarDecl *, 8> Params; |
847 | 2.80k | if (ParamInfo.getNumTypeObjects() == 02.80k ) { |
848 | 830 | // C++11 [expr.prim.lambda]p4: |
849 | 830 | // If a lambda-expression does not include a lambda-declarator, it is as |
850 | 830 | // if the lambda-declarator were (). |
851 | 830 | FunctionProtoType::ExtProtoInfo EPI(Context.getDefaultCallingConvention( |
852 | 830 | /*IsVariadic=*/false, /*IsCXXMethod=*/true)); |
853 | 830 | EPI.HasTrailingReturn = true; |
854 | 830 | EPI.TypeQuals |= DeclSpec::TQ_const; |
855 | 830 | // C++1y [expr.prim.lambda]: |
856 | 830 | // The lambda return type is 'auto', which is replaced by the |
857 | 830 | // trailing-return type if provided and/or deduced from 'return' |
858 | 830 | // statements |
859 | 830 | // We don't do this before C++1y, because we don't support deduced return |
860 | 830 | // types there. |
861 | 830 | QualType DefaultTypeForNoTrailingReturn = |
862 | 442 | getLangOpts().CPlusPlus14 ? Context.getAutoDeductType() |
863 | 388 | : Context.DependentTy; |
864 | 830 | QualType MethodTy = |
865 | 830 | Context.getFunctionType(DefaultTypeForNoTrailingReturn, None, EPI); |
866 | 830 | MethodTyInfo = Context.getTrivialTypeSourceInfo(MethodTy); |
867 | 830 | ExplicitParams = false; |
868 | 830 | ExplicitResultType = false; |
869 | 830 | EndLoc = Intro.Range.getEnd(); |
870 | 2.80k | } else { |
871 | 1.97k | assert(ParamInfo.isFunctionDeclarator() && |
872 | 1.97k | "lambda-declarator is a function"); |
873 | 1.97k | DeclaratorChunk::FunctionTypeInfo &FTI = ParamInfo.getFunctionTypeInfo(); |
874 | 1.97k | |
875 | 1.97k | // C++11 [expr.prim.lambda]p5: |
876 | 1.97k | // This function call operator is declared const (9.3.1) if and only if |
877 | 1.97k | // the lambda-expression's parameter-declaration-clause is not followed |
878 | 1.97k | // by mutable. It is neither virtual nor declared volatile. [...] |
879 | 1.97k | if (!FTI.hasMutableQualifier()) |
880 | 1.85k | FTI.TypeQuals |= DeclSpec::TQ_const; |
881 | 1.97k | |
882 | 1.97k | MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope); |
883 | 1.97k | assert(MethodTyInfo && "no type from lambda-declarator"); |
884 | 1.97k | EndLoc = ParamInfo.getSourceRange().getEnd(); |
885 | 1.97k | |
886 | 1.97k | ExplicitResultType = FTI.hasTrailingReturnType(); |
887 | 1.97k | |
888 | 1.97k | if (FTIHasNonVoidParameters(FTI)1.97k ) { |
889 | 1.21k | Params.reserve(FTI.NumParams); |
890 | 2.52k | for (unsigned i = 0, e = FTI.NumParams; i != e2.52k ; ++i1.30k ) |
891 | 1.30k | Params.push_back(cast<ParmVarDecl>(FTI.Params[i].Param)); |
892 | 1.21k | } |
893 | 1.97k | |
894 | 1.97k | // Check for unexpanded parameter packs in the method type. |
895 | 1.97k | if (MethodTyInfo->getType()->containsUnexpandedParameterPack()) |
896 | 10 | ContainsUnexpandedParameterPack = true; |
897 | 1.97k | } |
898 | 2.80k | |
899 | 2.80k | CXXRecordDecl *Class = createLambdaClosureType(Intro.Range, MethodTyInfo, |
900 | 2.80k | KnownDependent, Intro.Default); |
901 | 2.80k | |
902 | 2.80k | CXXMethodDecl *Method = |
903 | 2.80k | startLambdaDefinition(Class, Intro.Range, MethodTyInfo, EndLoc, Params, |
904 | 2.80k | ParamInfo.getDeclSpec().isConstexprSpecified()); |
905 | 2.80k | if (ExplicitParams) |
906 | 1.97k | CheckCXXDefaultArguments(Method); |
907 | 2.80k | |
908 | 2.80k | // Attributes on the lambda apply to the method. |
909 | 2.80k | ProcessDeclAttributes(CurScope, Method, ParamInfo); |
910 | 2.80k | |
911 | 2.80k | // CUDA lambdas get implicit attributes based on the scope in which they're |
912 | 2.80k | // declared. |
913 | 2.80k | if (getLangOpts().CUDA) |
914 | 82 | CUDASetLambdaAttrs(Method); |
915 | 2.80k | |
916 | 2.80k | // Introduce the function call operator as the current declaration context. |
917 | 2.80k | PushDeclContext(CurScope, Method); |
918 | 2.80k | |
919 | 2.80k | // Build the lambda scope. |
920 | 2.80k | buildLambdaScope(LSI, Method, Intro.Range, Intro.Default, Intro.DefaultLoc, |
921 | 2.80k | ExplicitParams, ExplicitResultType, !Method->isConst()); |
922 | 2.80k | |
923 | 2.80k | // C++11 [expr.prim.lambda]p9: |
924 | 2.80k | // A lambda-expression whose smallest enclosing scope is a block scope is a |
925 | 2.80k | // local lambda expression; any other lambda expression shall not have a |
926 | 2.80k | // capture-default or simple-capture in its lambda-introducer. |
927 | 2.80k | // |
928 | 2.80k | // For simple-captures, this is covered by the check below that any named |
929 | 2.80k | // entity is a variable that can be captured. |
930 | 2.80k | // |
931 | 2.80k | // For DR1632, we also allow a capture-default in any context where we can |
932 | 2.80k | // odr-use 'this' (in particular, in a default initializer for a non-static |
933 | 2.80k | // data member). |
934 | 2.80k | if (Intro.Default != LCD_None && 2.80k !Class->getParent()->isFunctionOrMethod()824 && |
935 | 17 | (getCurrentThisType().isNull() || |
936 | 13 | CheckCXXThisCapture(SourceLocation(), /*Explicit*/true, |
937 | 13 | /*BuildAndDiagnose*/false))) |
938 | 4 | Diag(Intro.DefaultLoc, diag::err_capture_default_non_local); |
939 | 2.80k | |
940 | 2.80k | // Distinct capture names, for diagnostics. |
941 | 2.80k | llvm::SmallSet<IdentifierInfo*, 8> CaptureNames; |
942 | 2.80k | |
943 | 2.80k | // Handle explicit captures. |
944 | 2.80k | SourceLocation PrevCaptureLoc |
945 | 2.80k | = Intro.Default == LCD_None? Intro.Range.getBegin()1.98k : Intro.DefaultLoc824 ; |
946 | 3.66k | for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E; |
947 | 2.80k | PrevCaptureLoc = C->Loc, ++C860 ) { |
948 | 860 | if (C->Kind == LCK_This || 860 C->Kind == LCK_StarThis683 ) { |
949 | 275 | if (C->Kind == LCK_StarThis) |
950 | 98 | Diag(C->Loc, !getLangOpts().CPlusPlus1z |
951 | 1 | ? diag::ext_star_this_lambda_capture_cxx17 |
952 | 98 | : diag::warn_cxx14_compat_star_this_lambda_capture); |
953 | 275 | |
954 | 275 | // C++11 [expr.prim.lambda]p8: |
955 | 275 | // An identifier or this shall not appear more than once in a |
956 | 275 | // lambda-capture. |
957 | 275 | if (LSI->isCXXThisCaptured()275 ) { |
958 | 5 | Diag(C->Loc, diag::err_capture_more_than_once) |
959 | 5 | << "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation()) |
960 | 5 | << FixItHint::CreateRemoval( |
961 | 5 | SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc)); |
962 | 5 | continue; |
963 | 5 | } |
964 | 270 | |
965 | 270 | // C++2a [expr.prim.lambda]p8: |
966 | 270 | // If a lambda-capture includes a capture-default that is =, |
967 | 270 | // each simple-capture of that lambda-capture shall be of the form |
968 | 270 | // "&identifier", "this", or "* this". [ Note: The form [&,this] is |
969 | 270 | // redundant but accepted for compatibility with ISO C++14. --end note ] |
970 | 270 | if (270 Intro.Default == LCD_ByCopy && 270 C->Kind != LCK_StarThis9 ) |
971 | 5 | Diag(C->Loc, !getLangOpts().CPlusPlus2a |
972 | 3 | ? diag::ext_equals_this_lambda_capture_cxx2a |
973 | 5 | : diag::warn_cxx17_compat_equals_this_lambda_capture); |
974 | 270 | |
975 | 270 | // C++11 [expr.prim.lambda]p12: |
976 | 270 | // If this is captured by a local lambda expression, its nearest |
977 | 270 | // enclosing function shall be a non-static member function. |
978 | 270 | QualType ThisCaptureType = getCurrentThisType(); |
979 | 270 | if (ThisCaptureType.isNull()270 ) { |
980 | 3 | Diag(C->Loc, diag::err_this_capture) << true; |
981 | 3 | continue; |
982 | 3 | } |
983 | 267 | |
984 | 267 | CheckCXXThisCapture(C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true, |
985 | 267 | /*FunctionScopeIndexToStopAtPtr*/ nullptr, |
986 | 267 | C->Kind == LCK_StarThis); |
987 | 267 | continue; |
988 | 267 | } |
989 | 585 | |
990 | 860 | assert(C->Id && "missing identifier for capture"); |
991 | 585 | |
992 | 585 | if (C->Init.isInvalid()) |
993 | 3 | continue; |
994 | 582 | |
995 | 582 | VarDecl *Var = nullptr; |
996 | 582 | if (C->Init.isUsable()582 ) { |
997 | 184 | Diag(C->Loc, getLangOpts().CPlusPlus14 |
998 | 148 | ? diag::warn_cxx11_compat_init_capture |
999 | 36 | : diag::ext_init_capture); |
1000 | 184 | |
1001 | 184 | if (C->Init.get()->containsUnexpandedParameterPack()) |
1002 | 8 | ContainsUnexpandedParameterPack = true; |
1003 | 184 | // If the initializer expression is usable, but the InitCaptureType |
1004 | 184 | // is not, then an error has occurred - so ignore the capture for now. |
1005 | 184 | // for e.g., [n{0}] { }; <-- if no <initializer_list> is included. |
1006 | 184 | // FIXME: we should create the init capture variable and mark it invalid |
1007 | 184 | // in this case. |
1008 | 184 | if (C->InitCaptureType.get().isNull()) |
1009 | 27 | continue; |
1010 | 157 | |
1011 | 157 | unsigned InitStyle; |
1012 | 157 | switch (C->InitKind) { |
1013 | 0 | case LambdaCaptureInitKind::NoInit: |
1014 | 0 | llvm_unreachable("not an init-capture?"); |
1015 | 99 | case LambdaCaptureInitKind::CopyInit: |
1016 | 99 | InitStyle = VarDecl::CInit; |
1017 | 99 | break; |
1018 | 54 | case LambdaCaptureInitKind::DirectInit: |
1019 | 54 | InitStyle = VarDecl::CallInit; |
1020 | 54 | break; |
1021 | 4 | case LambdaCaptureInitKind::ListInit: |
1022 | 4 | InitStyle = VarDecl::ListInit; |
1023 | 4 | break; |
1024 | 157 | } |
1025 | 157 | Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(), |
1026 | 157 | C->Id, InitStyle, C->Init.get()); |
1027 | 157 | // C++1y [expr.prim.lambda]p11: |
1028 | 157 | // An init-capture behaves as if it declares and explicitly |
1029 | 157 | // captures a variable [...] whose declarative region is the |
1030 | 157 | // lambda-expression's compound-statement |
1031 | 157 | if (Var) |
1032 | 157 | PushOnScopeChains(Var, CurScope, false); |
1033 | 582 | } else { |
1034 | 398 | assert(C->InitKind == LambdaCaptureInitKind::NoInit && |
1035 | 398 | "init capture has valid but null init?"); |
1036 | 398 | |
1037 | 398 | // C++11 [expr.prim.lambda]p8: |
1038 | 398 | // If a lambda-capture includes a capture-default that is &, the |
1039 | 398 | // identifiers in the lambda-capture shall not be preceded by &. |
1040 | 398 | // If a lambda-capture includes a capture-default that is =, [...] |
1041 | 398 | // each identifier it contains shall be preceded by &. |
1042 | 398 | if (C->Kind == LCK_ByRef && 398 Intro.Default == LCD_ByRef113 ) { |
1043 | 6 | Diag(C->Loc, diag::err_reference_capture_with_reference_default) |
1044 | 6 | << FixItHint::CreateRemoval( |
1045 | 6 | SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc)); |
1046 | 6 | continue; |
1047 | 392 | } else if (392 C->Kind == LCK_ByCopy && 392 Intro.Default == LCD_ByCopy285 ) { |
1048 | 1 | Diag(C->Loc, diag::err_copy_capture_with_copy_default) |
1049 | 1 | << FixItHint::CreateRemoval( |
1050 | 1 | SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc)); |
1051 | 1 | continue; |
1052 | 1 | } |
1053 | 391 | |
1054 | 391 | // C++11 [expr.prim.lambda]p10: |
1055 | 391 | // The identifiers in a capture-list are looked up using the usual |
1056 | 391 | // rules for unqualified name lookup (3.4.1) |
1057 | 391 | DeclarationNameInfo Name(C->Id, C->Loc); |
1058 | 391 | LookupResult R(*this, Name, LookupOrdinaryName); |
1059 | 391 | LookupName(R, CurScope); |
1060 | 391 | if (R.isAmbiguous()) |
1061 | 1 | continue; |
1062 | 390 | if (390 R.empty()390 ) { |
1063 | 1 | // FIXME: Disable corrections that would add qualification? |
1064 | 1 | CXXScopeSpec ScopeSpec; |
1065 | 1 | if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, |
1066 | 1 | llvm::make_unique<DeclFilterCCC<VarDecl>>())) |
1067 | 0 | continue; |
1068 | 390 | } |
1069 | 390 | |
1070 | 390 | Var = R.getAsSingle<VarDecl>(); |
1071 | 390 | if (Var && 390 DiagnoseUseOfDecl(Var, C->Loc)386 ) |
1072 | 1 | continue; |
1073 | 546 | } |
1074 | 546 | |
1075 | 546 | // C++11 [expr.prim.lambda]p8: |
1076 | 546 | // An identifier or this shall not appear more than once in a |
1077 | 546 | // lambda-capture. |
1078 | 546 | if (546 !CaptureNames.insert(C->Id).second546 ) { |
1079 | 9 | if (Var && 9 LSI->isCaptured(Var)9 ) { |
1080 | 7 | Diag(C->Loc, diag::err_capture_more_than_once) |
1081 | 7 | << C->Id << SourceRange(LSI->getCapture(Var).getLocation()) |
1082 | 7 | << FixItHint::CreateRemoval( |
1083 | 7 | SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc)); |
1084 | 7 | } else |
1085 | 9 | // Previous capture captured something different (one or both was |
1086 | 9 | // an init-cpature): no fixit. |
1087 | 2 | Diag(C->Loc, diag::err_capture_more_than_once) << C->Id; |
1088 | 9 | continue; |
1089 | 9 | } |
1090 | 537 | |
1091 | 537 | // C++11 [expr.prim.lambda]p10: |
1092 | 537 | // [...] each such lookup shall find a variable with automatic storage |
1093 | 537 | // duration declared in the reaching scope of the local lambda expression. |
1094 | 537 | // Note that the 'reaching scope' check happens in tryCaptureVariable(). |
1095 | 537 | if (537 !Var537 ) { |
1096 | 4 | Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id; |
1097 | 4 | continue; |
1098 | 4 | } |
1099 | 533 | |
1100 | 533 | // Ignore invalid decls; they'll just confuse the code later. |
1101 | 533 | if (533 Var->isInvalidDecl()533 ) |
1102 | 3 | continue; |
1103 | 530 | |
1104 | 530 | if (530 !Var->hasLocalStorage()530 ) { |
1105 | 2 | Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id; |
1106 | 2 | Diag(Var->getLocation(), diag::note_previous_decl) << C->Id; |
1107 | 2 | continue; |
1108 | 2 | } |
1109 | 528 | |
1110 | 528 | // C++11 [expr.prim.lambda]p23: |
1111 | 528 | // A capture followed by an ellipsis is a pack expansion (14.5.3). |
1112 | 528 | SourceLocation EllipsisLoc; |
1113 | 528 | if (C->EllipsisLoc.isValid()528 ) { |
1114 | 23 | if (Var->isParameterPack()23 ) { |
1115 | 21 | EllipsisLoc = C->EllipsisLoc; |
1116 | 23 | } else { |
1117 | 2 | Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs) |
1118 | 2 | << SourceRange(C->Loc); |
1119 | 2 | |
1120 | 2 | // Just ignore the ellipsis. |
1121 | 2 | } |
1122 | 528 | } else if (505 Var->isParameterPack()505 ) { |
1123 | 9 | ContainsUnexpandedParameterPack = true; |
1124 | 9 | } |
1125 | 528 | |
1126 | 528 | if (C->Init.isUsable()528 ) { |
1127 | 155 | buildInitCaptureField(LSI, Var); |
1128 | 528 | } else { |
1129 | 103 | TryCaptureKind Kind = C->Kind == LCK_ByRef ? TryCapture_ExplicitByRef : |
1130 | 270 | TryCapture_ExplicitByVal; |
1131 | 373 | tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc); |
1132 | 373 | } |
1133 | 860 | } |
1134 | 2.80k | finishLambdaExplicitCaptures(LSI); |
1135 | 2.80k | |
1136 | 2.80k | LSI->ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack; |
1137 | 2.80k | |
1138 | 2.80k | // Add lambda parameters into scope. |
1139 | 2.80k | addLambdaParameters(Method, CurScope); |
1140 | 2.80k | |
1141 | 2.80k | // Enter a new evaluation context to insulate the lambda from any |
1142 | 2.80k | // cleanups from the enclosing full-expression. |
1143 | 2.80k | PushExpressionEvaluationContext( |
1144 | 2.80k | ExpressionEvaluationContext::PotentiallyEvaluated); |
1145 | 2.80k | } |
1146 | | |
1147 | | void Sema::ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, |
1148 | 38 | bool IsInstantiation) { |
1149 | 38 | LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(FunctionScopes.back()); |
1150 | 38 | |
1151 | 38 | // Leave the expression-evaluation context. |
1152 | 38 | DiscardCleanupsInEvaluationContext(); |
1153 | 38 | PopExpressionEvaluationContext(); |
1154 | 38 | |
1155 | 38 | // Leave the context of the lambda. |
1156 | 38 | if (!IsInstantiation) |
1157 | 24 | PopDeclContext(); |
1158 | 38 | |
1159 | 38 | // Finalize the lambda. |
1160 | 38 | CXXRecordDecl *Class = LSI->Lambda; |
1161 | 38 | Class->setInvalidDecl(); |
1162 | 38 | SmallVector<Decl*, 4> Fields(Class->fields()); |
1163 | 38 | ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(), |
1164 | 38 | SourceLocation(), nullptr); |
1165 | 38 | CheckCompletedCXXClass(Class); |
1166 | 38 | |
1167 | 38 | PopFunctionScopeInfo(); |
1168 | 38 | } |
1169 | | |
1170 | | /// \brief Add a lambda's conversion to function pointer, as described in |
1171 | | /// C++11 [expr.prim.lambda]p6. |
1172 | | static void addFunctionPointerConversion(Sema &S, |
1173 | | SourceRange IntroducerRange, |
1174 | | CXXRecordDecl *Class, |
1175 | 2.09k | CXXMethodDecl *CallOperator) { |
1176 | 2.09k | // This conversion is explicitly disabled if the lambda's function has |
1177 | 2.09k | // pass_object_size attributes on any of its parameters. |
1178 | 1.97k | auto HasPassObjectSizeAttr = [](const ParmVarDecl *P) { |
1179 | 1.97k | return P->hasAttr<PassObjectSizeAttr>(); |
1180 | 1.97k | }; |
1181 | 2.09k | if (llvm::any_of(CallOperator->parameters(), HasPassObjectSizeAttr)) |
1182 | 2 | return; |
1183 | 2.09k | |
1184 | 2.09k | // Add the conversion to function pointer. |
1185 | 2.09k | const FunctionProtoType *CallOpProto = |
1186 | 2.09k | CallOperator->getType()->getAs<FunctionProtoType>(); |
1187 | 2.09k | const FunctionProtoType::ExtProtoInfo CallOpExtInfo = |
1188 | 2.09k | CallOpProto->getExtProtoInfo(); |
1189 | 2.09k | QualType PtrToFunctionTy; |
1190 | 2.09k | QualType InvokerFunctionTy; |
1191 | 2.09k | { |
1192 | 2.09k | FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo; |
1193 | 2.09k | CallingConv CC = S.Context.getDefaultCallingConvention( |
1194 | 2.09k | CallOpProto->isVariadic(), /*IsCXXMethod=*/false); |
1195 | 2.09k | InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC); |
1196 | 2.09k | InvokerExtInfo.TypeQuals = 0; |
1197 | 2.09k | assert(InvokerExtInfo.RefQualifier == RQ_None && |
1198 | 2.09k | "Lambda's call operator should not have a reference qualifier"); |
1199 | 2.09k | InvokerFunctionTy = |
1200 | 2.09k | S.Context.getFunctionType(CallOpProto->getReturnType(), |
1201 | 2.09k | CallOpProto->getParamTypes(), InvokerExtInfo); |
1202 | 2.09k | PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy); |
1203 | 2.09k | } |
1204 | 2.09k | |
1205 | 2.09k | // Create the type of the conversion function. |
1206 | 2.09k | FunctionProtoType::ExtProtoInfo ConvExtInfo( |
1207 | 2.09k | S.Context.getDefaultCallingConvention( |
1208 | 2.09k | /*IsVariadic=*/false, /*IsCXXMethod=*/true)); |
1209 | 2.09k | // The conversion function is always const. |
1210 | 2.09k | ConvExtInfo.TypeQuals = Qualifiers::Const; |
1211 | 2.09k | QualType ConvTy = |
1212 | 2.09k | S.Context.getFunctionType(PtrToFunctionTy, None, ConvExtInfo); |
1213 | 2.09k | |
1214 | 2.09k | SourceLocation Loc = IntroducerRange.getBegin(); |
1215 | 2.09k | DeclarationName ConversionName |
1216 | 2.09k | = S.Context.DeclarationNames.getCXXConversionFunctionName( |
1217 | 2.09k | S.Context.getCanonicalType(PtrToFunctionTy)); |
1218 | 2.09k | DeclarationNameLoc ConvNameLoc; |
1219 | 2.09k | // Construct a TypeSourceInfo for the conversion function, and wire |
1220 | 2.09k | // all the parameters appropriately for the FunctionProtoTypeLoc |
1221 | 2.09k | // so that everything works during transformation/instantiation of |
1222 | 2.09k | // generic lambdas. |
1223 | 2.09k | // The main reason for wiring up the parameters of the conversion |
1224 | 2.09k | // function with that of the call operator is so that constructs |
1225 | 2.09k | // like the following work: |
1226 | 2.09k | // auto L = [](auto b) { <-- 1 |
1227 | 2.09k | // return [](auto a) -> decltype(a) { <-- 2 |
1228 | 2.09k | // return a; |
1229 | 2.09k | // }; |
1230 | 2.09k | // }; |
1231 | 2.09k | // int (*fp)(int) = L(5); |
1232 | 2.09k | // Because the trailing return type can contain DeclRefExprs that refer |
1233 | 2.09k | // to the original call operator's variables, we hijack the call |
1234 | 2.09k | // operators ParmVarDecls below. |
1235 | 2.09k | TypeSourceInfo *ConvNamePtrToFunctionTSI = |
1236 | 2.09k | S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc); |
1237 | 2.09k | ConvNameLoc.NamedType.TInfo = ConvNamePtrToFunctionTSI; |
1238 | 2.09k | |
1239 | 2.09k | // The conversion function is a conversion to a pointer-to-function. |
1240 | 2.09k | TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc); |
1241 | 2.09k | FunctionProtoTypeLoc ConvTL = |
1242 | 2.09k | ConvTSI->getTypeLoc().getAs<FunctionProtoTypeLoc>(); |
1243 | 2.09k | // Get the result of the conversion function which is a pointer-to-function. |
1244 | 2.09k | PointerTypeLoc PtrToFunctionTL = |
1245 | 2.09k | ConvTL.getReturnLoc().getAs<PointerTypeLoc>(); |
1246 | 2.09k | // Do the same for the TypeSourceInfo that is used to name the conversion |
1247 | 2.09k | // operator. |
1248 | 2.09k | PointerTypeLoc ConvNamePtrToFunctionTL = |
1249 | 2.09k | ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>(); |
1250 | 2.09k | |
1251 | 2.09k | // Get the underlying function types that the conversion function will |
1252 | 2.09k | // be converting to (should match the type of the call operator). |
1253 | 2.09k | FunctionProtoTypeLoc CallOpConvTL = |
1254 | 2.09k | PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>(); |
1255 | 2.09k | FunctionProtoTypeLoc CallOpConvNameTL = |
1256 | 2.09k | ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>(); |
1257 | 2.09k | |
1258 | 2.09k | // Wire up the FunctionProtoTypeLocs with the call operator's parameters. |
1259 | 2.09k | // These parameter's are essentially used to transform the name and |
1260 | 2.09k | // the type of the conversion operator. By using the same parameters |
1261 | 2.09k | // as the call operator's we don't have to fix any back references that |
1262 | 2.09k | // the trailing return type of the call operator's uses (such as |
1263 | 2.09k | // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.) |
1264 | 2.09k | // - we can simply use the return type of the call operator, and |
1265 | 2.09k | // everything should work. |
1266 | 2.09k | SmallVector<ParmVarDecl *, 4> InvokerParams; |
1267 | 4.06k | for (unsigned I = 0, N = CallOperator->getNumParams(); I != N4.06k ; ++I1.97k ) { |
1268 | 1.97k | ParmVarDecl *From = CallOperator->getParamDecl(I); |
1269 | 1.97k | |
1270 | 1.97k | InvokerParams.push_back(ParmVarDecl::Create(S.Context, |
1271 | 1.97k | // Temporarily add to the TU. This is set to the invoker below. |
1272 | 1.97k | S.Context.getTranslationUnitDecl(), |
1273 | 1.97k | From->getLocStart(), |
1274 | 1.97k | From->getLocation(), |
1275 | 1.97k | From->getIdentifier(), |
1276 | 1.97k | From->getType(), |
1277 | 1.97k | From->getTypeSourceInfo(), |
1278 | 1.97k | From->getStorageClass(), |
1279 | 1.97k | /*DefaultArg=*/nullptr)); |
1280 | 1.97k | CallOpConvTL.setParam(I, From); |
1281 | 1.97k | CallOpConvNameTL.setParam(I, From); |
1282 | 1.97k | } |
1283 | 2.09k | |
1284 | 2.09k | CXXConversionDecl *Conversion |
1285 | 2.09k | = CXXConversionDecl::Create(S.Context, Class, Loc, |
1286 | 2.09k | DeclarationNameInfo(ConversionName, |
1287 | 2.09k | Loc, ConvNameLoc), |
1288 | 2.09k | ConvTy, |
1289 | 2.09k | ConvTSI, |
1290 | 2.09k | /*isInline=*/true, /*isExplicit=*/false, |
1291 | 2.09k | /*isConstexpr=*/S.getLangOpts().CPlusPlus1z, |
1292 | 2.09k | CallOperator->getBody()->getLocEnd()); |
1293 | 2.09k | Conversion->setAccess(AS_public); |
1294 | 2.09k | Conversion->setImplicit(true); |
1295 | 2.09k | |
1296 | 2.09k | if (Class->isGenericLambda()2.09k ) { |
1297 | 1.04k | // Create a template version of the conversion operator, using the template |
1298 | 1.04k | // parameter list of the function call operator. |
1299 | 1.04k | FunctionTemplateDecl *TemplateCallOperator = |
1300 | 1.04k | CallOperator->getDescribedFunctionTemplate(); |
1301 | 1.04k | FunctionTemplateDecl *ConversionTemplate = |
1302 | 1.04k | FunctionTemplateDecl::Create(S.Context, Class, |
1303 | 1.04k | Loc, ConversionName, |
1304 | 1.04k | TemplateCallOperator->getTemplateParameters(), |
1305 | 1.04k | Conversion); |
1306 | 1.04k | ConversionTemplate->setAccess(AS_public); |
1307 | 1.04k | ConversionTemplate->setImplicit(true); |
1308 | 1.04k | Conversion->setDescribedFunctionTemplate(ConversionTemplate); |
1309 | 1.04k | Class->addDecl(ConversionTemplate); |
1310 | 1.04k | } else |
1311 | 1.04k | Class->addDecl(Conversion); |
1312 | 2.09k | // Add a non-static member function that will be the result of |
1313 | 2.09k | // the conversion with a certain unique ID. |
1314 | 2.09k | DeclarationName InvokerName = &S.Context.Idents.get( |
1315 | 2.09k | getLambdaStaticInvokerName()); |
1316 | 2.09k | // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo() |
1317 | 2.09k | // we should get a prebuilt TrivialTypeSourceInfo from Context |
1318 | 2.09k | // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc |
1319 | 2.09k | // then rewire the parameters accordingly, by hoisting up the InvokeParams |
1320 | 2.09k | // loop below and then use its Params to set Invoke->setParams(...) below. |
1321 | 2.09k | // This would avoid the 'const' qualifier of the calloperator from |
1322 | 2.09k | // contaminating the type of the invoker, which is currently adjusted |
1323 | 2.09k | // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the |
1324 | 2.09k | // trailing return type of the invoker would require a visitor to rebuild |
1325 | 2.09k | // the trailing return type and adjusting all back DeclRefExpr's to refer |
1326 | 2.09k | // to the new static invoker parameters - not the call operator's. |
1327 | 2.09k | CXXMethodDecl *Invoke |
1328 | 2.09k | = CXXMethodDecl::Create(S.Context, Class, Loc, |
1329 | 2.09k | DeclarationNameInfo(InvokerName, Loc), |
1330 | 2.09k | InvokerFunctionTy, |
1331 | 2.09k | CallOperator->getTypeSourceInfo(), |
1332 | 2.09k | SC_Static, /*IsInline=*/true, |
1333 | 2.09k | /*IsConstexpr=*/false, |
1334 | 2.09k | CallOperator->getBody()->getLocEnd()); |
1335 | 4.06k | for (unsigned I = 0, N = CallOperator->getNumParams(); I != N4.06k ; ++I1.97k ) |
1336 | 1.97k | InvokerParams[I]->setOwningFunction(Invoke); |
1337 | 2.09k | Invoke->setParams(InvokerParams); |
1338 | 2.09k | Invoke->setAccess(AS_private); |
1339 | 2.09k | Invoke->setImplicit(true); |
1340 | 2.09k | if (Class->isGenericLambda()2.09k ) { |
1341 | 1.04k | FunctionTemplateDecl *TemplateCallOperator = |
1342 | 1.04k | CallOperator->getDescribedFunctionTemplate(); |
1343 | 1.04k | FunctionTemplateDecl *StaticInvokerTemplate = FunctionTemplateDecl::Create( |
1344 | 1.04k | S.Context, Class, Loc, InvokerName, |
1345 | 1.04k | TemplateCallOperator->getTemplateParameters(), |
1346 | 1.04k | Invoke); |
1347 | 1.04k | StaticInvokerTemplate->setAccess(AS_private); |
1348 | 1.04k | StaticInvokerTemplate->setImplicit(true); |
1349 | 1.04k | Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate); |
1350 | 1.04k | Class->addDecl(StaticInvokerTemplate); |
1351 | 1.04k | } else |
1352 | 1.04k | Class->addDecl(Invoke); |
1353 | 2.09k | } |
1354 | | |
1355 | | /// \brief Add a lambda's conversion to block pointer. |
1356 | | static void addBlockPointerConversion(Sema &S, |
1357 | | SourceRange IntroducerRange, |
1358 | | CXXRecordDecl *Class, |
1359 | 114 | CXXMethodDecl *CallOperator) { |
1360 | 114 | const FunctionProtoType *Proto = |
1361 | 114 | CallOperator->getType()->getAs<FunctionProtoType>(); |
1362 | 114 | |
1363 | 114 | // The function type inside the block pointer type is the same as the call |
1364 | 114 | // operator with some tweaks. The calling convention is the default free |
1365 | 114 | // function convention, and the type qualifications are lost. |
1366 | 114 | FunctionProtoType::ExtProtoInfo BlockEPI = Proto->getExtProtoInfo(); |
1367 | 114 | BlockEPI.ExtInfo = |
1368 | 114 | BlockEPI.ExtInfo.withCallingConv(S.Context.getDefaultCallingConvention( |
1369 | 114 | Proto->isVariadic(), /*IsCXXMethod=*/false)); |
1370 | 114 | BlockEPI.TypeQuals = 0; |
1371 | 114 | QualType FunctionTy = S.Context.getFunctionType( |
1372 | 114 | Proto->getReturnType(), Proto->getParamTypes(), BlockEPI); |
1373 | 114 | QualType BlockPtrTy = S.Context.getBlockPointerType(FunctionTy); |
1374 | 114 | |
1375 | 114 | FunctionProtoType::ExtProtoInfo ConversionEPI( |
1376 | 114 | S.Context.getDefaultCallingConvention( |
1377 | 114 | /*IsVariadic=*/false, /*IsCXXMethod=*/true)); |
1378 | 114 | ConversionEPI.TypeQuals = Qualifiers::Const; |
1379 | 114 | QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, None, ConversionEPI); |
1380 | 114 | |
1381 | 114 | SourceLocation Loc = IntroducerRange.getBegin(); |
1382 | 114 | DeclarationName Name |
1383 | 114 | = S.Context.DeclarationNames.getCXXConversionFunctionName( |
1384 | 114 | S.Context.getCanonicalType(BlockPtrTy)); |
1385 | 114 | DeclarationNameLoc NameLoc; |
1386 | 114 | NameLoc.NamedType.TInfo = S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc); |
1387 | 114 | CXXConversionDecl *Conversion |
1388 | 114 | = CXXConversionDecl::Create(S.Context, Class, Loc, |
1389 | 114 | DeclarationNameInfo(Name, Loc, NameLoc), |
1390 | 114 | ConvTy, |
1391 | 114 | S.Context.getTrivialTypeSourceInfo(ConvTy, Loc), |
1392 | 114 | /*isInline=*/true, /*isExplicit=*/false, |
1393 | 114 | /*isConstexpr=*/false, |
1394 | 114 | CallOperator->getBody()->getLocEnd()); |
1395 | 114 | Conversion->setAccess(AS_public); |
1396 | 114 | Conversion->setImplicit(true); |
1397 | 114 | Class->addDecl(Conversion); |
1398 | 114 | } |
1399 | | |
1400 | | static ExprResult performLambdaVarCaptureInitialization( |
1401 | 1.28k | Sema &S, const LambdaScopeInfo::Capture &Capture, FieldDecl *Field) { |
1402 | 1.28k | assert(Capture.isVariableCapture() && "not a variable capture"); |
1403 | 1.28k | |
1404 | 1.28k | auto *Var = Capture.getVariable(); |
1405 | 1.28k | SourceLocation Loc = Capture.getLocation(); |
1406 | 1.28k | |
1407 | 1.28k | // C++11 [expr.prim.lambda]p21: |
1408 | 1.28k | // When the lambda-expression is evaluated, the entities that |
1409 | 1.28k | // are captured by copy are used to direct-initialize each |
1410 | 1.28k | // corresponding non-static data member of the resulting closure |
1411 | 1.28k | // object. (For array members, the array elements are |
1412 | 1.28k | // direct-initialized in increasing subscript order.) These |
1413 | 1.28k | // initializations are performed in the (unspecified) order in |
1414 | 1.28k | // which the non-static data members are declared. |
1415 | 1.28k | |
1416 | 1.28k | // C++ [expr.prim.lambda]p12: |
1417 | 1.28k | // An entity captured by a lambda-expression is odr-used (3.2) in |
1418 | 1.28k | // the scope containing the lambda-expression. |
1419 | 1.28k | ExprResult RefResult = S.BuildDeclarationNameExpr( |
1420 | 1.28k | CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var); |
1421 | 1.28k | if (RefResult.isInvalid()) |
1422 | 0 | return ExprError(); |
1423 | 1.28k | Expr *Ref = RefResult.get(); |
1424 | 1.28k | |
1425 | 1.28k | auto Entity = InitializedEntity::InitializeLambdaCapture( |
1426 | 1.28k | Var->getIdentifier(), Field->getType(), Loc); |
1427 | 1.28k | InitializationKind InitKind = InitializationKind::CreateDirect(Loc, Loc, Loc); |
1428 | 1.28k | InitializationSequence Init(S, Entity, InitKind, Ref); |
1429 | 1.28k | return Init.Perform(S, Entity, InitKind, Ref); |
1430 | 1.28k | } |
1431 | | |
1432 | | ExprResult Sema::ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, |
1433 | 2.78k | Scope *CurScope) { |
1434 | 2.78k | LambdaScopeInfo LSI = *cast<LambdaScopeInfo>(FunctionScopes.back()); |
1435 | 2.78k | ActOnFinishFunctionBody(LSI.CallOperator, Body); |
1436 | 2.78k | return BuildLambdaExpr(StartLoc, Body->getLocEnd(), &LSI); |
1437 | 2.78k | } |
1438 | | |
1439 | | static LambdaCaptureDefault |
1440 | 3.93k | mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS) { |
1441 | 3.93k | switch (ICS) { |
1442 | 2.91k | case CapturingScopeInfo::ImpCap_None: |
1443 | 2.91k | return LCD_None; |
1444 | 440 | case CapturingScopeInfo::ImpCap_LambdaByval: |
1445 | 440 | return LCD_ByCopy; |
1446 | 588 | case CapturingScopeInfo::ImpCap_CapturedRegion: |
1447 | 588 | case CapturingScopeInfo::ImpCap_LambdaByref: |
1448 | 588 | return LCD_ByRef; |
1449 | 0 | case CapturingScopeInfo::ImpCap_Block: |
1450 | 0 | llvm_unreachable("block capture in lambda"); |
1451 | 0 | } |
1452 | 0 | llvm_unreachable0 ("Unknown implicit capture style"); |
1453 | 0 | } |
1454 | | |
1455 | 375 | bool Sema::CaptureHasSideEffects(const LambdaScopeInfo::Capture &From) { |
1456 | 375 | if (!From.isVLATypeCapture()375 ) { |
1457 | 370 | Expr *Init = From.getInitExpr(); |
1458 | 370 | if (Init && 370 Init->HasSideEffects(Context)177 ) |
1459 | 37 | return true; |
1460 | 338 | } |
1461 | 338 | |
1462 | 338 | if (338 !From.isCopyCapture()338 ) |
1463 | 88 | return false; |
1464 | 250 | |
1465 | 250 | const QualType T = From.isThisCapture() |
1466 | 11 | ? getCurrentThisType()->getPointeeType() |
1467 | 239 | : From.getCaptureType(); |
1468 | 250 | |
1469 | 250 | if (T.isVolatileQualified()) |
1470 | 2 | return true; |
1471 | 248 | |
1472 | 248 | const Type *BaseT = T->getBaseElementTypeUnsafe(); |
1473 | 248 | if (const CXXRecordDecl *RD = BaseT->getAsCXXRecordDecl()) |
1474 | 47 | return !RD->isCompleteDefinition() || 47 !RD->hasTrivialCopyConstructor()47 || |
1475 | 36 | !RD->hasTrivialDestructor(); |
1476 | 201 | |
1477 | 201 | return false; |
1478 | 201 | } |
1479 | | |
1480 | 375 | void Sema::DiagnoseUnusedLambdaCapture(const LambdaScopeInfo::Capture &From) { |
1481 | 375 | if (CaptureHasSideEffects(From)) |
1482 | 53 | return; |
1483 | 322 | |
1484 | 322 | auto diag = Diag(From.getLocation(), diag::warn_unused_lambda_capture); |
1485 | 322 | if (From.isThisCapture()) |
1486 | 60 | diag << "'this'"; |
1487 | 322 | else |
1488 | 262 | diag << From.getVariable(); |
1489 | 375 | diag << From.isNonODRUsed(); |
1490 | 375 | } |
1491 | | |
1492 | | ExprResult Sema::BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, |
1493 | 3.93k | LambdaScopeInfo *LSI) { |
1494 | 3.93k | // Collect information from the lambda scope. |
1495 | 3.93k | SmallVector<LambdaCapture, 4> Captures; |
1496 | 3.93k | SmallVector<Expr *, 4> CaptureInits; |
1497 | 3.93k | SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc; |
1498 | 3.93k | LambdaCaptureDefault CaptureDefault = |
1499 | 3.93k | mapImplicitCaptureStyle(LSI->ImpCaptureStyle); |
1500 | 3.93k | CXXRecordDecl *Class; |
1501 | 3.93k | CXXMethodDecl *CallOperator; |
1502 | 3.93k | SourceRange IntroducerRange; |
1503 | 3.93k | bool ExplicitParams; |
1504 | 3.93k | bool ExplicitResultType; |
1505 | 3.93k | CleanupInfo LambdaCleanup; |
1506 | 3.93k | bool ContainsUnexpandedParameterPack; |
1507 | 3.93k | bool IsGenericLambda; |
1508 | 3.93k | { |
1509 | 3.93k | CallOperator = LSI->CallOperator; |
1510 | 3.93k | Class = LSI->Lambda; |
1511 | 3.93k | IntroducerRange = LSI->IntroducerRange; |
1512 | 3.93k | ExplicitParams = LSI->ExplicitParams; |
1513 | 3.93k | ExplicitResultType = !LSI->HasImplicitReturnType; |
1514 | 3.93k | LambdaCleanup = LSI->Cleanup; |
1515 | 3.93k | ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack; |
1516 | 3.93k | IsGenericLambda = Class->isGenericLambda(); |
1517 | 3.93k | |
1518 | 3.93k | CallOperator->setLexicalDeclContext(Class); |
1519 | 3.93k | Decl *TemplateOrNonTemplateCallOperatorDecl = |
1520 | 3.93k | CallOperator->getDescribedFunctionTemplate() |
1521 | 1.38k | ? CallOperator->getDescribedFunctionTemplate() |
1522 | 2.55k | : cast<Decl>(CallOperator); |
1523 | 3.93k | |
1524 | 3.93k | TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class); |
1525 | 3.93k | Class->addDecl(TemplateOrNonTemplateCallOperatorDecl); |
1526 | 3.93k | |
1527 | 3.93k | PopExpressionEvaluationContext(); |
1528 | 3.93k | |
1529 | 3.93k | // Translate captures. |
1530 | 3.93k | auto CurField = Class->field_begin(); |
1531 | 5.95k | for (unsigned I = 0, N = LSI->Captures.size(); I != N5.95k ; ++I, ++CurField2.01k ) { |
1532 | 2.02k | const LambdaScopeInfo::Capture &From = LSI->Captures[I]; |
1533 | 2.02k | assert(!From.isBlockCapture() && "Cannot capture __block variables"); |
1534 | 2.02k | bool IsImplicit = I >= LSI->NumExplicitCaptures; |
1535 | 2.02k | |
1536 | 2.02k | // Warn about unused explicit captures. |
1537 | 2.02k | if (!CurContext->isDependentContext() && 2.02k !IsImplicit1.77k && !From.isODRUsed()830 ) { |
1538 | 377 | // Initialized captures that are non-ODR used may not be eliminated. |
1539 | 377 | bool NonODRUsedInitCapture = |
1540 | 377 | IsGenericLambda && From.isNonODRUsed()17 && From.getInitExpr()3 ; |
1541 | 377 | if (!NonODRUsedInitCapture) |
1542 | 375 | DiagnoseUnusedLambdaCapture(From); |
1543 | 377 | } |
1544 | 2.02k | |
1545 | 2.02k | // Handle 'this' capture. |
1546 | 2.02k | if (From.isThisCapture()2.02k ) { |
1547 | 483 | Captures.push_back( |
1548 | 483 | LambdaCapture(From.getLocation(), IsImplicit, |
1549 | 483 | From.isCopyCapture() ? LCK_StarThis114 : LCK_This369 )); |
1550 | 483 | CaptureInits.push_back(From.getInitExpr()); |
1551 | 483 | continue; |
1552 | 483 | } |
1553 | 1.54k | if (1.54k From.isVLATypeCapture()1.54k ) { |
1554 | 33 | Captures.push_back( |
1555 | 33 | LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType)); |
1556 | 33 | CaptureInits.push_back(nullptr); |
1557 | 33 | continue; |
1558 | 33 | } |
1559 | 1.50k | |
1560 | 1.50k | VarDecl *Var = From.getVariable(); |
1561 | 1.50k | LambdaCaptureKind Kind = From.isCopyCapture() ? LCK_ByCopy702 : LCK_ByRef805 ; |
1562 | 1.50k | Captures.push_back(LambdaCapture(From.getLocation(), IsImplicit, Kind, |
1563 | 1.50k | Var, From.getEllipsisLoc())); |
1564 | 1.50k | Expr *Init = From.getInitExpr(); |
1565 | 1.50k | if (!Init1.50k ) { |
1566 | 1.28k | auto InitResult = |
1567 | 1.28k | performLambdaVarCaptureInitialization(*this, From, *CurField); |
1568 | 1.28k | if (InitResult.isInvalid()) |
1569 | 7 | return ExprError(); |
1570 | 1.28k | Init = InitResult.get(); |
1571 | 1.28k | } |
1572 | 1.50k | CaptureInits.push_back(Init); |
1573 | 1.50k | } |
1574 | 3.93k | |
1575 | 3.93k | // C++11 [expr.prim.lambda]p6: |
1576 | 3.93k | // The closure type for a lambda-expression with no lambda-capture |
1577 | 3.93k | // has a public non-virtual non-explicit const conversion function |
1578 | 3.93k | // to pointer to function having the same parameter and return |
1579 | 3.93k | // types as the closure type's function call operator. |
1580 | 3.93k | if (3.93k Captures.empty() && 3.93k CaptureDefault == LCD_None2.49k ) |
1581 | 2.09k | addFunctionPointerConversion(*this, IntroducerRange, Class, |
1582 | 2.09k | CallOperator); |
1583 | 3.93k | |
1584 | 3.93k | // Objective-C++: |
1585 | 3.93k | // The closure type for a lambda-expression has a public non-virtual |
1586 | 3.93k | // non-explicit const conversion function to a block pointer having the |
1587 | 3.93k | // same parameter and return types as the closure type's function call |
1588 | 3.93k | // operator. |
1589 | 3.93k | // FIXME: Fix generic lambda to block conversions. |
1590 | 3.93k | if (getLangOpts().Blocks && 3.93k getLangOpts().ObjC12.37k && !IsGenericLambda120 ) |
1591 | 114 | addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator); |
1592 | 3.93k | |
1593 | 3.93k | // Finalize the lambda class. |
1594 | 3.93k | SmallVector<Decl*, 4> Fields(Class->fields()); |
1595 | 3.93k | ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(), |
1596 | 3.93k | SourceLocation(), nullptr); |
1597 | 3.93k | CheckCompletedCXXClass(Class); |
1598 | 3.93k | } |
1599 | 3.93k | |
1600 | 3.93k | Cleanup.mergeFrom(LambdaCleanup); |
1601 | 3.93k | |
1602 | 3.93k | LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange, |
1603 | 3.93k | CaptureDefault, CaptureDefaultLoc, |
1604 | 3.93k | Captures, |
1605 | 3.93k | ExplicitParams, ExplicitResultType, |
1606 | 3.93k | CaptureInits, EndLoc, |
1607 | 3.93k | ContainsUnexpandedParameterPack); |
1608 | 3.93k | // If the lambda expression's call operator is not explicitly marked constexpr |
1609 | 3.93k | // and we are not in a dependent context, analyze the call operator to infer |
1610 | 3.93k | // its constexpr-ness, suppressing diagnostics while doing so. |
1611 | 3.93k | if (getLangOpts().CPlusPlus1z && 3.93k !CallOperator->isInvalidDecl()642 && |
1612 | 638 | !CallOperator->isConstexpr() && |
1613 | 633 | !isa<CoroutineBodyStmt>(CallOperator->getBody()) && |
1614 | 3.93k | !Class->getDeclContext()->isDependentContext()631 ) { |
1615 | 475 | TentativeAnalysisScope DiagnosticScopeGuard(*this); |
1616 | 475 | CallOperator->setConstexpr( |
1617 | 475 | CheckConstexprFunctionDecl(CallOperator) && |
1618 | 473 | CheckConstexprFunctionBody(CallOperator, CallOperator->getBody())); |
1619 | 475 | } |
1620 | 3.93k | |
1621 | 3.93k | // Emit delayed shadowing warnings now that the full capture list is known. |
1622 | 3.93k | DiagnoseShadowingLambdaDecls(LSI); |
1623 | 3.93k | |
1624 | 3.93k | if (!CurContext->isDependentContext()3.93k ) { |
1625 | 2.90k | switch (ExprEvalContexts.back().Context) { |
1626 | 2.90k | // C++11 [expr.prim.lambda]p2: |
1627 | 2.90k | // A lambda-expression shall not appear in an unevaluated operand |
1628 | 2.90k | // (Clause 5). |
1629 | 56 | case ExpressionEvaluationContext::Unevaluated: |
1630 | 56 | case ExpressionEvaluationContext::UnevaluatedList: |
1631 | 56 | case ExpressionEvaluationContext::UnevaluatedAbstract: |
1632 | 56 | // C++1y [expr.const]p2: |
1633 | 56 | // A conditional-expression e is a core constant expression unless the |
1634 | 56 | // evaluation of e, following the rules of the abstract machine, would |
1635 | 56 | // evaluate [...] a lambda-expression. |
1636 | 56 | // |
1637 | 56 | // This is technically incorrect, there are some constant evaluated contexts |
1638 | 56 | // where this should be allowed. We should probably fix this when DR1607 is |
1639 | 56 | // ratified, it lays out the exact set of conditions where we shouldn't |
1640 | 56 | // allow a lambda-expression. |
1641 | 56 | case ExpressionEvaluationContext::ConstantEvaluated: |
1642 | 56 | // We don't actually diagnose this case immediately, because we |
1643 | 56 | // could be within a context where we might find out later that |
1644 | 56 | // the expression is potentially evaluated (e.g., for typeid). |
1645 | 56 | ExprEvalContexts.back().Lambdas.push_back(Lambda); |
1646 | 56 | break; |
1647 | 56 | |
1648 | 2.85k | case ExpressionEvaluationContext::DiscardedStatement: |
1649 | 2.85k | case ExpressionEvaluationContext::PotentiallyEvaluated: |
1650 | 2.85k | case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed: |
1651 | 2.85k | break; |
1652 | 3.93k | } |
1653 | 3.93k | } |
1654 | 3.93k | |
1655 | 3.93k | return MaybeBindToTemporary(Lambda); |
1656 | 3.93k | } |
1657 | | |
1658 | | ExprResult Sema::BuildBlockForLambdaConversion(SourceLocation CurrentLocation, |
1659 | | SourceLocation ConvLocation, |
1660 | | CXXConversionDecl *Conv, |
1661 | 25 | Expr *Src) { |
1662 | 25 | // Make sure that the lambda call operator is marked used. |
1663 | 25 | CXXRecordDecl *Lambda = Conv->getParent(); |
1664 | 25 | CXXMethodDecl *CallOperator |
1665 | 25 | = cast<CXXMethodDecl>( |
1666 | 25 | Lambda->lookup( |
1667 | 25 | Context.DeclarationNames.getCXXOperatorName(OO_Call)).front()); |
1668 | 25 | CallOperator->setReferenced(); |
1669 | 25 | CallOperator->markUsed(Context); |
1670 | 25 | |
1671 | 25 | ExprResult Init = PerformCopyInitialization( |
1672 | 25 | InitializedEntity::InitializeLambdaToBlock(ConvLocation, Src->getType(), |
1673 | 25 | /*NRVO=*/false), |
1674 | 25 | CurrentLocation, Src); |
1675 | 25 | if (!Init.isInvalid()) |
1676 | 25 | Init = ActOnFinishFullExpr(Init.get()); |
1677 | 25 | |
1678 | 25 | if (Init.isInvalid()) |
1679 | 0 | return ExprError(); |
1680 | 25 | |
1681 | 25 | // Create the new block to be returned. |
1682 | 25 | BlockDecl *Block = BlockDecl::Create(Context, CurContext, ConvLocation); |
1683 | 25 | |
1684 | 25 | // Set the type information. |
1685 | 25 | Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo()); |
1686 | 25 | Block->setIsVariadic(CallOperator->isVariadic()); |
1687 | 25 | Block->setBlockMissingReturnType(false); |
1688 | 25 | |
1689 | 25 | // Add parameters. |
1690 | 25 | SmallVector<ParmVarDecl *, 4> BlockParams; |
1691 | 35 | for (unsigned I = 0, N = CallOperator->getNumParams(); I != N35 ; ++I10 ) { |
1692 | 10 | ParmVarDecl *From = CallOperator->getParamDecl(I); |
1693 | 10 | BlockParams.push_back(ParmVarDecl::Create(Context, Block, |
1694 | 10 | From->getLocStart(), |
1695 | 10 | From->getLocation(), |
1696 | 10 | From->getIdentifier(), |
1697 | 10 | From->getType(), |
1698 | 10 | From->getTypeSourceInfo(), |
1699 | 10 | From->getStorageClass(), |
1700 | 10 | /*DefaultArg=*/nullptr)); |
1701 | 10 | } |
1702 | 25 | Block->setParams(BlockParams); |
1703 | 25 | |
1704 | 25 | Block->setIsConversionFromLambda(true); |
1705 | 25 | |
1706 | 25 | // Add capture. The capture uses a fake variable, which doesn't correspond |
1707 | 25 | // to any actual memory location. However, the initializer copy-initializes |
1708 | 25 | // the lambda object. |
1709 | 25 | TypeSourceInfo *CapVarTSI = |
1710 | 25 | Context.getTrivialTypeSourceInfo(Src->getType()); |
1711 | 25 | VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation, |
1712 | 25 | ConvLocation, nullptr, |
1713 | 25 | Src->getType(), CapVarTSI, |
1714 | 25 | SC_None); |
1715 | 25 | BlockDecl::Capture Capture(/*Variable=*/CapVar, /*ByRef=*/false, |
1716 | 25 | /*Nested=*/false, /*Copy=*/Init.get()); |
1717 | 25 | Block->setCaptures(Context, Capture, /*CapturesCXXThis=*/false); |
1718 | 25 | |
1719 | 25 | // Add a fake function body to the block. IR generation is responsible |
1720 | 25 | // for filling in the actual body, which cannot be expressed as an AST. |
1721 | 25 | Block->setBody(new (Context) CompoundStmt(ConvLocation)); |
1722 | 25 | |
1723 | 25 | // Create the block literal expression. |
1724 | 25 | Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType()); |
1725 | 25 | ExprCleanupObjects.push_back(Block); |
1726 | 25 | Cleanup.setExprNeedsCleanups(true); |
1727 | 25 | |
1728 | 25 | return BuildBlock; |
1729 | 25 | } |