clang 24.0.0git
SemaLambda.cpp
Go to the documentation of this file.
1//===--- SemaLambda.cpp - Semantic Analysis for C++11 Lambdas -------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for C++ lambda expressions.
10//
11//===----------------------------------------------------------------------===//
13#include "TypeLocBuilder.h"
14#include "clang/AST/ASTLambda.h"
16#include "clang/AST/ExprCXX.h"
19#include "clang/Sema/DeclSpec.h"
21#include "clang/Sema/Lookup.h"
22#include "clang/Sema/Scope.h"
24#include "clang/Sema/SemaARM.h"
25#include "clang/Sema/SemaCUDA.h"
28#include "clang/Sema/SemaSYCL.h"
29#include "clang/Sema/Template.h"
30#include "llvm/ADT/STLExtras.h"
31#include <optional>
32using namespace clang;
33using namespace sema;
34
35/// Examines the FunctionScopeInfo stack to determine the nearest
36/// enclosing lambda (to the current lambda) that is 'capture-ready' for
37/// the variable referenced in the current lambda (i.e. \p VarToCapture).
38/// If successful, returns the index into Sema's FunctionScopeInfo stack
39/// of the capture-ready lambda's LambdaScopeInfo.
40///
41/// Climbs down the stack of lambdas (deepest nested lambda - i.e. current
42/// lambda - is on top) to determine the index of the nearest enclosing/outer
43/// lambda that is ready to capture the \p VarToCapture being referenced in
44/// the current lambda.
45/// As we climb down the stack, we want the index of the first such lambda -
46/// that is the lambda with the highest index that is 'capture-ready'.
47///
48/// A lambda 'L' is capture-ready for 'V' (var or this) if:
49/// - its enclosing context is non-dependent
50/// - and if the chain of lambdas between L and the lambda in which
51/// V is potentially used (i.e. the lambda at the top of the scope info
52/// stack), can all capture or have already captured V.
53/// If \p VarToCapture is 'null' then we are trying to capture 'this'.
54///
55/// Note that a lambda that is deemed 'capture-ready' still needs to be checked
56/// for whether it is 'capture-capable' (see
57/// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly
58/// capture.
59///
60/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
61/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
62/// is at the top of the stack and has the highest index.
63/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
64///
65/// \returns An UnsignedOrNone Index that if evaluates to 'true'
66/// contains the index (into Sema's FunctionScopeInfo stack) of the innermost
67/// lambda which is capture-ready. If the return value evaluates to 'false'
68/// then no lambda is capture-ready for \p VarToCapture.
69
72 ValueDecl *VarToCapture) {
73 // Label failure to capture.
74 const UnsignedOrNone NoLambdaIsCaptureReady = std::nullopt;
75
76 // Ignore all inner captured regions.
77 unsigned CurScopeIndex = FunctionScopes.size() - 1;
78 while (CurScopeIndex > 0 && isa<clang::sema::CapturedRegionScopeInfo>(
79 FunctionScopes[CurScopeIndex]))
80 --CurScopeIndex;
81 assert(
82 isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) &&
83 "The function on the top of sema's function-info stack must be a lambda");
84
85 // If VarToCapture is null, we are attempting to capture 'this'.
86 const bool IsCapturingThis = !VarToCapture;
87 const bool IsCapturingVariable = !IsCapturingThis;
88
89 // Start with the current lambda at the top of the stack (highest index).
90 DeclContext *EnclosingDC =
91 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator;
92
93 do {
95 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]);
96 // IF we have climbed down to an intervening enclosing lambda that contains
97 // the variable declaration - it obviously can/must not capture the
98 // variable.
99 // Since its enclosing DC is dependent, all the lambdas between it and the
100 // innermost nested lambda are dependent (otherwise we wouldn't have
101 // arrived here) - so we don't yet have a lambda that can capture the
102 // variable.
103 if (IsCapturingVariable && VarToCapture->getDeclContext()
105 ->Equals(EnclosingDC))
106 return NoLambdaIsCaptureReady;
107
108 // For an enclosing lambda to be capture ready for an entity, all
109 // intervening lambda's have to be able to capture that entity. If even
110 // one of the intervening lambda's is not capable of capturing the entity
111 // then no enclosing lambda can ever capture that entity.
112 // For e.g.
113 // const int x = 10;
114 // [=](auto a) { #1
115 // [](auto b) { #2 <-- an intervening lambda that can never capture 'x'
116 // [=](auto c) { #3
117 // f(x, c); <-- can not lead to x's speculative capture by #1 or #2
118 // }; }; };
119 // If they do not have a default implicit capture, check to see
120 // if the entity has already been explicitly captured.
121 // If even a single dependent enclosing lambda lacks the capability
122 // to ever capture this variable, there is no further enclosing
123 // non-dependent lambda that can capture this variable.
125 if (IsCapturingVariable && !LSI->isCaptured(VarToCapture))
126 return NoLambdaIsCaptureReady;
127 if (IsCapturingThis && !LSI->isCXXThisCaptured())
128 return NoLambdaIsCaptureReady;
129 }
130 EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC)
132
133 assert(CurScopeIndex);
134 --CurScopeIndex;
135 } while (!EnclosingDC->isTranslationUnit() &&
136 EnclosingDC->isDependentContext() &&
137 isLambdaCallOperator(EnclosingDC));
138
139 assert(CurScopeIndex < (FunctionScopes.size() - 1));
140 // If the enclosingDC is not dependent, then the immediately nested lambda
141 // (one index above) is capture-ready.
142 if (!EnclosingDC->isDependentContext())
143 return CurScopeIndex + 1;
144 return NoLambdaIsCaptureReady;
145}
146
147/// Examines the FunctionScopeInfo stack to determine the nearest
148/// enclosing lambda (to the current lambda) that is 'capture-capable' for
149/// the variable referenced in the current lambda (i.e. \p VarToCapture).
150/// If successful, returns the index into Sema's FunctionScopeInfo stack
151/// of the capture-capable lambda's LambdaScopeInfo.
152///
153/// Given the current stack of lambdas being processed by Sema and
154/// the variable of interest, to identify the nearest enclosing lambda (to the
155/// current lambda at the top of the stack) that can truly capture
156/// a variable, it has to have the following two properties:
157/// a) 'capture-ready' - be the innermost lambda that is 'capture-ready':
158/// - climb down the stack (i.e. starting from the innermost and examining
159/// each outer lambda step by step) checking if each enclosing
160/// lambda can either implicitly or explicitly capture the variable.
161/// Record the first such lambda that is enclosed in a non-dependent
162/// context. If no such lambda currently exists return failure.
163/// b) 'capture-capable' - make sure the 'capture-ready' lambda can truly
164/// capture the variable by checking all its enclosing lambdas:
165/// - check if all outer lambdas enclosing the 'capture-ready' lambda
166/// identified above in 'a' can also capture the variable (this is done
167/// via tryCaptureVariable for variables and CheckCXXThisCapture for
168/// 'this' by passing in the index of the Lambda identified in step 'a')
169///
170/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
171/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
172/// is at the top of the stack.
173///
174/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
175///
176///
177/// \returns An UnsignedOrNone Index that if evaluates to 'true'
178/// contains the index (into Sema's FunctionScopeInfo stack) of the innermost
179/// lambda which is capture-capable. If the return value evaluates to 'false'
180/// then no lambda is capture-capable for \p VarToCapture.
181
184 ValueDecl *VarToCapture, Sema &S) {
185
186 const UnsignedOrNone NoLambdaIsCaptureCapable = std::nullopt;
187
188 const UnsignedOrNone OptionalStackIndex =
190 VarToCapture);
191 if (!OptionalStackIndex)
192 return NoLambdaIsCaptureCapable;
193
194 const unsigned IndexOfCaptureReadyLambda = *OptionalStackIndex;
195 const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI =
196 cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]);
197
198 // If VarToCapture is null, we are attempting to capture 'this'
199 const bool IsCapturingThis = !VarToCapture;
200 const bool IsCapturingVariable = !IsCapturingThis;
201
202 if (IsCapturingVariable) {
203 // Check if the capture-ready lambda can truly capture the variable, by
204 // checking whether all enclosing lambdas of the capture-ready lambda allow
205 // the capture - i.e. make sure it is capture-capable.
206 QualType CaptureType, DeclRefType;
207 const bool CanCaptureVariable = !S.tryCaptureVariable(
208 VarToCapture,
209 /*ExprVarIsUsedInLoc*/ SourceLocation(), TryCaptureKind::Implicit,
210 /*EllipsisLoc*/ SourceLocation(),
211 /*BuildAndDiagnose*/ false, CaptureType, DeclRefType,
212 &IndexOfCaptureReadyLambda);
213 if (!CanCaptureVariable)
214 return NoLambdaIsCaptureCapable;
215 } else {
216 // Check if the capture-ready lambda can truly capture 'this' by checking
217 // whether all enclosing lambdas of the capture-ready lambda can capture
218 // 'this'.
219 const bool CanCaptureThis =
221 CaptureReadyLambdaLSI->PotentialThisCaptureLocation,
222 /*Explicit*/ false, /*BuildAndDiagnose*/ false,
223 &IndexOfCaptureReadyLambda);
224 if (!CanCaptureThis)
225 return NoLambdaIsCaptureCapable;
226 }
227 return IndexOfCaptureReadyLambda;
228}
229
230static inline TemplateParameterList *
232 if (!LSI->GLTemplateParameterList && !LSI->TemplateParams.empty()) {
234 SemaRef.Context,
235 /*Begin loc of the lambda expression*/ LSI->IntroducerRange.getBegin(),
236 /*L angle loc*/ LSI->ExplicitTemplateParamsRange.getBegin(),
237 LSI->TemplateParams,
238 /*R angle loc*/ LSI->ExplicitTemplateParamsRange.getEnd(),
239 LSI->RequiresClause.get());
240 }
241 return LSI->GLTemplateParameterList;
242}
243
246 unsigned LambdaDependencyKind,
247 LambdaCaptureDefault CaptureDefault) {
248 DeclContext *DC = CurContext->getEnclosingNonExpansionStatementContext();
249
250 bool IsGenericLambda =
252 // Start constructing the lambda class.
254 Context, DC, Info, IntroducerRange.getBegin(), LambdaDependencyKind,
255 IsGenericLambda, CaptureDefault);
256 DC->addDecl(Class);
257
258 return Class;
259}
260
261std::tuple<MangleNumberingContext *, Decl *>
263 // Compute the context for allocating mangling numbers in the current
264 // expression, if the ABI requires them.
265 Decl *ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
266
267 enum ContextKind {
268 Normal,
270 DataMember,
271 InlineVariable,
272 TemplatedVariable,
273 ExternallyVisibleVariableInModulePurview,
274 Concept,
275 } Kind = Normal;
276
277 bool IsInNonspecializedTemplate =
278 inTemplateInstantiation() || CurContext->isDependentContext();
279
280 // Checks if a VarDecl or FunctionDecl is from a module purview and externally
281 // visible. These Decls should be treated as "inline" for the purpose of
282 // mangling in the code below.
283 //
284 // See discussion in https://github.com/itanium-cxx-abi/cxx-abi/issues/186
285 //
286 // zygoloid:
287 // Yeah, I think the only cases left where lambdas don't need a
288 // mangling are when they have (effectively) internal linkage or
289 // appear in a non-inline function in a non-module translation unit.
290 static constexpr auto IsExternallyVisibleInModulePurview =
291 [](const NamedDecl *ND) -> bool {
292 return (ND->isInNamedModule() || ND->isFromGlobalModule()) &&
293 ND->isExternallyVisible();
294 };
295
296 // Default arguments of member function parameters that appear in a class
297 // definition, as well as the initializers of data members, receive special
298 // treatment. Identify them.
299 Kind = [&]() {
300 if (!ManglingContextDecl)
301 return Normal;
302
303 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
304 if (const DeclContext *LexicalDC
305 = Param->getDeclContext()->getLexicalParent())
306 if (LexicalDC->isRecord())
307 return DefaultArgument;
308 } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
309 if (Var->getMostRecentDecl()->isInline())
310 return InlineVariable;
311
312 if (IsExternallyVisibleInModulePurview(Var))
313 return ExternallyVisibleVariableInModulePurview;
314
315 if (Var->getDeclContext()->isRecord() && IsInNonspecializedTemplate)
316 return TemplatedVariable;
317
318 if (Var->getDescribedVarTemplate())
319 return TemplatedVariable;
320
321 if (auto *VTS = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
322 if (!VTS->isExplicitSpecialization())
323 return TemplatedVariable;
324 }
325 } else if (isa<FieldDecl>(ManglingContextDecl)) {
326 return DataMember;
328 ManglingContextDecl)) {
329 return Concept;
330 }
331
332 return Normal;
333 }();
334
335 // Determine whether the given context is or is enclosed in a function that
336 // requires Decl's inside to be mangled, so either:
337 // - an inline function
338 // - or a function in a module purview that is externally visible
339 static constexpr auto IsInFunctionThatRequiresMangling =
340 [](const DeclContext *DC) -> bool {
341 while (!DC->isFileContext()) {
342 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
343 if (FD->isInlined() || IsExternallyVisibleInModulePurview(FD))
344 return true;
345
346 DC = DC->getLexicalParent();
347 }
348
349 return false;
350 };
351
352 // Itanium ABI [5.1.8]:
353 // In the following contexts [...] the one-definition rule requires closure
354 // types in different translation units to "correspond":
355 switch (Kind) {
356 case Normal: {
357 // -- the bodies of inline or templated functions
358 // -- the bodies of externally visible functions in a module purview
359 // (note: this is not yet part of the Itanium ABI, see the linked Github
360 // discussion above)
361 if ((IsInNonspecializedTemplate &&
362 !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
363 IsInFunctionThatRequiresMangling(CurContext)) {
364 while (auto *CD = dyn_cast<CapturedDecl>(DC))
365 DC = CD->getParent();
366 return std::make_tuple(&Context.getManglingNumberContext(DC), nullptr);
367 }
368
369 return std::make_tuple(nullptr, nullptr);
370 }
371
372 case Concept:
373 // Concept definitions aren't code generated and thus aren't mangled,
374 // however the ManglingContextDecl is important for the purposes of
375 // re-forming the template argument list of the lambda for constraint
376 // evaluation.
377 case DataMember:
378 // -- default member initializers
379 case DefaultArgument:
380 // -- default arguments appearing in class definitions
381 case InlineVariable:
382 case ExternallyVisibleVariableInModulePurview:
383 case TemplatedVariable:
384 // -- the initializers of inline or templated variables
385 // -- the initializers of externally visible variables in a module purview
386 // (note: this is not yet part of the Itanium ABI, see the linked Github
387 // discussion above)
388 return std::make_tuple(
389 &Context.getManglingNumberContext(ASTContext::NeedExtraManglingDecl,
390 ManglingContextDecl),
391 ManglingContextDecl);
392 }
393
394 llvm_unreachable("unexpected context");
395}
396
397static QualType
399 TemplateParameterList *TemplateParams,
400 TypeSourceInfo *MethodTypeInfo) {
401 assert(MethodTypeInfo && "expected a non null type");
402
403 QualType MethodType = MethodTypeInfo->getType();
404 // If a lambda appears in a dependent context or is a generic lambda (has
405 // template parameters) and has an 'auto' return type, deduce it to a
406 // dependent type.
407 if (Class->isDependentContext() || TemplateParams) {
408 const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
410 if (Result->isUndeducedType()) {
412 MethodType = S.Context.getFunctionType(Result, FPT->getParamTypes(),
413 FPT->getExtProtoInfo());
414 }
415 }
416 return MethodType;
417}
418
419// [C++2b] [expr.prim.lambda.closure] p4
420// Given a lambda with a lambda-capture, the type of the explicit object
421// parameter, if any, of the lambda's function call operator (possibly
422// instantiated from a function call operator template) shall be either:
423// - the closure type,
424// - class type publicly and unambiguously derived from the closure type, or
425// - a reference to a possibly cv-qualified such type.
429 return false;
430 CXXRecordDecl *RD = Method->getParent();
431 if (Method->getType()->isDependentType())
432 return false;
433 if (RD->isCapturelessLambda())
434 return false;
435
436 ParmVarDecl *Param = Method->getParamDecl(0);
437 QualType ExplicitObjectParameterType = Param->getType()
438 .getNonReferenceType()
439 .getUnqualifiedType()
440 .getDesugaredType(getASTContext());
442 if (LambdaType == ExplicitObjectParameterType)
443 return false;
444
445 // Don't check the same instantiation twice.
446 //
447 // If this call operator is ill-formed, there is no point in issuing
448 // a diagnostic every time it is called because the problem is in the
449 // definition of the derived type, not at the call site.
450 //
451 // FIXME: Move this check to where we instantiate the method? This should
452 // be possible, but the naive approach of just marking the method as invalid
453 // leads to us emitting more diagnostics than we should have to for this case
454 // (1 error here *and* 1 error about there being no matching overload at the
455 // call site). It might be possible to avoid that by also checking if there
456 // is an empty cast path for the method stored in the context (signalling that
457 // we've already diagnosed it) and then just not building the call, but that
458 // doesn't really seem any simpler than diagnosing it at the call site...
459 auto [It, Inserted] = Context.LambdaCastPaths.try_emplace(Method);
460 if (!Inserted)
461 return It->second.empty();
462
463 CXXCastPath &Path = It->second;
464 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
465 /*DetectVirtual=*/false);
466 if (!IsDerivedFrom(RD->getLocation(), ExplicitObjectParameterType, LambdaType,
467 Paths)) {
468 Diag(Param->getLocation(), diag::err_invalid_explicit_object_type_in_lambda)
469 << ExplicitObjectParameterType;
470 return true;
471 }
472
473 if (Paths.isAmbiguous(LambdaType)) {
474 std::string PathsDisplay = getAmbiguousPathsDisplayString(Paths);
475 Diag(CallLoc, diag::err_explicit_object_lambda_ambiguous_base)
476 << LambdaType << PathsDisplay;
477 return true;
478 }
479
480 if (CheckBaseClassAccess(CallLoc, LambdaType, ExplicitObjectParameterType,
481 Paths.front(),
482 diag::err_explicit_object_lambda_inaccessible_base))
483 return true;
484
485 BuildBasePathArray(Paths, Path);
486 return false;
487}
488
491 std::optional<CXXRecordDecl::LambdaNumbering> NumberingOverride) {
492 ContextRAII ManglingContext(*this, Class->getDeclContext());
493
494 auto getMangleNumberingContext =
495 [this](CXXRecordDecl *Class,
496 Decl *ManglingContextDecl) -> MangleNumberingContext * {
497 // Get mangle numbering context if there's any extra decl context.
498 if (ManglingContextDecl)
499 return &Context.getManglingNumberContext(
500 ASTContext::NeedExtraManglingDecl, ManglingContextDecl);
501 // Otherwise, from that lambda's decl context.
502 auto DC = Class->getDeclContext();
503 while (auto *CD = dyn_cast<CapturedDecl>(DC))
504 DC = CD->getParent();
505 return &Context.getManglingNumberContext(DC);
506 };
507
509 Decl *ContextDecl;
510 std::tie(MCtx, ContextDecl) =
511 getCurrentMangleNumberContext(Class->getDeclContext());
512 // getManglingNumber(Method) below may trigger mangling of dependent types
513 // that reference init-captures. Publish the lambda context declaration early
514 // so such mangling can resolve the surrounding context without recursing
515 // through the lambda call operator. This avoids publishing provisional
516 // numbering state before final numbering is assigned below.
517 if (ContextDecl)
518 Class->setLambdaContextDecl(ContextDecl);
519
521 if (!MCtx && (getLangOpts().CUDA || getLangOpts().SYCLIsDevice ||
522 getLangOpts().SYCLIsHost)) {
523 // Force lambda numbering in CUDA/HIP as we need to name lambdas following
524 // ODR. Both device- and host-compilation need to have a consistent naming
525 // on kernel functions. As lambdas are potential part of these `__global__`
526 // function names, they needs numbering following ODR.
527 // Also force for SYCL, since we need this for the
528 // __builtin_sycl_unique_stable_name implementation, which depends on lambda
529 // mangling.
530 MCtx = getMangleNumberingContext(Class, ContextDecl);
531 assert(MCtx && "Retrieving mangle numbering context failed!");
532 Numbering.HasKnownInternalLinkage = true;
533 }
534
535 if (!MCtx) {
536 // This lambda doesn't need a mangle numbering.
537 return;
538 }
539
540 if (NumberingOverride) {
541 Numbering = *NumberingOverride;
542 } else {
543 Numbering.IndexInContext = MCtx->getNextLambdaIndex();
544 Numbering.ManglingNumber = MCtx->getManglingNumber(Method);
546 }
547
548 Class->setLambdaNumbering(Numbering);
549
550 // If there is no context declaration (e.g. this lambda is defined at the
551 // top-level in the global namespace), there is no need to register it for
552 // merging.
553 if (!ContextDecl) {
554 return;
555 }
556
557 // This lambda might redeclare a previous lambda if this is not the first
558 // definition of the context declaration. We might have a definition from
559 // another translation unit.
560 auto *&Slot = Context.getLambdaDeclarationSlotForMerging(
561 ContextDecl, Numbering.IndexInContext);
562 if (auto *Previous = Slot) {
563 Class->setPreviousDecl(Previous);
565 } else {
566 // Keep track of this lambda so it can be merged with another lambda that is
567 // parsed or loaded later.
568 Slot = Class;
569 }
570}
571
573 CXXMethodDecl *CallOperator,
574 bool ExplicitResultType) {
575 if (ExplicitResultType) {
576 LSI->HasImplicitReturnType = false;
577 LSI->ReturnType = CallOperator->getReturnType();
578 if (!LSI->ReturnType->isDependentType() && !LSI->ReturnType->isVoidType())
579 S.RequireCompleteType(CallOperator->getBeginLoc(), LSI->ReturnType,
580 diag::err_lambda_incomplete_result);
581 } else {
582 LSI->HasImplicitReturnType = true;
583 }
584}
585
587 SourceRange IntroducerRange,
588 LambdaCaptureDefault CaptureDefault,
589 SourceLocation CaptureDefaultLoc,
590 bool ExplicitParams, bool Mutable) {
591 LSI->CallOperator = CallOperator;
592 CXXRecordDecl *LambdaClass = CallOperator->getParent();
593 LSI->Lambda = LambdaClass;
594 if (CaptureDefault == LCD_ByCopy)
595 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
596 else if (CaptureDefault == LCD_ByRef)
597 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
598 LSI->CaptureDefaultLoc = CaptureDefaultLoc;
599 LSI->IntroducerRange = IntroducerRange;
600 LSI->ExplicitParams = ExplicitParams;
601 LSI->Mutable = Mutable;
602}
603
607
609 LambdaIntroducer &Intro, SourceLocation LAngleLoc,
610 ArrayRef<NamedDecl *> TParams, SourceLocation RAngleLoc,
611 ExprResult RequiresClause) {
613 assert(LSI && "Expected a lambda scope");
614 assert(LSI->NumExplicitTemplateParams == 0 &&
615 "Already acted on explicit template parameters");
616 assert(LSI->TemplateParams.empty() &&
617 "Explicit template parameters should come "
618 "before invented (auto) ones");
619 assert(!TParams.empty() &&
620 "No template parameters to act on");
621 LSI->TemplateParams.append(TParams.begin(), TParams.end());
622 LSI->NumExplicitTemplateParams = TParams.size();
623 LSI->ExplicitTemplateParamsRange = {LAngleLoc, RAngleLoc};
624 LSI->RequiresClause = RequiresClause;
625}
626
627/// If this expression is an enumerator-like expression of some type
628/// T, return the type T; otherwise, return null.
629///
630/// Pointer comparisons on the result here should always work because
631/// it's derived from either the parent of an EnumConstantDecl
632/// (i.e. the definition) or the declaration returned by
633/// EnumType::getDecl() (i.e. the definition).
635 // An expression is an enumerator-like expression of type T if,
636 // ignoring parens and parens-like expressions:
637 E = E->IgnoreParens();
638
639 // - it is an enumerator whose enum type is T or
640 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
641 if (EnumConstantDecl *D
642 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
643 return cast<EnumDecl>(D->getDeclContext());
644 }
645 return nullptr;
646 }
647
648 // - it is a comma expression whose RHS is an enumerator-like
649 // expression of type T or
650 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
651 if (BO->getOpcode() == BO_Comma)
652 return findEnumForBlockReturn(BO->getRHS());
653 return nullptr;
654 }
655
656 // - it is a statement-expression whose value expression is an
657 // enumerator-like expression of type T or
658 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
659 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
660 return findEnumForBlockReturn(last);
661 return nullptr;
662 }
663
664 // - it is a ternary conditional operator (not the GNU ?:
665 // extension) whose second and third operands are
666 // enumerator-like expressions of type T or
667 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
668 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
669 if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
670 return ED;
671 return nullptr;
672 }
673
674 // (implicitly:)
675 // - it is an implicit integral conversion applied to an
676 // enumerator-like expression of type T or
677 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
678 // We can sometimes see integral conversions in valid
679 // enumerator-like expressions.
680 if (ICE->getCastKind() == CK_IntegralCast)
681 return findEnumForBlockReturn(ICE->getSubExpr());
682
683 // Otherwise, just rely on the type.
684 }
685
686 // - it is an expression of that formal enum type.
687 if (auto *ED = E->getType()->getAsEnumDecl())
688 return ED;
689
690 // Otherwise, nope.
691 return nullptr;
692}
693
694/// Attempt to find a type T for which the returned expression of the
695/// given statement is an enumerator-like expression of that type.
697 if (Expr *retValue = ret->getRetValue())
698 return findEnumForBlockReturn(retValue);
699 return nullptr;
700}
701
702/// Attempt to find a common type T for which all of the returned
703/// expressions in a block are enumerator-like expressions of that
704/// type.
706 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
707
708 // Try to find one for the first return.
710 if (!ED) return nullptr;
711
712 // Check that the rest of the returns have the same enum.
713 for (++i; i != e; ++i) {
714 if (findEnumForBlockReturn(*i) != ED)
715 return nullptr;
716 }
717
718 // Never infer an anonymous enum type.
719 if (!ED->hasNameForLinkage()) return nullptr;
720
721 return ED;
722}
723
724/// Adjust the given return statements so that they formally return
725/// the given type. It should require, at most, an IntegralCast.
727 QualType returnType) {
729 i = returns.begin(), e = returns.end(); i != e; ++i) {
730 ReturnStmt *ret = *i;
731 Expr *retValue = ret->getRetValue();
732 if (S.Context.hasSameType(retValue->getType(), returnType))
733 continue;
734
735 // Right now we only support integral fixup casts.
736 assert(returnType->isIntegralOrUnscopedEnumerationType());
737 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
738
739 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
740
741 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
742 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast, E,
743 /*base path*/ nullptr, VK_PRValue,
745 if (cleanups) {
746 cleanups->setSubExpr(E);
747 } else {
748 ret->setRetValue(E);
749 }
750 }
751}
752
754 assert(CSI.HasImplicitReturnType);
755 // If it was ever a placeholder, it had to been deduced to DependentTy.
756 assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
757 assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) &&
758 "lambda expressions use auto deduction in C++14 onwards");
759
760 // C++ core issue 975:
761 // If a lambda-expression does not include a trailing-return-type,
762 // it is as if the trailing-return-type denotes the following type:
763 // - if there are no return statements in the compound-statement,
764 // or all return statements return either an expression of type
765 // void or no expression or braced-init-list, the type void;
766 // - otherwise, if all return statements return an expression
767 // and the types of the returned expressions after
768 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
769 // array-to-pointer conversion (4.2 [conv.array]), and
770 // function-to-pointer conversion (4.3 [conv.func]) are the
771 // same, that common type;
772 // - otherwise, the program is ill-formed.
773 //
774 // C++ core issue 1048 additionally removes top-level cv-qualifiers
775 // from the types of returned expressions to match the C++14 auto
776 // deduction rules.
777 //
778 // In addition, in blocks in non-C++ modes, if all of the return
779 // statements are enumerator-like expressions of some type T, where
780 // T has a name for linkage, then we infer the return type of the
781 // block to be that type.
782
783 // First case: no return statements, implicit void return type.
784 ASTContext &Ctx = getASTContext();
785 if (CSI.Returns.empty()) {
786 // It's possible there were simply no /valid/ return statements.
787 // In this case, the first one we found may have at least given us a type.
788 if (CSI.ReturnType.isNull())
789 CSI.ReturnType = Ctx.VoidTy;
790 return;
791 }
792
793 // Second case: at least one return statement has dependent type.
794 // Delay type checking until instantiation.
795 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
796 if (CSI.ReturnType->isDependentType())
797 return;
798
799 // Try to apply the enum-fuzz rule.
800 if (!getLangOpts().CPlusPlus) {
801 assert(isa<BlockScopeInfo>(CSI));
803 if (ED) {
804 CSI.ReturnType = Context.getCanonicalTagType(ED);
806 return;
807 }
808 }
809
810 // Third case: only one return statement. Don't bother doing extra work!
811 if (CSI.Returns.size() == 1)
812 return;
813
814 // General case: many return statements.
815 // Check that they all have compatible return types.
816
817 // We require the return types to strictly match here.
818 // Note that we've already done the required promotions as part of
819 // processing the return statement.
820 for (const ReturnStmt *RS : CSI.Returns) {
821 const Expr *RetE = RS->getRetValue();
822
823 QualType ReturnType =
824 (RetE ? RetE->getType() : Context.VoidTy).getUnqualifiedType();
825 if (Context.getCanonicalFunctionResultType(ReturnType) ==
826 Context.getCanonicalFunctionResultType(CSI.ReturnType)) {
827 // Use the return type with the strictest possible nullability annotation.
828 auto RetTyNullability = ReturnType->getNullability();
829 auto BlockNullability = CSI.ReturnType->getNullability();
830 if (BlockNullability &&
831 (!RetTyNullability ||
832 hasWeakerNullability(*RetTyNullability, *BlockNullability)))
833 CSI.ReturnType = ReturnType;
834 continue;
835 }
836
837 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
838 // TODO: It's possible that the *first* return is the divergent one.
839 Diag(RS->getBeginLoc(),
840 diag::err_typecheck_missing_return_type_incompatible)
841 << ReturnType << CSI.ReturnType << isa<LambdaScopeInfo>(CSI);
842 // Continue iterating so that we keep emitting diagnostics.
843 }
844}
845
847 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
848 UnsignedOrNone NumExpansions, IdentifierInfo *Id, bool IsDirectInit,
849 Expr *&Init) {
850 // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to
851 // deduce against.
852 QualType DeductType = Context.getAutoDeductType();
853 TypeLocBuilder TLB;
854 AutoTypeLoc TL = TLB.push<AutoTypeLoc>(DeductType);
855 TL.setNameLoc(Loc);
856 if (ByRef) {
857 DeductType = BuildReferenceType(DeductType, true, Loc, Id);
858 assert(!DeductType.isNull() && "can't build reference to auto");
859 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
860 }
861 if (EllipsisLoc.isValid()) {
862 if (Init->containsUnexpandedParameterPack()) {
863 DiagCompat(EllipsisLoc, diag_compat::init_capture_pack);
864 DeductType = Context.getPackExpansionType(DeductType, NumExpansions,
865 /*ExpectPackInType=*/false);
866 TLB.push<PackExpansionTypeLoc>(DeductType).setEllipsisLoc(EllipsisLoc);
867 } else {
868 // Just ignore the ellipsis for now and form a non-pack variable. We'll
869 // diagnose this later when we try to capture it.
870 }
871 }
872 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
873
874 // Deduce the type of the init capture.
876 /*VarDecl*/nullptr, DeclarationName(Id), DeductType, TSI,
877 SourceRange(Loc, Loc), IsDirectInit, Init);
878 if (DeducedType.isNull())
879 return QualType();
880
881 // Are we a non-list direct initialization?
882 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
883
884 // Perform initialization analysis and ensure any implicit conversions
885 // (such as lvalue-to-rvalue) are enforced.
886 InitializedEntity Entity =
887 InitializedEntity::InitializeLambdaCapture(Id, DeducedType, Loc);
888 InitializationKind Kind =
889 IsDirectInit
890 ? (CXXDirectInit ? InitializationKind::CreateDirect(
891 Loc, Init->getBeginLoc(), Init->getEndLoc())
893 : InitializationKind::CreateCopy(Loc, Init->getBeginLoc());
894
895 MultiExprArg Args = Init;
896 if (CXXDirectInit)
897 Args =
898 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
899 QualType DclT;
900 InitializationSequence InitSeq(*this, Entity, Kind, Args);
901 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
902
903 if (Result.isInvalid())
904 return QualType();
905
906 Init = Result.getAs<Expr>();
907 return DeducedType;
908}
909
911 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
912 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx) {
913 // FIXME: Retain the TypeSourceInfo from buildLambdaInitCaptureInitialization
914 // rather than reconstructing it here.
915 TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType, Loc);
916 if (auto PETL = TSI->getTypeLoc().getAs<PackExpansionTypeLoc>())
917 PETL.setEllipsisLoc(EllipsisLoc);
918
919 // Create a dummy variable representing the init-capture. This is not actually
920 // used as a variable, and only exists as a way to name and refer to the
921 // init-capture.
922 // FIXME: Pass in separate source locations for '&' and identifier.
923 VarDecl *NewVD = VarDecl::Create(Context, DeclCtx, Loc, Loc, Id,
924 InitCaptureType, TSI, SC_Auto);
925 NewVD->setInitCapture(true);
926 NewVD->setReferenced(true);
927 // FIXME: Pass in a VarDecl::InitializationStyle.
928 NewVD->setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle));
929 NewVD->markUsed(Context);
930 NewVD->setInit(Init);
931 if (NewVD->isParameterPack())
932 getCurLambda()->LocalPacks.push_back(NewVD);
933 return NewVD;
934}
935
936void Sema::addInitCapture(LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef) {
937 assert(Var->isInitCapture() && "init capture flag should be set");
938 LSI->addCapture(Var, /*isBlock=*/false, ByRef,
939 /*isNested=*/false, Var->getLocation(), SourceLocation(),
940 Var->getType(), /*Invalid=*/false);
941}
942
943// Unlike getCurLambda, getCurrentLambdaScopeUnsafe doesn't
944// check that the current lambda is in a consistent or fully constructed state.
946 assert(!S.FunctionScopes.empty());
948}
949
950static TypeSourceInfo *
952 // C++11 [expr.prim.lambda]p4:
953 // If a lambda-expression does not include a lambda-declarator, it is as
954 // if the lambda-declarator were ().
956 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
957 EPI.HasTrailingReturn = true;
958 EPI.TypeQuals.addConst();
960 if (AS != LangAS::Default)
962
963 // C++1y [expr.prim.lambda]:
964 // The lambda return type is 'auto', which is replaced by the
965 // trailing-return type if provided and/or deduced from 'return'
966 // statements
967 // We don't do this before C++1y, because we don't support deduced return
968 // types there.
969 QualType DefaultTypeForNoTrailingReturn = S.getLangOpts().CPlusPlus14
972 QualType MethodTy =
973 S.Context.getFunctionType(DefaultTypeForNoTrailingReturn, {}, EPI);
974 return S.Context.getTrivialTypeSourceInfo(MethodTy, Loc);
975}
976
978 Declarator &ParamInfo, Scope *CurScope,
979 SourceLocation Loc,
980 bool &ExplicitResultType) {
981
982 ExplicitResultType = false;
983
984 assert(
985 (ParamInfo.getDeclSpec().getStorageClassSpec() ==
988 "Unexpected storage specifier");
989 bool IsLambdaStatic =
991
992 TypeSourceInfo *MethodTyInfo;
993
994 if (ParamInfo.getNumTypeObjects() == 0) {
995 MethodTyInfo = getDummyLambdaType(S, Loc);
996 } else {
997 // Check explicit parameters
998 S.CheckExplicitObjectLambda(ParamInfo);
999
1001
1002 bool HasExplicitObjectParameter =
1004
1005 ExplicitResultType = FTI.hasTrailingReturnType();
1006 if (!FTI.hasMutableQualifier() && !IsLambdaStatic &&
1007 !HasExplicitObjectParameter)
1009
1010 if (ExplicitResultType && S.getLangOpts().HLSL) {
1011 QualType RetTy = FTI.getTrailingReturnType().get();
1012 if (!RetTy.isNull()) {
1013 // HLSL does not support specifying an address space on a lambda return
1014 // type.
1015 LangAS AddressSpace = RetTy.getAddressSpace();
1016 if (AddressSpace != LangAS::Default)
1018 diag::err_return_value_with_address_space);
1019 }
1020 }
1021
1022 MethodTyInfo = S.GetTypeForDeclarator(ParamInfo);
1023 assert(MethodTyInfo && "no type from lambda-declarator");
1024
1025 // Check for unexpanded parameter packs in the method type.
1026 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
1027 S.DiagnoseUnexpandedParameterPack(Intro.Range.getBegin(), MethodTyInfo,
1029 }
1030 return MethodTyInfo;
1031}
1032
1035
1036 // C++20 [expr.prim.lambda.closure]p3:
1037 // The closure type for a lambda-expression has a public inline function
1038 // call operator (for a non-generic lambda) or function call operator
1039 // template (for a generic lambda) whose parameters and return type are
1040 // described by the lambda-expression's parameter-declaration-clause
1041 // and trailing-return-type respectively.
1042 DeclarationName MethodName =
1043 Context.DeclarationNames.getCXXOperatorName(OO_Call);
1044 DeclarationNameLoc MethodNameLoc =
1048 DeclarationNameInfo(MethodName, IntroducerRange.getBegin(),
1049 MethodNameLoc),
1050 QualType(), /*Tinfo=*/nullptr, SC_None,
1051 getCurFPFeatures().isFPConstrained(),
1052 /*isInline=*/true, ConstexprSpecKind::Unspecified, SourceLocation(),
1053 /*TrailingRequiresClause=*/{});
1054 Method->setAccess(AS_public);
1055 return Method;
1056}
1057
1059 CXXMethodDecl *CallOperator, CXXRecordDecl *Class,
1060 TemplateParameterList *TemplateParams) {
1061 assert(TemplateParams && "no template parameters");
1063 Context, Class, CallOperator->getLocation(), CallOperator->getDeclName(),
1064 TemplateParams, CallOperator);
1065 TemplateMethod->setAccess(AS_public);
1066 CallOperator->setDescribedFunctionTemplate(TemplateMethod);
1067}
1068
1071 SourceLocation CallOperatorLoc,
1072 const AssociatedConstraint &TrailingRequiresClause,
1073 TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind,
1075 bool HasExplicitResultType) {
1076
1078
1079 if (TrailingRequiresClause)
1080 Method->setTrailingRequiresClause(TrailingRequiresClause);
1081
1082 TemplateParameterList *TemplateParams =
1084
1085 DeclContext *DC = Method->getLexicalDeclContext();
1086 // DeclContext::addDecl() assumes that the DeclContext we're adding to is the
1087 // lexical context of the Method. Do so.
1088 Method->setLexicalDeclContext(LSI->Lambda);
1089 if (TemplateParams) {
1090 FunctionTemplateDecl *TemplateMethod =
1091 Method->getDescribedFunctionTemplate();
1092 assert(TemplateMethod &&
1093 "AddTemplateParametersToLambdaCallOperator should have been called");
1094
1095 LSI->Lambda->addDecl(TemplateMethod);
1096 TemplateMethod->setLexicalDeclContext(DC);
1097 } else {
1098 LSI->Lambda->addDecl(Method);
1099 }
1100 LSI->Lambda->setLambdaIsGeneric(TemplateParams);
1101 LSI->Lambda->setLambdaTypeInfo(MethodTyInfo);
1102
1103 Method->setLexicalDeclContext(DC);
1104 Method->setLocation(LambdaLoc);
1105 Method->setInnerLocStart(CallOperatorLoc);
1106 Method->setTypeSourceInfo(MethodTyInfo);
1107 Method->setType(buildTypeForLambdaCallOperator(*this, LSI->Lambda,
1108 TemplateParams, MethodTyInfo));
1109 Method->setConstexprKind(ConstexprKind);
1110 Method->setStorageClass(SC);
1111 if (!Params.empty()) {
1112 CheckParmsForFunctionDef(Params, /*CheckParameterNames=*/false);
1113 Method->setParams(Params);
1114 for (auto P : Method->parameters()) {
1115 assert(P && "null in a parameter list");
1116 P->setOwningFunction(Method);
1117 }
1118 }
1119
1120 buildLambdaScopeReturnType(*this, LSI, Method, HasExplicitResultType);
1121
1122 // Not built by ActOnFunctionDeclarator, so tag it here.
1124}
1125
1127 Scope *CurrentScope) {
1128
1130 assert(LSI && "LambdaScopeInfo should be on stack!");
1131
1132 if (Intro.Default == LCD_ByCopy)
1133 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
1134 else if (Intro.Default == LCD_ByRef)
1135 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
1136 LSI->CaptureDefaultLoc = Intro.DefaultLoc;
1137 LSI->IntroducerRange = Intro.Range;
1138 LSI->AfterParameterList = false;
1139
1140 assert(LSI->NumExplicitTemplateParams == 0);
1141
1142 // Determine if we're within a context where we know that the lambda will
1143 // be dependent, because there are template parameters in scope.
1144 //
1145 // FIXME: A lambda in the noexcept specifier of an abbreviated function
1146 // template (e.g. `auto&&`) is not marked dependent when it captures
1147 // a dependent entity. See:
1148 // * clang/unittests/AST/LambdaDependencyTest.cpp
1149 // * https://github.com/llvm/llvm-project/issues/232874
1150 // * https://github.com/llvm/llvm-project/issues/233102
1151 // A temporary guard in PaddingChecker::shouldSkipDecl skips fields of
1152 // dependent type as a workaround; remove it together with this FIXME
1153 // once the bug is fixed.
1154 CXXRecordDecl::LambdaDependencyKind LambdaDependencyKind =
1156 if (CurScope->getTemplateParamParent() != nullptr) {
1157 LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
1158 } else if (Scope *ParentScope = CurScope->getParent()) {
1159 // Given a lambda defined inside a requires expression,
1160 //
1161 // struct S {
1162 // S(auto var) requires requires { [&] -> decltype(var) { }; }
1163 // {}
1164 // };
1165 //
1166 // The parameter var is not injected into the function Decl at the point of
1167 // parsing lambda. In such scenarios, perceiving it as dependent could
1168 // result in the constraint being evaluated, which matches what GCC does.
1169 Scope *LookupScope = ParentScope;
1170 while (LookupScope->getEntity() &&
1171 LookupScope->getEntity()->isRequiresExprBody())
1172 LookupScope = LookupScope->getParent();
1173
1174 if (LookupScope != ParentScope &&
1175 LookupScope->isFunctionDeclarationScope() &&
1176 llvm::any_of(LookupScope->decls(), [](Decl *D) {
1177 return isa<ParmVarDecl>(D) &&
1178 cast<ParmVarDecl>(D)->getType()->isTemplateTypeParmType();
1179 }))
1180 LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
1181 }
1182
1184 Intro.Range, /*Info=*/nullptr, LambdaDependencyKind, Intro.Default);
1185 LSI->Lambda = Class;
1186
1188 LSI->CallOperator = Method;
1189 // Temporarily set the lexical declaration context to the current
1190 // context, so that the Scope stack matches the lexical nesting.
1191 Method->setLexicalDeclContext(CurContext);
1192
1193 PushDeclContext(CurScope, Method);
1194
1195 bool ContainsUnexpandedParameterPack = false;
1196
1197 // Distinct capture names, for diagnostics.
1198 llvm::DenseMap<IdentifierInfo *, ValueDecl *> CaptureNames;
1199
1200 // Handle explicit captures.
1201 SourceLocation PrevCaptureLoc =
1202 Intro.Default == LCD_None ? Intro.Range.getBegin() : Intro.DefaultLoc;
1203 for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E;
1204 PrevCaptureLoc = C->Loc, ++C) {
1205 if (C->Kind == LCK_This || C->Kind == LCK_StarThis) {
1206 if (C->Kind == LCK_StarThis)
1207 DiagCompat(C->Loc, diag_compat::star_this_lambda_capture);
1208
1209 // C++11 [expr.prim.lambda]p8:
1210 // An identifier or this shall not appear more than once in a
1211 // lambda-capture.
1212 if (LSI->isCXXThisCaptured()) {
1213 Diag(C->Loc, diag::err_capture_more_than_once)
1214 << "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation())
1216 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1217 continue;
1218 }
1219
1220 // C++20 [expr.prim.lambda]p8:
1221 // If a lambda-capture includes a capture-default that is =,
1222 // each simple-capture of that lambda-capture shall be of the form
1223 // "&identifier", "this", or "* this". [ Note: The form [&,this] is
1224 // redundant but accepted for compatibility with ISO C++14. --end note ]
1225 if (Intro.Default == LCD_ByCopy && C->Kind != LCK_StarThis)
1226 DiagCompat(C->Loc, diag_compat::equals_this_lambda_capture);
1227
1228 // C++11 [expr.prim.lambda]p12:
1229 // If this is captured by a local lambda expression, its nearest
1230 // enclosing function shall be a non-static member function.
1231 QualType ThisCaptureType = getCurrentThisType();
1232 if (ThisCaptureType.isNull()) {
1233 Diag(C->Loc, diag::err_this_capture) << true;
1234 continue;
1235 }
1236
1237 CheckCXXThisCapture(C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true,
1238 /*FunctionScopeIndexToStopAtPtr*/ nullptr,
1239 C->Kind == LCK_StarThis);
1240 if (!LSI->Captures.empty())
1241 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1242 continue;
1243 }
1244
1245 assert(C->Id && "missing identifier for capture");
1246
1247 if (C->Init.isInvalid())
1248 continue;
1249
1250 ValueDecl *Var = nullptr;
1251 if (C->Init.isUsable()) {
1252 DiagCompat(C->Loc, diag_compat::init_capture);
1253
1254 // If the initializer expression is usable, but the InitCaptureType
1255 // is not, then an error has occurred - so ignore the capture for now.
1256 // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
1257 // FIXME: we should create the init capture variable and mark it invalid
1258 // in this case.
1259 if (C->InitCaptureType.get().isNull())
1260 continue;
1261
1262 if (C->Init.get()->containsUnexpandedParameterPack() &&
1263 !C->InitCaptureType.get()->getAs<PackExpansionType>())
1265
1266 unsigned InitStyle;
1267 switch (C->InitKind) {
1269 llvm_unreachable("not an init-capture?");
1271 InitStyle = VarDecl::CInit;
1272 break;
1274 InitStyle = VarDecl::CallInit;
1275 break;
1277 InitStyle = VarDecl::ListInit;
1278 break;
1279 }
1280 Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
1281 C->EllipsisLoc, C->Id, InitStyle,
1282 C->Init.get(), Method);
1283 assert(Var && "createLambdaInitCaptureVarDecl returned a null VarDecl?");
1284 if (auto *V = dyn_cast<VarDecl>(Var))
1285 CheckShadow(CurrentScope, V);
1286 PushOnScopeChains(Var, CurrentScope, false);
1287 } else {
1288 assert(C->InitKind == LambdaCaptureInitKind::NoInit &&
1289 "init capture has valid but null init?");
1290
1291 // C++11 [expr.prim.lambda]p8:
1292 // If a lambda-capture includes a capture-default that is &, the
1293 // identifiers in the lambda-capture shall not be preceded by &.
1294 // If a lambda-capture includes a capture-default that is =, [...]
1295 // each identifier it contains shall be preceded by &.
1296 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
1297 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
1299 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1300 continue;
1301 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
1302 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
1304 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1305 continue;
1306 }
1307
1308 // C++11 [expr.prim.lambda]p10:
1309 // The identifiers in a capture-list are looked up using the usual
1310 // rules for unqualified name lookup (3.4.1)
1311 DeclarationNameInfo Name(C->Id, C->Loc);
1312 LookupResult R(*this, Name, LookupOrdinaryName);
1313 LookupName(R, CurScope);
1314 if (R.isAmbiguous())
1315 continue;
1316 if (R.empty()) {
1317 // FIXME: Disable corrections that would add qualification?
1318 CXXScopeSpec ScopeSpec;
1319 DeclFilterCCC<VarDecl> Validator{};
1320 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
1321 continue;
1322 }
1323
1324 if (auto *BD = R.getAsSingle<BindingDecl>())
1325 Var = BD;
1326 else if (R.getAsSingle<FieldDecl>()) {
1327 Diag(C->Loc, diag::err_capture_class_member_does_not_name_variable)
1328 << C->Id;
1329 continue;
1330 } else
1331 Var = R.getAsSingle<VarDecl>();
1332 if (Var && DiagnoseUseOfDecl(Var, C->Loc))
1333 continue;
1334 }
1335
1336 // C++11 [expr.prim.lambda]p10:
1337 // [...] each such lookup shall find a variable with automatic storage
1338 // duration declared in the reaching scope of the local lambda expression.
1339 // Note that the 'reaching scope' check happens in tryCaptureVariable().
1340 if (!Var) {
1341 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
1342 continue;
1343 }
1344
1345 // C++11 [expr.prim.lambda]p8:
1346 // An identifier or this shall not appear more than once in a
1347 // lambda-capture.
1348 if (auto [It, Inserted] = CaptureNames.insert(std::pair{C->Id, Var});
1349 !Inserted) {
1350 if (C->InitKind == LambdaCaptureInitKind::NoInit &&
1351 !Var->isInitCapture()) {
1352 Diag(C->Loc, diag::err_capture_more_than_once)
1353 << C->Id << It->second->getBeginLoc()
1355 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1356 Var->setInvalidDecl();
1357 } else if (Var && Var->isPlaceholderVar(getLangOpts())) {
1359 } else {
1360 // Previous capture captured something different (one or both was
1361 // an init-capture): no fixit.
1362 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
1363 continue;
1364 }
1365 }
1366
1367 // Ignore invalid decls; they'll just confuse the code later.
1368 if (Var->isInvalidDecl())
1369 continue;
1370
1371 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
1372
1373 if (!Underlying->hasLocalStorage()) {
1374 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
1375 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
1376 continue;
1377 }
1378
1379 // C++11 [expr.prim.lambda]p23:
1380 // A capture followed by an ellipsis is a pack expansion (14.5.3).
1381 SourceLocation EllipsisLoc;
1382 if (C->EllipsisLoc.isValid()) {
1383 if (Var->isParameterPack()) {
1384 EllipsisLoc = C->EllipsisLoc;
1385 } else {
1386 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1387 << (C->Init.isUsable() ? C->Init.get()->getSourceRange()
1388 : SourceRange(C->Loc));
1389
1390 // Just ignore the ellipsis.
1391 }
1392 } else if (Var->isParameterPack()) {
1393 ContainsUnexpandedParameterPack = true;
1394 }
1395
1396 if (C->Init.isUsable()) {
1397 addInitCapture(LSI, cast<VarDecl>(Var), C->Kind == LCK_ByRef);
1398 } else {
1399 TryCaptureKind Kind = C->Kind == LCK_ByRef
1402 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
1403 }
1404 if (!LSI->Captures.empty())
1405 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1406 }
1408 LSI->ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
1410}
1411
1413 SourceLocation MutableLoc) {
1414
1416 LSI->Mutable = MutableLoc.isValid();
1417 ContextRAII Context(*this, LSI->CallOperator, /*NewThisContext*/ false);
1418
1419 // C++11 [expr.prim.lambda]p9:
1420 // A lambda-expression whose smallest enclosing scope is a block scope is a
1421 // local lambda expression; any other lambda expression shall not have a
1422 // capture-default or simple-capture in its lambda-introducer.
1423 //
1424 // For simple-captures, this is covered by the check below that any named
1425 // entity is a variable that can be captured.
1426 //
1427 // For DR1632, we also allow a capture-default in any context where we can
1428 // odr-use 'this' (in particular, in a default initializer for a non-static
1429 // data member).
1430 if (Intro.Default != LCD_None &&
1431 !LSI->Lambda->getParent()
1433 ->isFunctionOrMethod() &&
1434 (getCurrentThisType().isNull() ||
1435 CheckCXXThisCapture(SourceLocation(), /*Explicit=*/true,
1436 /*BuildAndDiagnose=*/false)))
1437 Diag(Intro.DefaultLoc, diag::err_capture_default_non_local);
1438}
1439
1443 PushDeclContext(LambdaScope, LSI->CallOperator);
1444
1445 for (const DeclaratorChunk::ParamInfo &P : Params) {
1446 auto *Param = cast<ParmVarDecl>(P.Param);
1447 Param->setOwningFunction(LSI->CallOperator);
1448 if (Param->getIdentifier())
1449 PushOnScopeChains(Param, LambdaScope, false);
1450 }
1451
1452 // After the parameter list, we may parse a noexcept/requires/trailing return
1453 // type which need to know whether the call operator constiture a dependent
1454 // context, so we need to setup the FunctionTemplateDecl of generic lambdas
1455 // now.
1456 TemplateParameterList *TemplateParams =
1458 if (TemplateParams) {
1460 TemplateParams);
1461 LSI->Lambda->setLambdaIsGeneric(true);
1463 TemplateParams->containsUnexpandedParameterPack();
1464 }
1465 LSI->AfterParameterList = true;
1466}
1467
1469 Declarator &ParamInfo,
1470 const DeclSpec &DS) {
1471
1474 LSI->BeforeCompoundStatement = false;
1475
1477 bool ExplicitResultType;
1478
1479 SourceLocation TypeLoc, CallOperatorLoc;
1480 if (ParamInfo.getNumTypeObjects() == 0) {
1481 CallOperatorLoc = TypeLoc = Intro.Range.getEnd();
1482 } else {
1483 unsigned Index;
1484 ParamInfo.isFunctionDeclarator(Index);
1485 const auto &Object = ParamInfo.getTypeObject(Index);
1486 TypeLoc =
1487 Object.Loc.isValid() ? Object.Loc : ParamInfo.getSourceRange().getEnd();
1488 CallOperatorLoc = ParamInfo.getSourceRange().getEnd();
1489 }
1490
1491 CXXRecordDecl *Class = LSI->Lambda;
1493
1494 TypeSourceInfo *MethodTyInfo = getLambdaType(
1495 *this, Intro, ParamInfo, getCurScope(), TypeLoc, ExplicitResultType);
1496
1497 if (ParamInfo.isFunctionDeclarator() != 0) {
1498 const auto &FTI = ParamInfo.getFunctionTypeInfo();
1499 LSI->ExplicitParams = FTI.getLParenLoc().isValid();
1500 if (!FTIHasSingleVoidParameter(FTI)) {
1501 Params.reserve(FTI.NumParams);
1502 for (unsigned I = 0; I < FTI.NumParams; ++I) {
1503 auto *Param = cast<ParmVarDecl>(FTI.Params[I].Param);
1504 Param->setScopeInfo(0, Params.size());
1505 Params.push_back(Param);
1506 }
1507 }
1508 }
1509
1510 bool IsLambdaStatic =
1512
1514 Method, Intro.Range.getBegin(), CallOperatorLoc,
1515 AssociatedConstraint(ParamInfo.getTrailingRequiresClause()), MethodTyInfo,
1516 ParamInfo.getDeclSpec().getConstexprSpecifier(),
1517 IsLambdaStatic ? SC_Static : SC_None, Params, ExplicitResultType);
1518
1520
1521 // code_seg attribute on lambda apply to the method.
1523 Method, /*IsDefinition=*/true))
1524 Method->addAttr(A);
1525
1526 // Attributes on the lambda apply to the method.
1527 ProcessDeclAttributes(CurScope, Method, ParamInfo);
1528
1529 // This represents the function body for the lambda function, check if we
1530 // have to apply optnone due to a pragma.
1532
1533 if (Context.getTargetInfo().getTriple().isAArch64())
1535
1536 // CUDA lambdas get implicit host and device attributes.
1537 if (getLangOpts().CUDA)
1539
1540 // OpenMP lambdas might get assumumption attributes.
1541 if (LangOpts.OpenMP)
1543
1545
1546 for (auto &&C : LSI->Captures) {
1547 if (!C.isVariableCapture())
1548 continue;
1549 ValueDecl *Var = C.getVariable();
1550 if (Var && Var->isInitCapture()) {
1551 PushOnScopeChains(Var, CurScope, false);
1552 }
1553 }
1554
1555 auto CheckRedefinition = [&](ParmVarDecl *Param) {
1556 for (const auto &Capture : Intro.Captures) {
1557 if (Capture.Id == Param->getIdentifier()) {
1558 Diag(Param->getLocation(), diag::err_parameter_shadow_capture);
1559 Diag(Capture.Loc, diag::note_var_explicitly_captured_here)
1560 << Capture.Id << true;
1561 return false;
1562 }
1563 }
1564 return true;
1565 };
1566
1567 for (ParmVarDecl *P : Params) {
1568 if (!P->getIdentifier())
1569 continue;
1570 if (CheckRedefinition(P))
1571 CheckShadow(CurScope, P);
1572 PushOnScopeChains(P, CurScope);
1573 }
1574
1575 // C++23 [expr.prim.lambda.capture]p5:
1576 // If an identifier in a capture appears as the declarator-id of a parameter
1577 // of the lambda-declarator's parameter-declaration-clause or as the name of a
1578 // template parameter of the lambda-expression's template-parameter-list, the
1579 // program is ill-formed.
1580 TemplateParameterList *TemplateParams =
1582 if (TemplateParams) {
1583 for (const auto *TP : TemplateParams->asArray()) {
1584 if (!TP->getIdentifier())
1585 continue;
1586 for (const auto &Capture : Intro.Captures) {
1587 if (Capture.Id == TP->getIdentifier()) {
1588 Diag(Capture.Loc, diag::err_template_param_shadow) << Capture.Id;
1590 }
1591 }
1592 }
1593 }
1594
1595 // C++20: dcl.decl.general p4:
1596 // The optional requires-clause ([temp.pre]) in an init-declarator or
1597 // member-declarator shall be present only if the declarator declares a
1598 // templated function ([dcl.fct]).
1599 if (const AssociatedConstraint &TRC = Method->getTrailingRequiresClause()) {
1600 // [temp.pre]/8:
1601 // An entity is templated if it is
1602 // - a template,
1603 // - an entity defined ([basic.def]) or created ([class.temporary]) in a
1604 // templated entity,
1605 // - a member of a templated entity,
1606 // - an enumerator for an enumeration that is a templated entity, or
1607 // - the closure type of a lambda-expression ([expr.prim.lambda.closure])
1608 // appearing in the declaration of a templated entity. [Note 6: A local
1609 // class, a local or block variable, or a friend function defined in a
1610 // templated entity is a templated entity. — end note]
1611 //
1612 // A templated function is a function template or a function that is
1613 // templated. A templated class is a class template or a class that is
1614 // templated. A templated variable is a variable template or a variable
1615 // that is templated.
1616
1617 // Note: we only have to check if this is defined in a template entity, OR
1618 // if we are a template, since the rest don't apply. The requires clause
1619 // applies to the call operator, which we already know is a member function,
1620 // AND defined.
1621 if (!Method->getDescribedFunctionTemplate() && !Method->isTemplated()) {
1622 Diag(TRC.ConstraintExpr->getBeginLoc(),
1623 diag::err_constrained_non_templated_function);
1624 }
1625 }
1626
1627 // Enter a new evaluation context to insulate the lambda from any
1628 // cleanups from the enclosing full-expression.
1631}
1632
1634 bool IsInstantiation) {
1636
1637 // Leave the expression-evaluation context.
1640
1641 // Leave the context of the lambda.
1642 if (!IsInstantiation)
1644
1645 // Finalize the lambda.
1646 CXXRecordDecl *Class = LSI->Lambda;
1647 Class->setInvalidDecl();
1648 SmallVector<Decl*, 4> Fields(Class->fields());
1649 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
1651 CheckCompletedCXXClass(nullptr, Class);
1652
1654}
1655
1656template <typename Func>
1658 Sema &S, const FunctionProtoType &CallOpProto, Func F) {
1660 CallOpProto.isVariadic(), /*IsCXXMethod=*/false);
1662 CallOpProto.isVariadic(), /*IsCXXMethod=*/true);
1663 CallingConv CallOpCC = CallOpProto.getCallConv();
1664
1665 /// Implement emitting a version of the operator for many of the calling
1666 /// conventions for MSVC, as described here:
1667 /// https://devblogs.microsoft.com/oldnewthing/20150220-00/?p=44623.
1668 /// Experimentally, we determined that cdecl, stdcall, fastcall, and
1669 /// vectorcall are generated by MSVC when it is supported by the target.
1670 /// Additionally, we are ensuring that the default-free/default-member and
1671 /// call-operator calling convention are generated as well.
1672 /// NOTE: We intentionally generate a 'thiscall' on Win32 implicitly from the
1673 /// 'member default', despite MSVC not doing so. We do this in order to ensure
1674 /// that someone who intentionally places 'thiscall' on the lambda call
1675 /// operator will still get that overload, since we don't have the a way of
1676 /// detecting the attribute by the time we get here.
1677 if (S.getLangOpts().MSVCCompat) {
1678 CallingConv Convs[] = {
1680 DefaultFree, DefaultMember, CallOpCC};
1681 llvm::sort(Convs);
1682 llvm::iterator_range<CallingConv *> Range(std::begin(Convs),
1683 llvm::unique(Convs));
1684 const TargetInfo &TI = S.getASTContext().getTargetInfo();
1685
1686 for (CallingConv C : Range) {
1688 F(C);
1689 }
1690 return;
1691 }
1692
1693 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree) {
1694 F(DefaultFree);
1695 F(DefaultMember);
1696 } else {
1697 F(CallOpCC);
1698 }
1699}
1700
1701// Returns the 'standard' calling convention to be used for the lambda
1702// conversion function, that is, the 'free' function calling convention unless
1703// it is overridden by a non-default calling convention attribute.
1704static CallingConv
1706 const FunctionProtoType *CallOpProto) {
1708 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
1710 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
1711 CallingConv CallOpCC = CallOpProto->getCallConv();
1712
1713 // If the call-operator hasn't been changed, return both the 'free' and
1714 // 'member' function calling convention.
1715 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree)
1716 return DefaultFree;
1717 return CallOpCC;
1718}
1719
1721 const FunctionProtoType *CallOpProto, CallingConv CC) {
1722 const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
1723 CallOpProto->getExtProtoInfo();
1724 FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
1725 InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
1726 InvokerExtInfo.TypeQuals = Qualifiers();
1727 assert(InvokerExtInfo.RefQualifier == RQ_None &&
1728 "Lambda's call operator should not have a reference qualifier");
1729 return Context.getFunctionType(CallOpProto->getReturnType(),
1730 CallOpProto->getParamTypes(), InvokerExtInfo);
1731}
1732
1733/// Add a lambda's conversion to function pointer, as described in
1734/// C++11 [expr.prim.lambda]p6.
1735static void addFunctionPointerConversion(Sema &S, SourceRange IntroducerRange,
1736 CXXRecordDecl *Class,
1737 CXXMethodDecl *CallOperator,
1738 QualType InvokerFunctionTy) {
1739 // This conversion is explicitly disabled if the lambda's function has
1740 // pass_object_size attributes on any of its parameters.
1741 auto HasPassObjectSizeAttr = [](const ParmVarDecl *P) {
1742 return P->hasAttr<PassObjectSizeAttr>();
1743 };
1744 if (llvm::any_of(CallOperator->parameters(), HasPassObjectSizeAttr))
1745 return;
1746
1747 // Add the conversion to function pointer.
1748 QualType PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
1749
1750 // Create the type of the conversion function.
1753 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1754 // The conversion function is always const and noexcept.
1755 ConvExtInfo.TypeQuals = Qualifiers();
1756 ConvExtInfo.TypeQuals.addConst();
1757 ConvExtInfo.ExceptionSpec.Type = EST_BasicNoexcept;
1758 QualType ConvTy = S.Context.getFunctionType(PtrToFunctionTy, {}, ConvExtInfo);
1759
1760 SourceLocation Loc = IntroducerRange.getBegin();
1761 DeclarationName ConversionName
1763 S.Context.getCanonicalType(PtrToFunctionTy));
1764 // Construct a TypeSourceInfo for the conversion function, and wire
1765 // all the parameters appropriately for the FunctionProtoTypeLoc
1766 // so that everything works during transformation/instantiation of
1767 // generic lambdas.
1768 // The main reason for wiring up the parameters of the conversion
1769 // function with that of the call operator is so that constructs
1770 // like the following work:
1771 // auto L = [](auto b) { <-- 1
1772 // return [](auto a) -> decltype(a) { <-- 2
1773 // return a;
1774 // };
1775 // };
1776 // int (*fp)(int) = L(5);
1777 // Because the trailing return type can contain DeclRefExprs that refer
1778 // to the original call operator's variables, we hijack the call
1779 // operators ParmVarDecls below.
1780 TypeSourceInfo *ConvNamePtrToFunctionTSI =
1781 S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
1782 DeclarationNameLoc ConvNameLoc =
1783 DeclarationNameLoc::makeNamedTypeLoc(ConvNamePtrToFunctionTSI);
1784
1785 // The conversion function is a conversion to a pointer-to-function.
1786 TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
1787 FunctionProtoTypeLoc ConvTL =
1789 // Get the result of the conversion function which is a pointer-to-function.
1790 PointerTypeLoc PtrToFunctionTL =
1791 ConvTL.getReturnLoc().getAs<PointerTypeLoc>();
1792 // Do the same for the TypeSourceInfo that is used to name the conversion
1793 // operator.
1794 PointerTypeLoc ConvNamePtrToFunctionTL =
1795 ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
1796
1797 // Get the underlying function types that the conversion function will
1798 // be converting to (should match the type of the call operator).
1799 FunctionProtoTypeLoc CallOpConvTL =
1800 PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1801 FunctionProtoTypeLoc CallOpConvNameTL =
1802 ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1803
1804 // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
1805 // These parameter's are essentially used to transform the name and
1806 // the type of the conversion operator. By using the same parameters
1807 // as the call operator's we don't have to fix any back references that
1808 // the trailing return type of the call operator's uses (such as
1809 // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
1810 // - we can simply use the return type of the call operator, and
1811 // everything should work.
1812 SmallVector<ParmVarDecl *, 4> InvokerParams;
1813 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1814 ParmVarDecl *From = CallOperator->getParamDecl(I);
1815
1816 InvokerParams.push_back(ParmVarDecl::Create(
1817 S.Context,
1818 // Temporarily add to the TU. This is set to the invoker below.
1820 From->getLocation(), From->getIdentifier(), From->getType(),
1821 From->getTypeSourceInfo(), From->getStorageClass(),
1822 /*DefArg=*/nullptr));
1823 CallOpConvTL.setParam(I, From);
1824 CallOpConvNameTL.setParam(I, From);
1825 }
1826
1828 S.Context, Class, Loc,
1829 DeclarationNameInfo(ConversionName, Loc, ConvNameLoc), ConvTy, ConvTSI,
1831 /*isInline=*/true, ExplicitSpecifier(),
1834 CallOperator->getBody()->getEndLoc());
1835 Conversion->setAccess(AS_public);
1836 Conversion->setImplicit(true);
1837
1838 // A non-generic lambda may still be a templated entity. We need to preserve
1839 // constraints when converting the lambda to a function pointer. See GH63181.
1840 if (const AssociatedConstraint &Requires =
1841 CallOperator->getTrailingRequiresClause())
1842 Conversion->setTrailingRequiresClause(Requires);
1843
1844 if (Class->isGenericLambda()) {
1845 // Create a template version of the conversion operator, using the template
1846 // parameter list of the function call operator.
1847 FunctionTemplateDecl *TemplateCallOperator =
1848 CallOperator->getDescribedFunctionTemplate();
1849 FunctionTemplateDecl *ConversionTemplate =
1851 Loc, ConversionName,
1852 TemplateCallOperator->getTemplateParameters(),
1853 Conversion);
1854 ConversionTemplate->setAccess(AS_public);
1855 ConversionTemplate->setImplicit(true);
1856 Conversion->setDescribedFunctionTemplate(ConversionTemplate);
1857 Class->addDecl(ConversionTemplate);
1858 } else
1859 Class->addDecl(Conversion);
1860
1861 // If the lambda is not static, we need to add a static member
1862 // function that will be the result of the conversion with a
1863 // certain unique ID.
1864 // When it is static we just return the static call operator instead.
1865 if (CallOperator->isImplicitObjectMemberFunction()) {
1866 DeclarationName InvokerName =
1868 // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
1869 // we should get a prebuilt TrivialTypeSourceInfo from Context
1870 // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
1871 // then rewire the parameters accordingly, by hoisting up the InvokeParams
1872 // loop below and then use its Params to set Invoke->setParams(...) below.
1873 // This would avoid the 'const' qualifier of the calloperator from
1874 // contaminating the type of the invoker, which is currently adjusted
1875 // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the
1876 // trailing return type of the invoker would require a visitor to rebuild
1877 // the trailing return type and adjusting all back DeclRefExpr's to refer
1878 // to the new static invoker parameters - not the call operator's.
1880 S.Context, Class, Loc, DeclarationNameInfo(InvokerName, Loc),
1881 InvokerFunctionTy, CallOperator->getTypeSourceInfo(), SC_Static,
1883 /*isInline=*/true, CallOperator->getConstexprKind(),
1884 CallOperator->getBody()->getEndLoc());
1885 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
1886 InvokerParams[I]->setOwningFunction(Invoke);
1887 Invoke->setParams(InvokerParams);
1888 Invoke->setAccess(AS_private);
1889 Invoke->setImplicit(true);
1890 if (Class->isGenericLambda()) {
1891 FunctionTemplateDecl *TemplateCallOperator =
1892 CallOperator->getDescribedFunctionTemplate();
1893 FunctionTemplateDecl *StaticInvokerTemplate =
1895 S.Context, Class, Loc, InvokerName,
1896 TemplateCallOperator->getTemplateParameters(), Invoke);
1897 StaticInvokerTemplate->setAccess(AS_private);
1898 StaticInvokerTemplate->setImplicit(true);
1899 Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
1900 Class->addDecl(StaticInvokerTemplate);
1901 } else
1902 Class->addDecl(Invoke);
1903 }
1904}
1905
1906/// Add a lambda's conversion to function pointers, as described in
1907/// C++11 [expr.prim.lambda]p6. Note that in most cases, this should emit only a
1908/// single pointer conversion. In the event that the default calling convention
1909/// for free and member functions is different, it will emit both conventions.
1910static void addFunctionPointerConversions(Sema &S, SourceRange IntroducerRange,
1911 CXXRecordDecl *Class,
1912 CXXMethodDecl *CallOperator) {
1913 const FunctionProtoType *CallOpProto =
1914 CallOperator->getType()->castAs<FunctionProtoType>();
1915
1917 S, *CallOpProto, [&](CallingConv CC) {
1918 QualType InvokerFunctionTy =
1919 S.getLambdaConversionFunctionResultType(CallOpProto, CC);
1920 addFunctionPointerConversion(S, IntroducerRange, Class, CallOperator,
1921 InvokerFunctionTy);
1922 });
1923}
1924
1925/// Add a lambda's conversion to block pointer.
1927 SourceRange IntroducerRange,
1928 CXXRecordDecl *Class,
1929 CXXMethodDecl *CallOperator) {
1930 const FunctionProtoType *CallOpProto =
1931 CallOperator->getType()->castAs<FunctionProtoType>();
1933 CallOpProto, getLambdaConversionFunctionCallConv(S, CallOpProto));
1934 QualType BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
1935
1936 FunctionProtoType::ExtProtoInfo ConversionEPI(
1938 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1939 ConversionEPI.TypeQuals = Qualifiers();
1940 ConversionEPI.TypeQuals.addConst();
1941 QualType ConvTy = S.Context.getFunctionType(BlockPtrTy, {}, ConversionEPI);
1942
1943 SourceLocation Loc = IntroducerRange.getBegin();
1944 DeclarationName Name
1946 S.Context.getCanonicalType(BlockPtrTy));
1948 S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc));
1950 S.Context, Class, Loc, DeclarationNameInfo(Name, Loc, NameLoc), ConvTy,
1951 S.Context.getTrivialTypeSourceInfo(ConvTy, Loc),
1954 CallOperator->getBody()->getEndLoc());
1955 Conversion->setAccess(AS_public);
1956 Conversion->setImplicit(true);
1957 Class->addDecl(Conversion);
1958}
1959
1961 SourceLocation ImplicitCaptureLoc,
1962 bool IsOpenMPMapping) {
1963 // VLA captures don't have a stored initialization expression.
1964 if (Cap.isVLATypeCapture())
1965 return ExprResult();
1966
1967 // An init-capture is initialized directly from its stored initializer.
1968 if (Cap.isInitCapture())
1969 return cast<VarDecl>(Cap.getVariable())->getInit();
1970
1971 // For anything else, build an initialization expression. For an implicit
1972 // capture, the capture notionally happens at the capture-default, so use
1973 // that location here.
1974 SourceLocation Loc =
1975 ImplicitCaptureLoc.isValid() ? ImplicitCaptureLoc : Cap.getLocation();
1976
1977 // C++11 [expr.prim.lambda]p21:
1978 // When the lambda-expression is evaluated, the entities that
1979 // are captured by copy are used to direct-initialize each
1980 // corresponding non-static data member of the resulting closure
1981 // object. (For array members, the array elements are
1982 // direct-initialized in increasing subscript order.) These
1983 // initializations are performed in the (unspecified) order in
1984 // which the non-static data members are declared.
1985
1986 // C++ [expr.prim.lambda]p12:
1987 // An entity captured by a lambda-expression is odr-used (3.2) in
1988 // the scope containing the lambda-expression.
1990 IdentifierInfo *Name = nullptr;
1991 if (Cap.isThisCapture()) {
1992 QualType ThisTy = getCurrentThisType();
1993 Expr *This = BuildCXXThisExpr(Loc, ThisTy, ImplicitCaptureLoc.isValid());
1994 if (Cap.isCopyCapture())
1995 Init = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
1996 else
1997 Init = This;
1998 } else {
1999 assert(Cap.isVariableCapture() && "unknown kind of capture");
2000 ValueDecl *Var = Cap.getVariable();
2001 // For OpenMP structured bindings, capture the decomposed decl, not the
2002 // binding.
2003 auto *BD = dyn_cast<BindingDecl>(Var);
2004 if (IsOpenMPMapping && BD)
2005 // When capturing a BindingDecl in an OpenMP mapping context, we need to
2006 // capture the DecompositionDecl instead. BindingDecls are references to
2007 // storage owned by the DecompositionDecl.
2008 // Example:
2009 // auto [a, b] = p;
2010 // auto lambda = [a]() { return a; }; // In OpenMP context.
2011 // This is reached during lambda capture for OpenMP mappings.
2012 Var = BD->getDecomposedDecl();
2013 Name = Var->getIdentifier();
2015 CXXScopeSpec(), DeclarationNameInfo(Var->getDeclName(), Loc), Var);
2016 }
2017
2018 // In OpenMP, the capture kind doesn't actually describe how to capture:
2019 // variables are "mapped" onto the device in a process that does not formally
2020 // make a copy, even for a "copy capture".
2021 if (IsOpenMPMapping)
2022 return Init;
2023
2024 if (Init.isInvalid())
2025 return ExprError();
2026
2027 Expr *InitExpr = Init.get();
2029 Name, Cap.getCaptureType(), Loc);
2030 InitializationKind InitKind =
2031 InitializationKind::CreateDirect(Loc, Loc, Loc);
2032 InitializationSequence InitSeq(*this, Entity, InitKind, InitExpr);
2033 return InitSeq.Perform(*this, Entity, InitKind, InitExpr);
2034}
2035
2038
2039 if (LSI.CallOperator->hasAttr<SYCLKernelEntryPointAttr>())
2041
2042 ActOnFinishFunctionBody(LSI.CallOperator, Body, /*IsInstantiation=*/false,
2043 /*RetainFunctionScopeInfo=*/true);
2044
2045 return BuildLambdaExpr(StartLoc, Body->getEndLoc());
2046}
2047
2050 switch (ICS) {
2052 return LCD_None;
2054 return LCD_ByCopy;
2057 return LCD_ByRef;
2059 llvm_unreachable("block capture in lambda");
2060 }
2061 llvm_unreachable("Unknown implicit capture style");
2062}
2063
2065 if (From.isInitCapture()) {
2066 Expr *Init = cast<VarDecl>(From.getVariable())->getInit();
2067 if (Init && Init->HasSideEffects(Context))
2068 return true;
2069 }
2070
2071 if (!From.isCopyCapture())
2072 return false;
2073
2074 const QualType T = From.isThisCapture()
2076 : From.getCaptureType();
2077
2078 if (T.isVolatileQualified())
2079 return true;
2080
2081 const Type *BaseT = T->getBaseElementTypeUnsafe();
2082 if (const CXXRecordDecl *RD = BaseT->getAsCXXRecordDecl())
2083 return !RD->isCompleteDefinition() || !RD->hasTrivialCopyConstructor() ||
2084 !RD->hasTrivialDestructor();
2085
2086 return false;
2087}
2088
2090 SourceRange FixItRange,
2091 const Capture &From) {
2092 if (CaptureHasSideEffects(From))
2093 return false;
2094
2095 if (From.isVLATypeCapture())
2096 return false;
2097
2098 // FIXME: maybe we should warn on these if we can find a sensible diagnostic
2099 // message
2100 if (From.isInitCapture() &&
2102 return false;
2103
2104 auto diag = Diag(From.getLocation(), diag::warn_unused_lambda_capture);
2105 if (From.isThisCapture())
2106 diag << "'this'";
2107 else
2108 diag << From.getVariable();
2109 diag << From.isNonODRUsed();
2110 // If we were able to resolve the fixit range we'll create a fixit,
2111 // otherwise we just use the raw capture range for the diagnostic.
2112 if (FixItRange.isValid())
2113 diag << FixItHint::CreateRemoval(FixItRange);
2114 else
2115 diag << CaptureRange;
2116 return true;
2117}
2118
2119/// Create a field within the lambda class or captured statement record for the
2120/// given capture.
2122 bool IsOpenMP) {
2124 QualType FieldType = Capture.getCaptureType();
2125 TypeSourceInfo *TSI = nullptr;
2126 if (Capture.isVariableCapture()) {
2127 const VarDecl *Var = nullptr;
2128 if (IsOpenMP) {
2129 if (auto *BD = dyn_cast_or_null<BindingDecl>(Capture.getVariable())) {
2130 Var = cast<VarDecl>(BD->getDecomposedDecl());
2131 FieldType = Var->getType().getNonReferenceType();
2133 FieldType = Context.getLValueReferenceType(FieldType);
2134 } else if (auto *DD = dyn_cast_or_null<DecompositionDecl>(
2135 Capture.getVariable())) {
2136 // OpenMP already transformed BindingDecl to DecompositionDecl
2137 // before buildCapturedStmtCaptureList. Use the DecompositionDecl
2138 // type.
2139 Var = DD;
2140 FieldType = DD->getType().getNonReferenceType();
2142 FieldType = Context.getLValueReferenceType(DD->getType());
2143 }
2144 }
2145 if (!Var)
2146 Var = dyn_cast_or_null<VarDecl>(Capture.getVariable());
2147 if (Var && Var->isInitCapture())
2148 TSI = Var->getTypeSourceInfo();
2149 }
2150
2151 // FIXME: Should we really be doing this? A null TypeSourceInfo seems more
2152 // appropriate, at least for an implicit capture.
2153 if (!TSI)
2154 TSI = Context.getTrivialTypeSourceInfo(FieldType, Loc);
2155
2156 // Build the non-static data member.
2157 FieldDecl *Field =
2158 FieldDecl::Create(Context, RD, /*StartLoc=*/Loc, /*IdLoc=*/Loc,
2159 /*Id=*/nullptr, FieldType, TSI, /*BW=*/nullptr,
2160 /*Mutable=*/false, ICIS_NoInit);
2161 // If the variable being captured has an invalid type, mark the class as
2162 // invalid as well.
2163 if (!FieldType->isDependentType()) {
2164 if (RequireCompleteSizedType(Loc, FieldType,
2165 diag::err_field_incomplete_or_sizeless)) {
2166 RD->setInvalidDecl();
2167 Field->setInvalidDecl();
2168 } else {
2169 NamedDecl *Def;
2170 FieldType->isIncompleteType(&Def);
2171 if (Def && Def->isInvalidDecl()) {
2172 RD->setInvalidDecl();
2173 Field->setInvalidDecl();
2174 }
2175 }
2176 }
2177 Field->setImplicit(true);
2178 Field->setAccess(AS_private);
2179 RD->addDecl(Field);
2180
2182 Field->setCapturedVLAType(Capture.getCapturedVLAType());
2183
2184 return Field;
2185}
2186
2187static SourceRange
2189 SourceLocation PrevCaptureLoc,
2190 bool CurHasPreviousCapture, bool IsLast) {
2191 if (!CaptureRange.isValid())
2192 return SourceRange();
2193
2194 auto GetTrailingEndLocation = [&](SourceLocation StartPoint) {
2195 SourceRange NextToken = S.getRangeForNextToken(
2196 StartPoint, /*IncludeMacros=*/false, /*IncludeComments=*/true);
2197 if (!NextToken.isValid())
2198 return SourceLocation();
2199 // Return the last location preceding the next token
2200 return NextToken.getBegin().getLocWithOffset(-1);
2201 };
2202
2203 if (!CurHasPreviousCapture && !IsLast) {
2204 // If there are no captures preceding this capture, remove the
2205 // trailing comma and anything up to the next token
2206 SourceRange CommaRange =
2207 S.getRangeForNextToken(CaptureRange.getEnd(), /*IncludeMacros=*/false,
2208 /*IncludeComments=*/false, tok::comma);
2209 SourceLocation FixItEnd = GetTrailingEndLocation(CommaRange.getBegin());
2210 return SourceRange(CaptureRange.getBegin(), FixItEnd);
2211 }
2212
2213 // Otherwise, remove the comma since the last used capture, and
2214 // anything up to the next token
2215 SourceLocation FixItStart = S.getLocForEndOfToken(PrevCaptureLoc);
2216 SourceLocation FixItEnd = GetTrailingEndLocation(CaptureRange.getEnd());
2217 return SourceRange(FixItStart, FixItEnd);
2218}
2219
2221 SourceLocation EndLoc) {
2223 // Collect information from the lambda scope.
2225 SmallVector<Expr *, 4> CaptureInits;
2226 SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc;
2227 LambdaCaptureDefault CaptureDefault =
2229 CXXRecordDecl *Class = LSI->Lambda;
2230 CXXMethodDecl *CallOperator = LSI->CallOperator;
2231 SourceRange IntroducerRange = LSI->IntroducerRange;
2232 bool ExplicitParams = LSI->ExplicitParams;
2233 bool ExplicitResultType = !LSI->HasImplicitReturnType;
2234 CleanupInfo LambdaCleanup = LSI->Cleanup;
2235 bool ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
2236 bool IsGenericLambda = Class->isGenericLambda();
2237
2238 CallOperator->setLexicalDeclContext(Class);
2239 Decl *TemplateOrNonTemplateCallOperatorDecl =
2240 CallOperator->getDescribedFunctionTemplate()
2241 ? CallOperator->getDescribedFunctionTemplate()
2242 : cast<Decl>(CallOperator);
2243
2244 // FIXME: Is this really the best choice? Keeping the lexical decl context
2245 // set as CurContext seems more faithful to the source.
2246 TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
2247
2248 {
2249 // TreeTransform of immediate functions may call getCurLambda, which
2250 // requires both the paired LSI and the lambda DeclContext.
2251 ContextRAII SavedContext(*this, CallOperator, /*NewThisContext=*/false);
2253 }
2254
2256 AnalysisWarnings.getPolicyInEffectAt(EndLoc);
2257 // We cannot release LSI until we finish computing captures, which
2258 // requires the scope to be popped.
2260
2261 // True if the current capture has a used capture or default before it.
2262 bool CurHasPreviousCapture = CaptureDefault != LCD_None;
2263 SourceLocation PrevCaptureLoc =
2264 CurHasPreviousCapture ? CaptureDefaultLoc : IntroducerRange.getBegin();
2265
2266 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
2267 const Capture &From = LSI->Captures[I];
2268
2269 if (From.isInvalid())
2270 return ExprError();
2271
2272 assert(!From.isBlockCapture() && "Cannot capture __block variables");
2273 bool IsImplicit = I >= LSI->NumExplicitCaptures;
2274 SourceLocation ImplicitCaptureLoc =
2275 IsImplicit ? CaptureDefaultLoc : SourceLocation();
2276
2277 // Use source ranges of explicit captures for fixits where available.
2278 SourceRange CaptureRange = LSI->ExplicitCaptureRanges[I];
2279
2280 // Warn about unused explicit captures.
2281 bool IsCaptureUsed = true;
2282 if (!CurContext->isDependentContext() && !IsImplicit && !From.isODRUsed()) {
2283 // Initialized captures that are non-ODR used may not be eliminated.
2284 // FIXME: Where did the IsGenericLambda here come from?
2285 bool NonODRUsedInitCapture =
2286 IsGenericLambda && From.isNonODRUsed() && From.isInitCapture();
2287 if (!NonODRUsedInitCapture) {
2288 bool IsLast = (I + 1) == LSI->NumExplicitCaptures;
2290 *this, CaptureRange, PrevCaptureLoc, CurHasPreviousCapture, IsLast);
2291 IsCaptureUsed =
2292 !DiagnoseUnusedLambdaCapture(CaptureRange, FixItRange, From);
2293 }
2294 }
2295
2296 if (CaptureRange.isValid()) {
2297 CurHasPreviousCapture |= IsCaptureUsed;
2298 PrevCaptureLoc = CaptureRange.getEnd();
2299 }
2300
2301 // Map the capture to our AST representation.
2302 LambdaCapture Capture = [&] {
2303 if (From.isThisCapture()) {
2304 // Capturing 'this' implicitly with a default of '[=]' is deprecated,
2305 // because it results in a reference capture. Don't warn prior to
2306 // C++2a; there's nothing that can be done about it before then.
2307 if (getLangOpts().CPlusPlus20 && IsImplicit &&
2308 CaptureDefault == LCD_ByCopy) {
2309 Diag(From.getLocation(), diag::warn_deprecated_this_capture);
2310 Diag(CaptureDefaultLoc, diag::note_deprecated_this_capture)
2312 getLocForEndOfToken(CaptureDefaultLoc), ", this");
2313 }
2314 return LambdaCapture(From.getLocation(), IsImplicit,
2316 } else if (From.isVLATypeCapture()) {
2317 return LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType);
2318 } else {
2319 assert(From.isVariableCapture() && "unknown kind of capture");
2320 ValueDecl *Var = From.getVariable();
2322 return LambdaCapture(From.getLocation(), IsImplicit, Kind, Var,
2323 From.getEllipsisLoc());
2324 }
2325 }();
2326
2327 // Form the initializer for the capture field.
2328 ExprResult Init = BuildCaptureInit(From, ImplicitCaptureLoc);
2329
2330 // FIXME: Skip this capture if the capture is not used, the initializer
2331 // has no side-effects, the type of the capture is trivial, and the
2332 // lambda is not externally visible.
2333
2334 // Add a FieldDecl for the capture and form its initializer.
2335 BuildCaptureField(Class, From);
2336 Captures.push_back(Capture);
2337 CaptureInits.push_back(Init.get());
2338
2339 if (LangOpts.CUDA)
2340 CUDA().CheckLambdaCapture(CallOperator, From);
2341 }
2342
2343 Class->setCaptures(Context, Captures);
2344
2345 // C++11 [expr.prim.lambda]p6:
2346 // The closure type for a lambda-expression with no lambda-capture
2347 // has a public non-virtual non-explicit const conversion function
2348 // to pointer to function having the same parameter and return
2349 // types as the closure type's function call operator.
2350 if (Captures.empty() && CaptureDefault == LCD_None)
2351 addFunctionPointerConversions(*this, IntroducerRange, Class, CallOperator);
2352
2353 // Objective-C++:
2354 // The closure type for a lambda-expression has a public non-virtual
2355 // non-explicit const conversion function to a block pointer having the
2356 // same parameter and return types as the closure type's function call
2357 // operator.
2358 // FIXME: Fix generic lambda to block conversions.
2359 if (getLangOpts().Blocks && getLangOpts().ObjC && !IsGenericLambda)
2360 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
2361
2362 // Finalize the lambda class.
2363 SmallVector<Decl *, 4> Fields(Class->fields());
2364 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
2366 CheckCompletedCXXClass(nullptr, Class);
2367
2368 Cleanup.mergeFrom(LambdaCleanup);
2369
2370 LambdaExpr *Lambda =
2371 LambdaExpr::Create(Context, Class, IntroducerRange, CaptureDefault,
2372 CaptureDefaultLoc, ExplicitParams, ExplicitResultType,
2373 CaptureInits, EndLoc, ContainsUnexpandedParameterPack);
2374
2375 // If the lambda expression's call operator is not explicitly marked constexpr
2376 // and is not dependent, analyze the call operator to infer
2377 // its constexpr-ness, suppressing diagnostics while doing so.
2378 if (getLangOpts().CPlusPlus17 && !CallOperator->isInvalidDecl() &&
2379 !CallOperator->isConstexpr() &&
2380 !isa<CoroutineBodyStmt>(CallOperator->getBody()) &&
2381 !Class->isDependentContext()) {
2382 CallOperator->setConstexprKind(
2387 }
2388
2389 // Emit delayed shadowing warnings now that the full capture list is known.
2391
2392 if (!CurContext->isDependentContext()) {
2393 switch (ExprEvalContexts.back().Context) {
2394 // C++11 [expr.prim.lambda]p2:
2395 // A lambda-expression shall not appear in an unevaluated operand
2396 // (Clause 5).
2400 // C++1y [expr.const]p2:
2401 // A conditional-expression e is a core constant expression unless the
2402 // evaluation of e, following the rules of the abstract machine, would
2403 // evaluate [...] a lambda-expression.
2404 //
2405 // This is technically incorrect, there are some constant evaluated contexts
2406 // where this should be allowed. We should probably fix this when DR1607 is
2407 // ratified, it lays out the exact set of conditions where we shouldn't
2408 // allow a lambda-expression.
2411 // We don't actually diagnose this case immediately, because we
2412 // could be within a context where we might find out later that
2413 // the expression is potentially evaluated (e.g., for typeid).
2414 ExprEvalContexts.back().Lambdas.push_back(Lambda);
2415 break;
2416
2420 break;
2421 }
2423 }
2424
2425 return MaybeBindToTemporary(Lambda);
2426}
2427
2429 SourceLocation ConvLocation,
2430 CXXConversionDecl *Conv,
2431 Expr *Src) {
2432 // Make sure that the lambda call operator is marked used.
2433 CXXRecordDecl *Lambda = Conv->getParent();
2434 CXXMethodDecl *CallOperator
2436 Lambda->lookup(
2437 Context.DeclarationNames.getCXXOperatorName(OO_Call)).front());
2438 CallOperator->setReferenced();
2439 CallOperator->markUsed(Context);
2440
2443 CurrentLocation, Src);
2444 if (!Init.isInvalid())
2445 Init = ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
2446
2447 if (Init.isInvalid())
2448 return ExprError();
2449
2450 // Create the new block to be returned.
2452
2453 // Set the type information.
2454 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
2455 Block->setIsVariadic(CallOperator->isVariadic());
2456 Block->setBlockMissingReturnType(false);
2457
2458 // Add parameters.
2460 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
2461 ParmVarDecl *From = CallOperator->getParamDecl(I);
2462 BlockParams.push_back(ParmVarDecl::Create(
2463 Context, Block, From->getBeginLoc(), From->getLocation(),
2464 From->getIdentifier(), From->getType(), From->getTypeSourceInfo(),
2465 From->getStorageClass(),
2466 /*DefArg=*/nullptr));
2467 }
2468 Block->setParams(BlockParams);
2469
2470 Block->setIsConversionFromLambda(true);
2471
2472 // Add capture. The capture uses a fake variable, which doesn't correspond
2473 // to any actual memory location. However, the initializer copy-initializes
2474 // the lambda object.
2475 TypeSourceInfo *CapVarTSI =
2476 Context.getTrivialTypeSourceInfo(Src->getType());
2477 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
2478 ConvLocation, nullptr,
2479 Src->getType(), CapVarTSI,
2480 SC_None);
2481 BlockDecl::Capture Capture(/*variable=*/CapVar, /*byRef=*/false,
2482 /*nested=*/false, /*copy=*/Init.get());
2483 Block->setCaptures(Context, Capture, /*CapturesCXXThis=*/false);
2484
2485 // Add a fake function body to the block. IR generation is responsible
2486 // for filling in the actual body, which cannot be expressed as an AST.
2487 Block->setBody(new (Context) CompoundStmt(ConvLocation));
2488
2489 // Create the block literal expression.
2490 // TODO: Do we ever get here if we have unexpanded packs in the lambda???
2491 Expr *BuildBlock =
2493 /*ContainsUnexpandedParameterPack=*/false);
2494 ExprCleanupObjects.push_back(Block);
2495 Cleanup.setExprNeedsCleanups(true);
2496
2497 return BuildBlock;
2498}
2499
2504 return FD;
2505 }
2506
2508 return FD->getInstantiatedFromDecl();
2509
2511 if (!FTD)
2512 return nullptr;
2513
2516
2517 return FTD->getTemplatedDecl();
2518}
2519
2520bool Sema::addInstantiatedCapturesToScope(
2521 FunctionDecl *Function, const FunctionDecl *PatternDecl,
2523 const MultiLevelTemplateArgumentList &TemplateArgs) {
2524 const auto *LambdaClass = cast<CXXMethodDecl>(Function)->getParent();
2525 const auto *LambdaPattern = cast<CXXMethodDecl>(PatternDecl)->getParent();
2526
2527 unsigned Instantiated = 0;
2528
2529 // FIXME: This is a workaround for not having deferred lambda body
2530 // instantiation.
2531 // When transforming a lambda's body, if we encounter another call to a
2532 // nested lambda that contains a constraint expression, we add all of the
2533 // outer lambda's instantiated captures to the current instantiation scope to
2534 // facilitate constraint evaluation. However, these captures don't appear in
2535 // the CXXRecordDecl until after the lambda expression is rebuilt, so we
2536 // pull them out from the corresponding LSI.
2537 LambdaScopeInfo *InstantiatingScope = nullptr;
2538 if (LambdaPattern->capture_size() && !LambdaClass->capture_size()) {
2539 for (FunctionScopeInfo *Scope : llvm::reverse(FunctionScopes)) {
2540 auto *LSI = dyn_cast<LambdaScopeInfo>(Scope);
2541 if (!LSI || getPatternFunctionDecl(LSI->CallOperator) != PatternDecl)
2542 continue;
2543 InstantiatingScope = LSI;
2544 break;
2545 }
2546 assert(InstantiatingScope);
2547 }
2548
2549 auto AddSingleCapture = [&](const ValueDecl *CapturedPattern,
2550 unsigned Index) {
2551 ValueDecl *CapturedVar =
2552 InstantiatingScope ? InstantiatingScope->Captures[Index].getVariable()
2553 : LambdaClass->getCapture(Index)->getCapturedVar();
2554 assert(CapturedVar->isInitCapture());
2555 Scope.InstantiatedLocal(CapturedPattern, CapturedVar);
2556 };
2557
2558 for (const LambdaCapture &CapturePattern : LambdaPattern->captures()) {
2559 if (!CapturePattern.capturesVariable()) {
2560 Instantiated++;
2561 continue;
2562 }
2563 ValueDecl *CapturedPattern = CapturePattern.getCapturedVar();
2564
2565 if (!CapturedPattern->isInitCapture()) {
2566 Instantiated++;
2567 continue;
2568 }
2569
2570 if (!CapturedPattern->isParameterPack()) {
2571 AddSingleCapture(CapturedPattern, Instantiated++);
2572 } else {
2573 Scope.MakeInstantiatedLocalArgPack(CapturedPattern);
2574 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
2575 SemaRef.collectUnexpandedParameterPacks(
2576 dyn_cast<VarDecl>(CapturedPattern)->getInit(), Unexpanded);
2577 auto NumArgumentsInExpansion =
2578 getNumArgumentsInExpansionFromUnexpanded(Unexpanded, TemplateArgs);
2579 if (!NumArgumentsInExpansion)
2580 continue;
2581 for (unsigned Arg = 0; Arg < *NumArgumentsInExpansion; ++Arg)
2582 AddSingleCapture(CapturedPattern, Instantiated++);
2583 }
2584 }
2585 return false;
2586}
2587
2591 LocalInstantiationScope &Scope, bool ShouldAddDeclsFromParentScope)
2593 if (!isLambdaCallOperator(FD)) {
2595 return;
2596 }
2597
2598 SemaRef.RebuildLambdaScopeInfo(cast<CXXMethodDecl>(FD));
2599
2600 FunctionDecl *FDPattern = getPatternFunctionDecl(FD);
2601 if (!FDPattern)
2602 return;
2603
2604 if (!ShouldAddDeclsFromParentScope)
2605 return;
2606
2608 InstantiationAndPatterns;
2609 while (FDPattern && FD) {
2610 InstantiationAndPatterns.emplace_back(FDPattern, FD);
2611
2612 FDPattern = dyn_cast<FunctionDecl>(
2614 ->getEnclosingNonExpansionStatementContext());
2615 FD = dyn_cast<FunctionDecl>(
2617 ->getEnclosingNonExpansionStatementContext());
2618 }
2619
2620 // Add instantiated parameters and local vars to scopes, starting from the
2621 // outermost lambda to the innermost lambda. This ordering ensures that
2622 // the outer instantiations can be found when referenced from within inner
2623 // lambdas.
2624 //
2625 // auto L = [](auto... x) {
2626 // return [](decltype(x)... y) { }; // Instantiating y needs x
2627 // };
2628 //
2629
2630 for (auto [FDPattern, FD] : llvm::reverse(InstantiationAndPatterns)) {
2631 SemaRef.addInstantiatedParametersToScope(FD, FDPattern, Scope, MLTAL);
2632 SemaRef.addInstantiatedLocalVarsToScope(FD, FDPattern, Scope);
2633
2634 if (isLambdaCallOperator(FD))
2635 SemaRef.addInstantiatedCapturesToScope(FD, FDPattern, Scope, MLTAL);
2636 }
2637}
#define V(N, I)
This file provides some common utility functions for processing Lambda related AST Constructs.
This file defines the classes used to store parsed information about declaration-specifiers and decla...
Defines the clang::Expr interface and subclasses for C++ expressions.
FormatToken * Previous
The previous token in the unwrapped line.
Result
Implement __builtin_bit_cast and related operations.
llvm::json::Object Object
This file declares semantic analysis functions specific to ARM.
This file declares semantic analysis for CUDA constructs.
static LambdaCaptureDefault mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS)
static CallingConv getLambdaConversionFunctionCallConv(Sema &S, const FunctionProtoType *CallOpProto)
static EnumDecl * findEnumForBlockReturn(Expr *E)
If this expression is an enumerator-like expression of some type T, return the type T; otherwise,...
static EnumDecl * findCommonEnumForBlockReturns(ArrayRef< ReturnStmt * > returns)
Attempt to find a common type T for which all of the returned expressions in a block are enumerator-l...
static TypeSourceInfo * getLambdaType(Sema &S, LambdaIntroducer &Intro, Declarator &ParamInfo, Scope *CurScope, SourceLocation Loc, bool &ExplicitResultType)
static FunctionDecl * getPatternFunctionDecl(FunctionDecl *FD)
static LambdaScopeInfo * getCurrentLambdaScopeUnsafe(Sema &S)
static UnsignedOrNone getStackIndexOfNearestEnclosingCaptureReadyLambda(ArrayRef< const clang::sema::FunctionScopeInfo * > FunctionScopes, ValueDecl *VarToCapture)
Examines the FunctionScopeInfo stack to determine the nearest enclosing lambda (to the current lambda...
static void adjustBlockReturnsToEnum(Sema &S, ArrayRef< ReturnStmt * > returns, QualType returnType)
Adjust the given return statements so that they formally return the given type.
static TemplateParameterList * getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef)
static void addBlockPointerConversion(Sema &S, SourceRange IntroducerRange, CXXRecordDecl *Class, CXXMethodDecl *CallOperator)
Add a lambda's conversion to block pointer.
static void buildLambdaScopeReturnType(Sema &S, LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator, bool ExplicitResultType)
static SourceRange ConstructFixItRangeForUnusedCapture(Sema &S, SourceRange CaptureRange, SourceLocation PrevCaptureLoc, bool CurHasPreviousCapture, bool IsLast)
static TypeSourceInfo * getDummyLambdaType(Sema &S, SourceLocation Loc=SourceLocation())
static QualType buildTypeForLambdaCallOperator(Sema &S, clang::CXXRecordDecl *Class, TemplateParameterList *TemplateParams, TypeSourceInfo *MethodTypeInfo)
static void addFunctionPointerConversions(Sema &S, SourceRange IntroducerRange, CXXRecordDecl *Class, CXXMethodDecl *CallOperator)
Add a lambda's conversion to function pointers, as described in C++11 [expr.prim.lambda]p6.
static void repeatForLambdaConversionFunctionCallingConvs(Sema &S, const FunctionProtoType &CallOpProto, Func F)
static void addFunctionPointerConversion(Sema &S, SourceRange IntroducerRange, CXXRecordDecl *Class, CXXMethodDecl *CallOperator, QualType InvokerFunctionTy)
Add a lambda's conversion to function pointer, as described in C++11 [expr.prim.lambda]p6.
This file provides some common utility functions for processing Lambdas.
This file declares semantic analysis for OpenMP constructs and clauses.
This file declares semantic analysis for SYCL constructs.
a trap message and trap category.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
TranslationUnitDecl * getTranslationUnitDecl() const
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
DeclarationNameTable DeclarationNames
Definition ASTContext.h:856
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType DependentTy
IdentifierTable & Idents
Definition ASTContext.h:852
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod) const
Retrieves the default calling convention for the current context.
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
CanQualType VoidTy
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:971
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
CanQualType getCanonicalTagType(const TagDecl *TD) const
PtrTy get() const
Definition Ownership.h:171
Attr - This represents one attribute.
Definition Attr.h:47
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4107
A binding in a decomposition declaration.
Definition DeclCXX.h:4223
A class which contains all the information about a particular captured value.
Definition Decl.h:4862
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4856
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition Decl.cpp:5758
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6758
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
CXXBasePath & front()
bool isAmbiguous(CanQualType BaseType) const
Determine whether the path from the most-derived type to the given base type is ambiguous (i....
Represents a C++ conversion function within a class.
Definition DeclCXX.h:2985
static CXXConversionDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool UsesFPIntrin, bool isInline, ExplicitSpecifier ES, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:3283
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition DeclCXX.h:3021
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2153
bool isImplicitObjectMemberFunction() const
[C++2b][dcl.fct]/p7 An implicit object member function is a non-static member function without an exp...
Definition DeclCXX.cpp:2726
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool UsesFPIntrin, bool isInline, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation, const AssociatedConstraint &TrailingRequiresClause={})
Definition DeclCXX.cpp:2504
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2296
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
void setLambdaTypeInfo(TypeSourceInfo *TS)
Definition DeclCXX.h:1889
void setLambdaIsGeneric(bool IsGeneric)
Definition DeclCXX.h:1900
static CXXRecordDecl * CreateLambda(const ASTContext &C, DeclContext *DC, TypeSourceInfo *Info, SourceLocation Loc, unsigned DependencyKind, bool IsGeneric, LambdaCaptureDefault CaptureDefault)
Definition DeclCXX.cpp:142
bool isCapturelessLambda() const
Definition DeclCXX.h:1074
Represents a C++ nested-name-specifier or a global scope specifier.
Definition DeclSpec.h:77
ConditionalOperator - The ?
Definition Expr.h:4460
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition DeclBase.h:1467
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2108
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition DeclBase.h:2261
bool isRequiresExprBody() const
Definition DeclBase.h:2213
bool isFileContext() const
Definition DeclBase.h:2199
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition DeclBase.h:2124
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
bool isTranslationUnit() const
Definition DeclBase.h:2204
void addDecl(Decl *D)
Add the declaration D into this context.
bool isFunctionOrMethod() const
Returns true if this DeclContext is a function, Objective-C method, or block, or a DeclContext that c...
Definition DeclBase.h:2163
DeclContext * getEnclosingNonExpansionStatementContext()
Retrieve the innermost enclosing context that doesn't belong to an expansion statement.
Simple template class for restricting typo correction candidates to ones having a single Decl* of the...
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1315
Captures information about "declaration specifiers".
Definition DeclSpec.h:279
SCS getStorageClassSpec() const
Definition DeclSpec.h:552
bool SetTypeQual(TQ T, SourceLocation Loc)
ConstexprSpecKind getConstexprSpecifier() const
Definition DeclSpec.h:905
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition DeclBase.cpp:178
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition DeclBase.cpp:594
bool isInvalidDecl() const
Definition DeclBase.h:597
void setAccess(AccessSpecifier AS)
Definition DeclBase.h:511
SourceLocation getLocation() const
Definition DeclBase.h:448
void setImplicit(bool I=true)
Definition DeclBase.h:603
void setReferenced(bool R=true)
Definition DeclBase.h:632
DeclContext * getDeclContext()
Definition DeclBase.h:457
bool hasAttr() const
Definition DeclBase.h:586
void setLexicalDeclContext(DeclContext *DC)
Definition DeclBase.cpp:389
DeclarationNameLoc - Additional source/type location info for a declaration name.
static DeclarationNameLoc makeNamedTypeLoc(TypeSourceInfo *TInfo)
Construct location information for a constructor, destructor or conversion operator.
static DeclarationNameLoc makeCXXOperatorNameLoc(SourceLocation BeginLoc, SourceLocation EndLoc)
Construct location information for a non-literal C++ operator.
DeclarationName getCXXConversionFunctionName(CanQualType Ty)
Returns the name of a C++ conversion function for the given Type.
The name of a declaration.
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Decl.h:833
const AssociatedConstraint & getTrailingRequiresClause() const
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition Decl.h:857
void setTrailingRequiresClause(const AssociatedConstraint &AC)
Definition Decl.cpp:2036
TypeSourceInfo * getTypeSourceInfo() const
Definition Decl.h:811
Information about one declarator, including the parsed type information and the identifier.
Definition DeclSpec.h:1996
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition DeclSpec.h:2559
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition DeclSpec.h:2501
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition DeclSpec.h:2146
Expr * getTrailingRequiresClause()
Sets a trailing requires clause for this declarator.
Definition DeclSpec.h:2736
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition DeclSpec.h:2497
bool isExplicitObjectMemberFunction()
Definition DeclSpec.cpp:400
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition DeclSpec.h:2181
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition DeclSpec.h:2590
An instance of this object exists for each enum constant that is defined.
Definition Decl.h:3604
Represents an enum.
Definition Decl.h:4192
Store information needed for an explicit specifier.
Definition DeclCXX.h:1949
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition ExprCXX.h:3715
This represents one expression.
Definition Expr.h:114
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3125
QualType getType() const
Definition Expr.h:146
Represents difference between two FPOptions values.
bool isFPConstrained() const
Represents a member of a struct/union/class.
Definition Decl.h:3341
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
Definition Decl.cpp:4802
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition Diagnostic.h:129
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
void setSubExpr(Expr *E)
As with any mutator of the AST, be very careful when modifying an existing AST to preserve its invari...
Definition Expr.h:1112
const Expr * getSubExpr() const
Definition Expr.h:1107
Represents a function declaration or definition.
Definition Decl.h:2082
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2974
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3284
ConstexprSpecKind getConstexprKind() const
Definition Decl.h:2645
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition Decl.cpp:4273
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4268
QualType getReturnType() const
Definition Decl.h:3022
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2947
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition Decl.cpp:4388
bool isVariadic() const
Whether this function is variadic.
Definition Decl.cpp:3137
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition Decl.cpp:4219
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2639
FunctionDecl * getInstantiatedFromDecl() const
Definition Decl.cpp:4292
void setConstexprKind(ConstexprSpecKind CSK)
Definition Decl.h:2642
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition Decl.cpp:4240
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3899
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition Decl.h:2982
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5548
bool isVariadic() const
Whether this function prototype is variadic.
Definition TypeBase.h:5952
ExtProtoInfo getExtProtoInfo() const
Definition TypeBase.h:5837
ArrayRef< QualType > getParamTypes() const
Definition TypeBase.h:5833
Declaration of a template function.
FunctionDecl * getTemplatedDecl() const
Get the underlying function declaration of the template.
FunctionTemplateDecl * getInstantiatedFromMemberTemplate() const
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
TypeLoc getReturnLoc() const
Definition TypeLoc.h:1756
ExtInfo withCallingConv(CallingConv cc) const
Definition TypeBase.h:4967
CallingConv getCallConv() const
Definition TypeBase.h:5099
QualType getReturnType() const
Definition TypeBase.h:5084
One of these records is kept for each identifier that is lexed.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
Definition Expr.h:3922
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition Expr.cpp:2109
Describes the kind of initialization being performed, along with location information for tokens rela...
static InitializationKind CreateDirect(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a direct initialization.
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
static InitializationKind CreateDirectList(SourceLocation InitLoc)
ExprResult Perform(Sema &S, const InitializedEntity &Entity, const InitializationKind &Kind, MultiExprArg Args, QualType *ResultType=nullptr)
Perform the actual initialization of the given entity based on the computed initialization sequence.
Describes an entity that is being initialized.
static InitializedEntity InitializeLambdaToBlock(SourceLocation BlockVarLoc, QualType Type)
static InitializedEntity InitializeLambdaCapture(IdentifierInfo *VarID, QualType FieldType, SourceLocation Loc)
Create the initialization entity for a lambda capture.
Describes the capture of a variable or of this, or of a C++1y init-capture.
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition ExprCXX.h:1973
static LambdaExpr * Create(const ASTContext &C, CXXRecordDecl *Class, SourceRange IntroducerRange, LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc, bool ExplicitParams, bool ExplicitResultType, ArrayRef< Expr * > CaptureInits, SourceLocation ClosingBrace, bool ContainsUnexpandedParameterPack)
Construct a new lambda expression.
Definition ExprCXX.cpp:1344
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition Template.h:377
void InstantiatedLocal(const Decl *D, Decl *Inst)
Represents the results of name lookup.
Definition Lookup.h:147
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
virtual unsigned getManglingNumber(const CXXMethodDecl *CallOperator)=0
Retrieve the mangling number of a new lambda expression with the given call operator within this cont...
virtual unsigned getDeviceManglingNumber(const CXXMethodDecl *)
Retrieve the mangling number of a new lambda expression with the given call operator within the devic...
Data structure that captures multiple levels of template argument lists for use in template instantia...
Definition Template.h:76
This represents a decl that may have a name.
Definition Decl.h:276
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:297
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition Decl.cpp:1097
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:342
PtrTy get() const
Definition Ownership.h:81
Expr ** getExprs()
Definition Expr.h:6207
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition Expr.h:6196
Represents a parameter to a function.
Definition Decl.h:1832
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Definition Decl.cpp:2963
Wrapper for source info for pointers.
Definition TypeLoc.h:1544
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8704
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8763
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8672
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
void addAddressSpace(LangAS space)
Definition TypeBase.h:598
Represents a struct/union/class.
Definition Decl.h:4506
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3173
void setRetValue(Expr *E)
Definition Stmt.h:3202
SourceLocation getBeginLoc() const
Definition Stmt.h:3225
Expr * getRetValue()
Definition Stmt.h:3200
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
DeclContext * getEntity() const
Get the entity corresponding to this scope.
Definition Scope.h:387
decl_range decls() const
Definition Scope.h:342
bool isFunctionDeclarationScope() const
isFunctionDeclarationScope - Return true if this scope is a function prototype scope.
Definition Scope.h:479
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition Scope.h:280
void CheckSMEFunctionDefAttributes(const FunctionDecl *FD)
Definition SemaARM.cpp:1640
Sema & SemaRef
Definition SemaBase.h:40
SemaDiagnosticBuilder DiagCompat(SourceLocation Loc, unsigned CompatDiagId)
Emit a compatibility diagnostic.
Definition SemaBase.cpp:98
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID)
Emit a diagnostic.
Definition SemaBase.cpp:61
void CheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture)
void SetLambdaAttrs(CXXMethodDecl *Method)
Set device or host device attributes on the given lambda operator() method.
void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D)
Act on D, a function definition inside of an omp [begin/end] assumes.
void CheckSYCLEntryPointFunctionDecl(FunctionDecl *FD)
Definition SemaSYCL.cpp:310
A RAII object to temporarily push a declaration context.
Definition Sema.h:3639
LambdaScopeForCallOperatorInstantiationRAII(Sema &SemasRef, FunctionDecl *FD, MultiLevelTemplateArgumentList MLTAL, LocalInstantiationScope &Scope, bool ShouldAddDeclsFromParentScope=true)
Sema - This implements semantic analysis and AST building for C.
Definition Sema.h:862
Attr * getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition)
Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a containing class.
QualType getCurrentThisType()
Try to retrieve the type of the 'this' pointer.
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src)
Scope * getCurScope() const
Retrieve the parser's current scope.
Definition Sema.h:1164
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath)
bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition Sema.h:8428
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition Sema.h:9529
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init)
VarDecl * createLambdaInitCaptureVarDecl(SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc, IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx)
Create a dummy variable within the declcontext of the lambda's call operator, for name lookup purpose...
ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body)
ActOnLambdaExpr - This is called when the body of a lambda expression was successfully completed.
SemaOpenMP & OpenMP()
Definition Sema.h:1558
CXXRecordDecl * createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info, unsigned LambdaDependencyKind, LambdaCaptureDefault CaptureDefault)
Create a new lambda closure type.
SemaCUDA & CUDA()
Definition Sema.h:1498
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition Sema.h:1267
bool CheckCXXThisCapture(SourceLocation Loc, bool Explicit=false, bool BuildAndDiagnose=true, const unsigned *const FunctionScopeIndexToStopAt=nullptr, bool ByCopy=false)
Make sure the value of 'this' is actually available in the current context, if it is a potentially ev...
void ActOnLambdaExpressionAfterIntroducer(LambdaIntroducer &Intro, Scope *CurContext)
Once the Lambdas capture are known, we can start to create the closure, call operator method,...
void AddTemplateParametersToLambdaCallOperator(CXXMethodDecl *CallOperator, CXXRecordDecl *Class, TemplateParameterList *TemplateParams)
ExprResult MaybeBindToTemporary(Expr *E)
MaybeBindToTemporary - If the passed in expression has a record type with a non-trivial destructor,...
void AddRangeBasedOptnone(FunctionDecl *FD)
Only called on function definitions; if there is a pragma in scope with the effect of a range-based o...
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body, bool IsInstantiation=false, bool RetainFunctionScopeInfo=false)
Performs semantic analysis at the end of a function body.
void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef)
Add an init-capture to a lambda scope.
SemaSYCL & SYCL()
Definition Sema.h:1583
ASTContext & Context
Definition Sema.h:1331
bool DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReceiver=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition SemaExpr.cpp:229
SemaObjC & ObjC()
Definition Sema.h:1543
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
ASTContext & getASTContext() const
Definition Sema.h:934
std::unique_ptr< sema::FunctionScopeInfo, PoppedFunctionScopeDeleter > PoppedFunctionScopePtr
Definition Sema.h:1076
bool tryCaptureVariable(ValueDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt)
Try to capture the given variable.
void PopExpressionEvaluationContext()
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths)
Builds a string representing ambiguous paths from a specific derived class to different subobjects of...
FieldDecl * BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture, bool IsOpenMP=false)
Build a FieldDecl suitable to hold the given capture.
void handleLambdaNumbering(CXXRecordDecl *Class, CXXMethodDecl *Method, std::optional< CXXRecordDecl::LambdaNumbering > NumberingOverride=std::nullopt)
Number lambda for linkage purposes if necessary.
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition Sema.cpp:1798
ExprResult BuildCaptureInit(const sema::Capture &Capture, SourceLocation ImplicitCaptureLoc, bool IsOpenMPMapping=false)
Initialize the given capture with a suitable expression.
void addImplicitCallingConvAbiTag(FunctionDecl *FD)
Attach the ABI tag a standard calling convention variant requires, as an implicit abi_tag attribute.
FPOptions & getCurFPFeatures()
Definition Sema.h:929
Sema(Preprocessor &pp, ASTContext &ctxt, ASTConsumer &consumer, TranslationUnitKind TUKind=TU_Complete, CodeCompleteConsumer *CompletionConsumer=nullptr)
Definition Sema.cpp:278
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition Sema.cpp:84
@ UPPC_Initializer
An initializer.
Definition Sema.h:14722
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition Sema.h:14695
void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator, SourceRange IntroducerRange, LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc, bool ExplicitParams, bool Mutable)
Endow the lambda scope info with the relevant properties.
const LangOptions & getLangOpts() const
Definition Sema.h:927
bool CaptureHasSideEffects(const sema::Capture &From)
Does copying/destroying the captured variable have side effects?
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition Sema.cpp:2624
void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, Declarator &ParamInfo, const DeclSpec &DS)
ActOnStartOfLambdaDefinition - This is called just before we start parsing the body of a lambda; it a...
void ActOnLambdaClosureParameters(Scope *LambdaScope, MutableArrayRef< DeclaratorChunk::ParamInfo > ParamInfo)
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args={}, DeclContext *LookupCtx=nullptr)
Diagnose an empty lookup.
bool CheckConstexprFunctionDefinition(const FunctionDecl *FD, CheckConstexprKind Kind)
AccessResult CheckBaseClassAccess(SourceLocation AccessLoc, QualType Base, QualType Derived, const CXXBasePath &Path, unsigned DiagID, bool ForceCheck=false, bool ForceUnprivileged=false)
Checks access for a hierarchy conversion.
bool DiagnoseUnexpandedParameterPack(SourceLocation Loc, TypeSourceInfo *T, UnexpandedParameterPackContext UPPC)
If the given type contains an unexpanded parameter pack, diagnose the error.
const LangOptions & LangOpts
Definition Sema.h:1329
void PushExpressionEvaluationContextForFunction(ExpressionEvaluationContext NewContext, FunctionDecl *FD)
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition Sema.cpp:2739
void CompleteLambdaCallOperator(CXXMethodDecl *Method, SourceLocation LambdaLoc, SourceLocation CallOperatorLoc, const AssociatedConstraint &TrailingRequiresClause, TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind, StorageClass SC, ArrayRef< ParmVarDecl * > Params, bool HasExplicitResultType)
void maybeAddDeclWithEffects(FuncOrBlockDecl *D)
Inline checks from the start of maybeAddDeclWithEffects, to minimize performance impact on code not u...
Definition Sema.h:16024
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition Sema.h:7140
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
Expr * BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit)
Build a CXXThisExpr and mark it referenced in the current context.
QualType BuildReferenceType(QualType T, bool LValueRef, SourceLocation Loc, DeclarationName Entity)
Build a reference type.
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
void DiagPlaceholderVariableDefinition(SourceLocation Loc)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition Sema.h:1471
bool IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived, CXXRecordDecl *Base, CXXBasePaths &Paths)
Determine whether the type Derived is a C++ class that is derived from the type Base.
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition Sema.h:14241
void ActOnLambdaExplicitTemplateParameterList(LambdaIntroducer &Intro, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > TParams, SourceLocation RAngleLoc, ExprResult RequiresClause)
This is called after parsing the explicit template parameter list on a lambda (if it exists) in C++2a...
void ActOnLambdaClosureQualifiers(LambdaIntroducer &Intro, SourceLocation MutableLoc)
void ActOnLambdaError(SourceLocation StartLoc, Scope *CurScope, bool IsInstantiation=false)
ActOnLambdaError - If there is an error parsing a lambda, this callback is invoked to pop the informa...
bool CheckParmsForFunctionDef(ArrayRef< ParmVarDecl * > Parameters, bool CheckParameterNames)
CheckParmsForFunctionDef - Check that the parameters of the given function are appropriate for the de...
void CheckShadow(NamedDecl *D, NamedDecl *ShadowedDecl, const LookupResult &R)
Diagnose variable or built-in function shadowing.
bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, SourceRange FixItRange, const sema::Capture &From)
Diagnose if an explicit lambda capture is unused.
QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, UnsignedOrNone NumExpansions, IdentifierInfo *Id, bool DirectInit, Expr *&Init)
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition Sema.h:7144
sema::AnalysisBasedWarnings AnalysisWarnings
Worker object for performing CFG-based warnings.
Definition Sema.h:1371
@ UnevaluatedAbstract
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
Definition Sema.h:6900
@ UnevaluatedList
The current expression occurs within a braced-init-list within an unevaluated operand.
Definition Sema.h:6890
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
Definition Sema.h:6905
@ DiscardedStatement
The current expression occurs within a discarded statement.
Definition Sema.h:6895
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
Definition Sema.h:6915
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
Definition Sema.h:6884
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
Definition Sema.h:6910
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
Definition Sema.h:6925
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
void CheckExplicitObjectLambda(Declarator &D)
QualType getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType, CallingConv CC)
Get the return type to use for a lambda's conversion function(s) to function pointer type,...
void CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record)
Perform semantic checks on a class definition that has been completing, introducing implicitly-declar...
void DiscardCleanupsInEvaluationContext()
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition Sema.h:8501
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
void makeMergedDefinitionVisible(NamedDecl *ND)
Make a merged definition of an existing hidden definition ND visible at the specified location.
CXXMethodDecl * CreateLambdaCallOperator(SourceRange IntroducerRange, CXXRecordDecl *Class)
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI)
Deduce a block or lambda's return type based on the return statements present in the body.
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
friend class InitializationSequence
Definition Sema.h:1613
void PopDeclContext()
ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc)
Complete a lambda-expression having processed and attached the lambda body.
void ProcessDeclAttributes(Scope *S, Decl *D, const Declarator &PD)
ProcessDeclAttributes - Given a declarator (PD) with attributes indicated in it, apply them to D.
QualType SubstAutoTypeDependent(QualType TypeWithAuto)
SourceRange getRangeForNextToken(SourceLocation Loc, bool IncludeMacros, bool IncludeComments, std::optional< tok::TokenKind > ExpectedToken=std::nullopt)
Calls Lexer::findNextToken() to find the next token, and if the locations of both ends of the token c...
Definition Sema.cpp:89
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI)
Note that we have finished the explicit captures for the given lambda.
@ CheckValid
Identify whether this function satisfies the formal rules for constexpr functions in the current lanu...
Definition Sema.h:6588
bool DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method, SourceLocation CallLoc)
Returns true if the explicit object parameter was invalid.
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
UnsignedOrNone getNumArgumentsInExpansionFromUnexpanded(llvm::ArrayRef< UnexpandedParameterPack > Unexpanded, const MultiLevelTemplateArgumentList &TemplateArgs)
void NoteTemplateParameterLocation(const NamedDecl &Decl)
SemaARM & ARM()
Definition Sema.h:1478
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition Sema.h:8845
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
SourceLocation getLocWithOffset(IntTy Offset) const
Return a source location with the specified offset from this SourceLocation.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition Expr.h:4664
Stmt - This represents one statement.
Definition Stmt.h:85
SourceLocation getEndLoc() const LLVM_READONLY
Definition Stmt.cpp:367
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition Decl.h:4131
Exposes information about the current target.
Definition TargetInfo.h:228
virtual CallingConvCheckResult checkCallingConvention(CallingConv CC) const
Determines whether a given calling convention is valid for the target.
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Stores a list of template parameters for a TemplateDecl and its derived classes.
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl * > Params, SourceLocation RAngleLoc, Expr *RequiresClause)
bool containsUnexpandedParameterPack() const
Determine whether this template parameter list contains an unexpanded parameter pack.
ArrayRef< NamedDecl * > asArray()
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
Base wrapper for a particular "section" of type source info.
Definition TypeLoc.h:59
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
Definition TypeLoc.h:89
A container of type source information.
Definition TypeBase.h:8549
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition TypeLoc.h:267
QualType getType() const
Return the type wrapped by this type source info.
Definition TypeBase.h:8560
void setNameLoc(SourceLocation Loc)
Definition TypeLoc.h:551
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isVoidType() const
Definition TypeBase.h:9200
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition Type.cpp:2299
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9498
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2863
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition TypeBase.h:2469
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition TypeBase.h:9347
EnumDecl * getAsEnumDecl() const
Retrieves the EnumDecl this type refers to.
Definition Type.h:53
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition Type.cpp:2655
NullabilityKindOrNone getNullability() const
Determine the nullability of the given type.
Definition Type.cpp:5325
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
QualType getType() const
Definition Decl.h:725
bool isParameterPack() const
Determine whether this value is actually a function parameter pack, init-capture pack,...
Definition Decl.cpp:5701
VarDecl * getPotentiallyDecomposedVarDecl()
Definition DeclCXX.cpp:3695
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.cpp:5695
Represents a variable declaration or definition.
Definition Decl.h:934
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition Decl.cpp:2132
void setInitStyle(InitializationStyle Style)
Definition Decl.h:1489
void setInitCapture(bool IC)
Definition Decl.h:1618
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1615
InitializationStyle
Initialization styles.
Definition Decl.h:937
@ ListInit
Direct list-initialization (C++11)
Definition Decl.h:945
@ CInit
C-style initialization with assignment.
Definition Decl.h:939
@ CallInit
Call-style initialization (C++98)
Definition Decl.h:942
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1192
void setInit(Expr *I)
Definition Decl.cpp:2470
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:1176
ValueDecl * getVariable() const
Definition ScopeInfo.h:676
bool isVariableCapture() const
Definition ScopeInfo.h:651
bool isBlockCapture() const
Definition ScopeInfo.h:657
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition ScopeInfo.h:687
bool isNonODRUsed() const
Definition ScopeInfo.h:668
bool isODRUsed() const
Definition ScopeInfo.h:667
bool isInitCapture() const
Determine whether this capture is an init-capture.
bool isInvalid() const
Definition ScopeInfo.h:662
bool isVLATypeCapture() const
Definition ScopeInfo.h:658
SourceLocation getEllipsisLoc() const
Retrieve the source location of the ellipsis, whose presence indicates that the capture is a pack exp...
Definition ScopeInfo.h:691
bool isThisCapture() const
Definition ScopeInfo.h:650
QualType getCaptureType() const
Retrieve the capture type for this capture, which is effectively the type of the non-static data memb...
Definition ScopeInfo.h:696
bool isCopyCapture() const
Definition ScopeInfo.h:655
bool isReferenceCapture() const
Definition ScopeInfo.h:656
const VariableArrayType * getCapturedVLAType() const
Definition ScopeInfo.h:681
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition ScopeInfo.h:733
bool isCaptured(ValueDecl *Var) const
Determine whether the given variable has been captured.
Definition ScopeInfo.h:765
bool ContainsUnexpandedParameterPack
Whether this contains an unexpanded parameter pack.
Definition ScopeInfo.h:729
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition ScopeInfo.h:722
ImplicitCaptureStyle ImpCaptureStyle
Definition ScopeInfo.h:709
Capture & getCXXThisCapture()
Retrieve the capture of C++ 'this', if it has been captured.
Definition ScopeInfo.h:759
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition ScopeInfo.h:756
SmallVector< NamedDecl *, 4 > LocalPacks
Packs introduced by this, if any.
Definition ScopeInfo.h:736
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition ScopeInfo.h:738
SmallVector< ReturnStmt *, 4 > Returns
The list of return statements that occur within the function or block, if there is any chance of appl...
Definition ScopeInfo.h:219
SourceLocation PotentialThisCaptureLocation
Definition ScopeInfo.h:953
void finishedExplicitCaptures()
Note when all explicit captures have been added.
Definition ScopeInfo.h:964
CleanupInfo Cleanup
Whether any of the capture expressions requires cleanups.
Definition ScopeInfo.h:905
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition ScopeInfo.h:887
bool ExplicitParams
Whether the (empty) parameter list is explicit.
Definition ScopeInfo.h:902
TemplateParameterList * GLTemplateParameterList
If this is a generic lambda, and the template parameter list has been created (from the TemplateParam...
Definition ScopeInfo.h:918
ExprResult RequiresClause
The requires-clause immediately following the explicit template parameter list, if any.
Definition ScopeInfo.h:913
SourceRange ExplicitTemplateParamsRange
Source range covering the explicit template parameter list (if it exists).
Definition ScopeInfo.h:908
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition ScopeInfo.h:872
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
Definition ScopeInfo.h:895
SourceLocation CaptureDefaultLoc
Source location of the '&' or '=' specifying the default capture type, if any.
Definition ScopeInfo.h:891
llvm::DenseMap< unsigned, SourceRange > ExplicitCaptureRanges
A map of explicit capture indices to their introducer source ranges.
Definition ScopeInfo.h:942
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition ScopeInfo.h:880
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition ScopeInfo.h:875
bool Mutable
Whether this is a mutable lambda.
Definition ScopeInfo.h:899
Defines the clang::TargetInfo interface.
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus14
@ CPlusPlus17
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition ASTLambda.h:102
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition Specifiers.h:36
TryCaptureKind
Definition Sema.h:646
@ ICIS_NoInit
No in-class initializer.
Definition Specifiers.h:276
@ RQ_None
No ref-qualifier was provided.
Definition TypeBase.h:1801
UnsignedOrNone getStackIndexOfNearestEnclosingCaptureCapableLambda(ArrayRef< const sema::FunctionScopeInfo * > FunctionScopes, ValueDecl *VarToCapture, Sema &S)
Examines the FunctionScopeInfo stack to determine the nearest enclosing lambda (to the current lambda...
LambdaCaptureKind
The different capture forms in a lambda introducer.
Definition Lambda.h:33
@ LCK_ByCopy
Capturing by copy (a.k.a., by value)
Definition Lambda.h:36
@ LCK_ByRef
Capturing by reference.
Definition Lambda.h:37
@ LCK_VLAType
Capturing variable-length array type.
Definition Lambda.h:38
@ LCK_StarThis
Capturing the *this object by copy.
Definition Lambda.h:35
@ LCK_This
Capturing the *this object by reference.
Definition Lambda.h:34
@ AS_public
Definition Specifiers.h:128
@ AS_private
Definition Specifiers.h:130
bool isLambdaCallWithExplicitObjectParameter(const DeclContext *DC)
Definition ASTLambda.h:45
StorageClass
Storage classes.
Definition Specifiers.h:252
@ SC_Auto
Definition Specifiers.h:260
@ SC_Static
Definition Specifiers.h:256
@ SC_None
Definition Specifiers.h:254
bool FTIHasSingleVoidParameter(const DeclaratorChunk::FunctionTypeInfo &FTI)
MutableArrayRef< Expr * > MultiExprArg
Definition Ownership.h:259
@ CopyInit
[a = b], [a = {b}]
Definition DeclSpec.h:2934
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Result
The result type of a method or function.
Definition TypeBase.h:906
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
bool hasWeakerNullability(NullabilityKind L, NullabilityKind R)
Return true if L has a weaker nullability annotation than R.
Definition Specifiers.h:373
ExprResult ExprError()
Definition Ownership.h:265
LangAS
Defines the address space values used by the address space qualifier of QualType.
LambdaCaptureDefault
The default, if any, capture method for a lambda expression.
Definition Lambda.h:22
@ LCD_ByRef
Definition Lambda.h:25
@ LCD_None
Definition Lambda.h:23
@ LCD_ByCopy
Definition Lambda.h:24
@ VK_PRValue
A pr-value expression (in the C++11 taxonomy) produces a temporary value.
Definition Specifiers.h:139
StringRef getLambdaStaticInvokerName()
Definition ASTLambda.h:23
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:147
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition Specifiers.h:282
@ CC_X86VectorCall
Definition Specifiers.h:287
@ CC_X86StdCall
Definition Specifiers.h:284
@ CC_X86FastCall
Definition Specifiers.h:285
U cast(CodeGen::Address addr)
Definition Address.h:327
@ Class
The "class" keyword introduces the elaborated-type-specifier.
Definition TypeBase.h:6157
ActionResult< Expr * > ExprResult
Definition Ownership.h:249
@ EST_BasicNoexcept
noexcept
Information about how a lambda is numbered within its context.
Definition DeclCXX.h:1823
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspon...
SourceLocation getTrailingReturnTypeLoc() const
Get the trailing-return-type location for this function declarator.
Definition DeclSpec.h:1683
bool hasTrailingReturnType() const
Determine whether this function declarator had a trailing-return-type.
Definition DeclSpec.h:1674
ParsedType getTrailingReturnType() const
Get the trailing-return-type for this function declarator.
Definition DeclSpec.h:1677
bool hasMutableQualifier() const
Determine whether this lambda-declarator contains a 'mutable' qualifier.
Definition DeclSpec.h:1646
ParamInfo - An array of paraminfo objects is allocated whenever a function declarator is parsed.
Definition DeclSpec.h:1421
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition TypeBase.h:5607
Extra information about a function prototype.
Definition TypeBase.h:5633
unsigned NumExplicitTemplateParams
The number of parameters in the template parameter list that were explicitly specified by the user,...
Definition DeclSpec.h:2991
SmallVector< NamedDecl *, 4 > TemplateParams
Store the list of the template parameters for a generic lambda or an abbreviated function template.
Definition DeclSpec.h:3004
Represents a complete lambda introducer.
Definition DeclSpec.h:2940
SmallVector< LambdaCapture, 4 > Captures
Definition DeclSpec.h:2965
SourceLocation DefaultLoc
Definition DeclSpec.h:2963
LambdaCaptureDefault Default
Definition DeclSpec.h:2964