clang 20.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/SemaCUDA.h"
27#include "clang/Sema/Template.h"
28#include "llvm/ADT/STLExtras.h"
29#include <optional>
30using namespace clang;
31using namespace sema;
32
33/// Examines the FunctionScopeInfo stack to determine the nearest
34/// enclosing lambda (to the current lambda) that is 'capture-ready' for
35/// the variable referenced in the current lambda (i.e. \p VarToCapture).
36/// If successful, returns the index into Sema's FunctionScopeInfo stack
37/// of the capture-ready lambda's LambdaScopeInfo.
38///
39/// Climbs down the stack of lambdas (deepest nested lambda - i.e. current
40/// lambda - is on top) to determine the index of the nearest enclosing/outer
41/// lambda that is ready to capture the \p VarToCapture being referenced in
42/// the current lambda.
43/// As we climb down the stack, we want the index of the first such lambda -
44/// that is the lambda with the highest index that is 'capture-ready'.
45///
46/// A lambda 'L' is capture-ready for 'V' (var or this) if:
47/// - its enclosing context is non-dependent
48/// - and if the chain of lambdas between L and the lambda in which
49/// V is potentially used (i.e. the lambda at the top of the scope info
50/// stack), can all capture or have already captured V.
51/// If \p VarToCapture is 'null' then we are trying to capture 'this'.
52///
53/// Note that a lambda that is deemed 'capture-ready' still needs to be checked
54/// for whether it is 'capture-capable' (see
55/// getStackIndexOfNearestEnclosingCaptureCapableLambda), before it can truly
56/// capture.
57///
58/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
59/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
60/// is at the top of the stack and has the highest index.
61/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
62///
63/// \returns An std::optional<unsigned> Index that if evaluates to 'true'
64/// contains the index (into Sema's FunctionScopeInfo stack) of the innermost
65/// lambda which is capture-ready. If the return value evaluates to 'false'
66/// then no lambda is capture-ready for \p VarToCapture.
67
68static inline std::optional<unsigned>
71 ValueDecl *VarToCapture) {
72 // Label failure to capture.
73 const std::optional<unsigned> NoLambdaIsCaptureReady;
74
75 // Ignore all inner captured regions.
76 unsigned CurScopeIndex = FunctionScopes.size() - 1;
77 while (CurScopeIndex > 0 && isa<clang::sema::CapturedRegionScopeInfo>(
78 FunctionScopes[CurScopeIndex]))
79 --CurScopeIndex;
80 assert(
81 isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) &&
82 "The function on the top of sema's function-info stack must be a lambda");
83
84 // If VarToCapture is null, we are attempting to capture 'this'.
85 const bool IsCapturingThis = !VarToCapture;
86 const bool IsCapturingVariable = !IsCapturingThis;
87
88 // Start with the current lambda at the top of the stack (highest index).
89 DeclContext *EnclosingDC =
90 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator;
91
92 do {
94 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]);
95 // IF we have climbed down to an intervening enclosing lambda that contains
96 // the variable declaration - it obviously can/must not capture the
97 // variable.
98 // Since its enclosing DC is dependent, all the lambdas between it and the
99 // innermost nested lambda are dependent (otherwise we wouldn't have
100 // arrived here) - so we don't yet have a lambda that can capture the
101 // variable.
102 if (IsCapturingVariable &&
103 VarToCapture->getDeclContext()->Equals(EnclosingDC))
104 return NoLambdaIsCaptureReady;
105
106 // For an enclosing lambda to be capture ready for an entity, all
107 // intervening lambda's have to be able to capture that entity. If even
108 // one of the intervening lambda's is not capable of capturing the entity
109 // then no enclosing lambda can ever capture that entity.
110 // For e.g.
111 // const int x = 10;
112 // [=](auto a) { #1
113 // [](auto b) { #2 <-- an intervening lambda that can never capture 'x'
114 // [=](auto c) { #3
115 // f(x, c); <-- can not lead to x's speculative capture by #1 or #2
116 // }; }; };
117 // If they do not have a default implicit capture, check to see
118 // if the entity has already been explicitly captured.
119 // If even a single dependent enclosing lambda lacks the capability
120 // to ever capture this variable, there is no further enclosing
121 // non-dependent lambda that can capture this variable.
122 if (LSI->ImpCaptureStyle == sema::LambdaScopeInfo::ImpCap_None) {
123 if (IsCapturingVariable && !LSI->isCaptured(VarToCapture))
124 return NoLambdaIsCaptureReady;
125 if (IsCapturingThis && !LSI->isCXXThisCaptured())
126 return NoLambdaIsCaptureReady;
127 }
128 EnclosingDC = getLambdaAwareParentOfDeclContext(EnclosingDC);
129
130 assert(CurScopeIndex);
131 --CurScopeIndex;
132 } while (!EnclosingDC->isTranslationUnit() &&
133 EnclosingDC->isDependentContext() &&
134 isLambdaCallOperator(EnclosingDC));
135
136 assert(CurScopeIndex < (FunctionScopes.size() - 1));
137 // If the enclosingDC is not dependent, then the immediately nested lambda
138 // (one index above) is capture-ready.
139 if (!EnclosingDC->isDependentContext())
140 return CurScopeIndex + 1;
141 return NoLambdaIsCaptureReady;
142}
143
144/// Examines the FunctionScopeInfo stack to determine the nearest
145/// enclosing lambda (to the current lambda) that is 'capture-capable' for
146/// the variable referenced in the current lambda (i.e. \p VarToCapture).
147/// If successful, returns the index into Sema's FunctionScopeInfo stack
148/// of the capture-capable lambda's LambdaScopeInfo.
149///
150/// Given the current stack of lambdas being processed by Sema and
151/// the variable of interest, to identify the nearest enclosing lambda (to the
152/// current lambda at the top of the stack) that can truly capture
153/// a variable, it has to have the following two properties:
154/// a) 'capture-ready' - be the innermost lambda that is 'capture-ready':
155/// - climb down the stack (i.e. starting from the innermost and examining
156/// each outer lambda step by step) checking if each enclosing
157/// lambda can either implicitly or explicitly capture the variable.
158/// Record the first such lambda that is enclosed in a non-dependent
159/// context. If no such lambda currently exists return failure.
160/// b) 'capture-capable' - make sure the 'capture-ready' lambda can truly
161/// capture the variable by checking all its enclosing lambdas:
162/// - check if all outer lambdas enclosing the 'capture-ready' lambda
163/// identified above in 'a' can also capture the variable (this is done
164/// via tryCaptureVariable for variables and CheckCXXThisCapture for
165/// 'this' by passing in the index of the Lambda identified in step 'a')
166///
167/// \param FunctionScopes - Sema's stack of nested FunctionScopeInfo's (which a
168/// LambdaScopeInfo inherits from). The current/deepest/innermost lambda
169/// is at the top of the stack.
170///
171/// \param VarToCapture - the variable to capture. If NULL, capture 'this'.
172///
173///
174/// \returns An std::optional<unsigned> Index that if evaluates to 'true'
175/// contains the index (into Sema's FunctionScopeInfo stack) of the innermost
176/// lambda which is capture-capable. If the return value evaluates to 'false'
177/// then no lambda is capture-capable for \p VarToCapture.
178
179std::optional<unsigned>
182 ValueDecl *VarToCapture, Sema &S) {
183
184 const std::optional<unsigned> NoLambdaIsCaptureCapable;
185
186 const std::optional<unsigned> OptionalStackIndex =
188 VarToCapture);
189 if (!OptionalStackIndex)
190 return NoLambdaIsCaptureCapable;
191
192 const unsigned IndexOfCaptureReadyLambda = *OptionalStackIndex;
193 assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) ||
194 S.getCurGenericLambda()) &&
195 "The capture ready lambda for a potential capture can only be the "
196 "current lambda if it is a generic lambda");
197
198 const sema::LambdaScopeInfo *const CaptureReadyLambdaLSI =
199 cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]);
200
201 // If VarToCapture is null, we are attempting to capture 'this'
202 const bool IsCapturingThis = !VarToCapture;
203 const bool IsCapturingVariable = !IsCapturingThis;
204
205 if (IsCapturingVariable) {
206 // Check if the capture-ready lambda can truly capture the variable, by
207 // checking whether all enclosing lambdas of the capture-ready lambda allow
208 // the capture - i.e. make sure it is capture-capable.
209 QualType CaptureType, DeclRefType;
210 const bool CanCaptureVariable =
211 !S.tryCaptureVariable(VarToCapture,
212 /*ExprVarIsUsedInLoc*/ SourceLocation(),
214 /*EllipsisLoc*/ SourceLocation(),
215 /*BuildAndDiagnose*/ false, CaptureType,
216 DeclRefType, &IndexOfCaptureReadyLambda);
217 if (!CanCaptureVariable)
218 return NoLambdaIsCaptureCapable;
219 } else {
220 // Check if the capture-ready lambda can truly capture 'this' by checking
221 // whether all enclosing lambdas of the capture-ready lambda can capture
222 // 'this'.
223 const bool CanCaptureThis =
225 CaptureReadyLambdaLSI->PotentialThisCaptureLocation,
226 /*Explicit*/ false, /*BuildAndDiagnose*/ false,
227 &IndexOfCaptureReadyLambda);
228 if (!CanCaptureThis)
229 return NoLambdaIsCaptureCapable;
230 }
231 return IndexOfCaptureReadyLambda;
232}
233
234static inline TemplateParameterList *
236 if (!LSI->GLTemplateParameterList && !LSI->TemplateParams.empty()) {
237 LSI->GLTemplateParameterList = TemplateParameterList::Create(
238 SemaRef.Context,
239 /*Template kw loc*/ SourceLocation(),
240 /*L angle loc*/ LSI->ExplicitTemplateParamsRange.getBegin(),
241 LSI->TemplateParams,
242 /*R angle loc*/LSI->ExplicitTemplateParamsRange.getEnd(),
243 LSI->RequiresClause.get());
244 }
245 return LSI->GLTemplateParameterList;
246}
247
250 unsigned LambdaDependencyKind,
251 LambdaCaptureDefault CaptureDefault) {
253 while (!(DC->isFunctionOrMethod() || DC->isRecord() || DC->isFileContext()))
254 DC = DC->getParent();
255
256 bool IsGenericLambda =
258 // Start constructing the lambda class.
260 Context, DC, Info, IntroducerRange.getBegin(), LambdaDependencyKind,
261 IsGenericLambda, CaptureDefault);
262 DC->addDecl(Class);
263
264 return Class;
265}
266
267/// Determine whether the given context is or is enclosed in an inline
268/// function.
269static bool isInInlineFunction(const DeclContext *DC) {
270 while (!DC->isFileContext()) {
271 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
272 if (FD->isInlined())
273 return true;
274
275 DC = DC->getLexicalParent();
276 }
277
278 return false;
279}
280
281std::tuple<MangleNumberingContext *, Decl *>
283 // Compute the context for allocating mangling numbers in the current
284 // expression, if the ABI requires them.
285 Decl *ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
286
287 enum ContextKind {
288 Normal,
290 DataMember,
291 InlineVariable,
292 TemplatedVariable,
293 Concept
294 } Kind = Normal;
295
296 bool IsInNonspecializedTemplate =
298
299 // Default arguments of member function parameters that appear in a class
300 // definition, as well as the initializers of data members, receive special
301 // treatment. Identify them.
302 if (ManglingContextDecl) {
303 if (ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
304 if (const DeclContext *LexicalDC
305 = Param->getDeclContext()->getLexicalParent())
306 if (LexicalDC->isRecord())
307 Kind = DefaultArgument;
308 } else if (VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
309 if (Var->getMostRecentDecl()->isInline())
310 Kind = InlineVariable;
311 else if (Var->getDeclContext()->isRecord() && IsInNonspecializedTemplate)
312 Kind = TemplatedVariable;
313 else if (Var->getDescribedVarTemplate())
314 Kind = TemplatedVariable;
315 else if (auto *VTS = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
316 if (!VTS->isExplicitSpecialization())
317 Kind = TemplatedVariable;
318 }
319 } else if (isa<FieldDecl>(ManglingContextDecl)) {
320 Kind = DataMember;
321 } else if (isa<ImplicitConceptSpecializationDecl>(ManglingContextDecl)) {
322 Kind = Concept;
323 }
324 }
325
326 // Itanium ABI [5.1.7]:
327 // In the following contexts [...] the one-definition rule requires closure
328 // types in different translation units to "correspond":
329 switch (Kind) {
330 case Normal: {
331 // -- the bodies of inline or templated functions
332 if ((IsInNonspecializedTemplate &&
333 !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
335 while (auto *CD = dyn_cast<CapturedDecl>(DC))
336 DC = CD->getParent();
337 return std::make_tuple(&Context.getManglingNumberContext(DC), nullptr);
338 }
339
340 return std::make_tuple(nullptr, nullptr);
341 }
342
343 case Concept:
344 // Concept definitions aren't code generated and thus aren't mangled,
345 // however the ManglingContextDecl is important for the purposes of
346 // re-forming the template argument list of the lambda for constraint
347 // evaluation.
348 case DataMember:
349 // -- default member initializers
350 case DefaultArgument:
351 // -- default arguments appearing in class definitions
352 case InlineVariable:
353 case TemplatedVariable:
354 // -- the initializers of inline or templated variables
355 return std::make_tuple(
357 ManglingContextDecl),
358 ManglingContextDecl);
359 }
360
361 llvm_unreachable("unexpected context");
362}
363
364static QualType
366 TemplateParameterList *TemplateParams,
367 TypeSourceInfo *MethodTypeInfo) {
368 assert(MethodTypeInfo && "expected a non null type");
369
370 QualType MethodType = MethodTypeInfo->getType();
371 // If a lambda appears in a dependent context or is a generic lambda (has
372 // template parameters) and has an 'auto' return type, deduce it to a
373 // dependent type.
374 if (Class->isDependentContext() || TemplateParams) {
375 const FunctionProtoType *FPT = MethodType->castAs<FunctionProtoType>();
377 if (Result->isUndeducedType()) {
379 MethodType = S.Context.getFunctionType(Result, FPT->getParamTypes(),
380 FPT->getExtProtoInfo());
381 }
382 }
383 return MethodType;
384}
385
386// [C++2b] [expr.prim.lambda.closure] p4
387// Given a lambda with a lambda-capture, the type of the explicit object
388// parameter, if any, of the lambda's function call operator (possibly
389// instantiated from a function call operator template) shall be either:
390// - the closure type,
391// - class type publicly and unambiguously derived from the closure type, or
392// - a reference to a possibly cv-qualified such type.
394 CXXMethodDecl *Method, SourceLocation CallLoc) {
396 return false;
397 CXXRecordDecl *RD = Method->getParent();
398 if (Method->getType()->isDependentType())
399 return false;
400 if (RD->isCapturelessLambda())
401 return false;
402
403 ParmVarDecl *Param = Method->getParamDecl(0);
404 QualType ExplicitObjectParameterType = Param->getType()
408 QualType LambdaType = getASTContext().getRecordType(RD);
409 if (LambdaType == ExplicitObjectParameterType)
410 return false;
411
412 // Don't check the same instantiation twice.
413 //
414 // If this call operator is ill-formed, there is no point in issuing
415 // a diagnostic every time it is called because the problem is in the
416 // definition of the derived type, not at the call site.
417 //
418 // FIXME: Move this check to where we instantiate the method? This should
419 // be possible, but the naive approach of just marking the method as invalid
420 // leads to us emitting more diagnostics than we should have to for this case
421 // (1 error here *and* 1 error about there being no matching overload at the
422 // call site). It might be possible to avoid that by also checking if there
423 // is an empty cast path for the method stored in the context (signalling that
424 // we've already diagnosed it) and then just not building the call, but that
425 // doesn't really seem any simpler than diagnosing it at the call site...
426 if (auto It = Context.LambdaCastPaths.find(Method);
427 It != Context.LambdaCastPaths.end())
428 return It->second.empty();
429
431 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
432 /*DetectVirtual=*/false);
433 if (!IsDerivedFrom(RD->getLocation(), ExplicitObjectParameterType, LambdaType,
434 Paths)) {
435 Diag(Param->getLocation(), diag::err_invalid_explicit_object_type_in_lambda)
436 << ExplicitObjectParameterType;
437 return true;
438 }
439
440 if (Paths.isAmbiguous(LambdaType->getCanonicalTypeUnqualified())) {
441 std::string PathsDisplay = getAmbiguousPathsDisplayString(Paths);
442 Diag(CallLoc, diag::err_explicit_object_lambda_ambiguous_base)
443 << LambdaType << PathsDisplay;
444 return true;
445 }
446
447 if (CheckBaseClassAccess(CallLoc, LambdaType, ExplicitObjectParameterType,
448 Paths.front(),
449 diag::err_explicit_object_lambda_inaccessible_base))
450 return true;
451
452 BuildBasePathArray(Paths, Path);
453 return false;
454}
455
458 std::optional<CXXRecordDecl::LambdaNumbering> NumberingOverride) {
459 if (NumberingOverride) {
460 Class->setLambdaNumbering(*NumberingOverride);
461 return;
462 }
463
464 ContextRAII ManglingContext(*this, Class->getDeclContext());
465
466 auto getMangleNumberingContext =
467 [this](CXXRecordDecl *Class,
468 Decl *ManglingContextDecl) -> MangleNumberingContext * {
469 // Get mangle numbering context if there's any extra decl context.
470 if (ManglingContextDecl)
472 ASTContext::NeedExtraManglingDecl, ManglingContextDecl);
473 // Otherwise, from that lambda's decl context.
474 auto DC = Class->getDeclContext();
475 while (auto *CD = dyn_cast<CapturedDecl>(DC))
476 DC = CD->getParent();
478 };
479
482 std::tie(MCtx, Numbering.ContextDecl) =
483 getCurrentMangleNumberContext(Class->getDeclContext());
484 if (!MCtx && (getLangOpts().CUDA || getLangOpts().SYCLIsDevice ||
485 getLangOpts().SYCLIsHost)) {
486 // Force lambda numbering in CUDA/HIP as we need to name lambdas following
487 // ODR. Both device- and host-compilation need to have a consistent naming
488 // on kernel functions. As lambdas are potential part of these `__global__`
489 // function names, they needs numbering following ODR.
490 // Also force for SYCL, since we need this for the
491 // __builtin_sycl_unique_stable_name implementation, which depends on lambda
492 // mangling.
493 MCtx = getMangleNumberingContext(Class, Numbering.ContextDecl);
494 assert(MCtx && "Retrieving mangle numbering context failed!");
495 Numbering.HasKnownInternalLinkage = true;
496 }
497 if (MCtx) {
498 Numbering.IndexInContext = MCtx->getNextLambdaIndex();
499 Numbering.ManglingNumber = MCtx->getManglingNumber(Method);
500 Numbering.DeviceManglingNumber = MCtx->getDeviceManglingNumber(Method);
501 Class->setLambdaNumbering(Numbering);
502
503 if (auto *Source =
504 dyn_cast_or_null<ExternalSemaSource>(Context.getExternalSource()))
505 Source->AssignedLambdaNumbering(Class);
506 }
507}
508
510 CXXMethodDecl *CallOperator,
511 bool ExplicitResultType) {
512 if (ExplicitResultType) {
513 LSI->HasImplicitReturnType = false;
514 LSI->ReturnType = CallOperator->getReturnType();
515 if (!LSI->ReturnType->isDependentType() && !LSI->ReturnType->isVoidType())
516 S.RequireCompleteType(CallOperator->getBeginLoc(), LSI->ReturnType,
517 diag::err_lambda_incomplete_result);
518 } else {
519 LSI->HasImplicitReturnType = true;
520 }
521}
522
524 SourceRange IntroducerRange,
525 LambdaCaptureDefault CaptureDefault,
526 SourceLocation CaptureDefaultLoc,
527 bool ExplicitParams, bool Mutable) {
528 LSI->CallOperator = CallOperator;
529 CXXRecordDecl *LambdaClass = CallOperator->getParent();
530 LSI->Lambda = LambdaClass;
531 if (CaptureDefault == LCD_ByCopy)
532 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
533 else if (CaptureDefault == LCD_ByRef)
534 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
535 LSI->CaptureDefaultLoc = CaptureDefaultLoc;
536 LSI->IntroducerRange = IntroducerRange;
537 LSI->ExplicitParams = ExplicitParams;
538 LSI->Mutable = Mutable;
539}
540
543}
544
546 LambdaIntroducer &Intro, SourceLocation LAngleLoc,
547 ArrayRef<NamedDecl *> TParams, SourceLocation RAngleLoc,
548 ExprResult RequiresClause) {
550 assert(LSI && "Expected a lambda scope");
551 assert(LSI->NumExplicitTemplateParams == 0 &&
552 "Already acted on explicit template parameters");
553 assert(LSI->TemplateParams.empty() &&
554 "Explicit template parameters should come "
555 "before invented (auto) ones");
556 assert(!TParams.empty() &&
557 "No template parameters to act on");
558 LSI->TemplateParams.append(TParams.begin(), TParams.end());
559 LSI->NumExplicitTemplateParams = TParams.size();
560 LSI->ExplicitTemplateParamsRange = {LAngleLoc, RAngleLoc};
561 LSI->RequiresClause = RequiresClause;
562}
563
564/// If this expression is an enumerator-like expression of some type
565/// T, return the type T; otherwise, return null.
566///
567/// Pointer comparisons on the result here should always work because
568/// it's derived from either the parent of an EnumConstantDecl
569/// (i.e. the definition) or the declaration returned by
570/// EnumType::getDecl() (i.e. the definition).
572 // An expression is an enumerator-like expression of type T if,
573 // ignoring parens and parens-like expressions:
574 E = E->IgnoreParens();
575
576 // - it is an enumerator whose enum type is T or
577 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
579 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
580 return cast<EnumDecl>(D->getDeclContext());
581 }
582 return nullptr;
583 }
584
585 // - it is a comma expression whose RHS is an enumerator-like
586 // expression of type T or
587 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
588 if (BO->getOpcode() == BO_Comma)
589 return findEnumForBlockReturn(BO->getRHS());
590 return nullptr;
591 }
592
593 // - it is a statement-expression whose value expression is an
594 // enumerator-like expression of type T or
595 if (StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
596 if (Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
597 return findEnumForBlockReturn(last);
598 return nullptr;
599 }
600
601 // - it is a ternary conditional operator (not the GNU ?:
602 // extension) whose second and third operands are
603 // enumerator-like expressions of type T or
604 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
605 if (EnumDecl *ED = findEnumForBlockReturn(CO->getTrueExpr()))
606 if (ED == findEnumForBlockReturn(CO->getFalseExpr()))
607 return ED;
608 return nullptr;
609 }
610
611 // (implicitly:)
612 // - it is an implicit integral conversion applied to an
613 // enumerator-like expression of type T or
614 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
615 // We can sometimes see integral conversions in valid
616 // enumerator-like expressions.
617 if (ICE->getCastKind() == CK_IntegralCast)
618 return findEnumForBlockReturn(ICE->getSubExpr());
619
620 // Otherwise, just rely on the type.
621 }
622
623 // - it is an expression of that formal enum type.
624 if (const EnumType *ET = E->getType()->getAs<EnumType>()) {
625 return ET->getDecl();
626 }
627
628 // Otherwise, nope.
629 return nullptr;
630}
631
632/// Attempt to find a type T for which the returned expression of the
633/// given statement is an enumerator-like expression of that type.
635 if (Expr *retValue = ret->getRetValue())
636 return findEnumForBlockReturn(retValue);
637 return nullptr;
638}
639
640/// Attempt to find a common type T for which all of the returned
641/// expressions in a block are enumerator-like expressions of that
642/// type.
644 ArrayRef<ReturnStmt*>::iterator i = returns.begin(), e = returns.end();
645
646 // Try to find one for the first return.
648 if (!ED) return nullptr;
649
650 // Check that the rest of the returns have the same enum.
651 for (++i; i != e; ++i) {
652 if (findEnumForBlockReturn(*i) != ED)
653 return nullptr;
654 }
655
656 // Never infer an anonymous enum type.
657 if (!ED->hasNameForLinkage()) return nullptr;
658
659 return ED;
660}
661
662/// Adjust the given return statements so that they formally return
663/// the given type. It should require, at most, an IntegralCast.
665 QualType returnType) {
667 i = returns.begin(), e = returns.end(); i != e; ++i) {
668 ReturnStmt *ret = *i;
669 Expr *retValue = ret->getRetValue();
670 if (S.Context.hasSameType(retValue->getType(), returnType))
671 continue;
672
673 // Right now we only support integral fixup casts.
674 assert(returnType->isIntegralOrUnscopedEnumerationType());
675 assert(retValue->getType()->isIntegralOrUnscopedEnumerationType());
676
677 ExprWithCleanups *cleanups = dyn_cast<ExprWithCleanups>(retValue);
678
679 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
680 E = ImplicitCastExpr::Create(S.Context, returnType, CK_IntegralCast, E,
681 /*base path*/ nullptr, VK_PRValue,
683 if (cleanups) {
684 cleanups->setSubExpr(E);
685 } else {
686 ret->setRetValue(E);
687 }
688 }
689}
690
692 assert(CSI.HasImplicitReturnType);
693 // If it was ever a placeholder, it had to been deduced to DependentTy.
694 assert(CSI.ReturnType.isNull() || !CSI.ReturnType->isUndeducedType());
695 assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().CPlusPlus14) &&
696 "lambda expressions use auto deduction in C++14 onwards");
697
698 // C++ core issue 975:
699 // If a lambda-expression does not include a trailing-return-type,
700 // it is as if the trailing-return-type denotes the following type:
701 // - if there are no return statements in the compound-statement,
702 // or all return statements return either an expression of type
703 // void or no expression or braced-init-list, the type void;
704 // - otherwise, if all return statements return an expression
705 // and the types of the returned expressions after
706 // lvalue-to-rvalue conversion (4.1 [conv.lval]),
707 // array-to-pointer conversion (4.2 [conv.array]), and
708 // function-to-pointer conversion (4.3 [conv.func]) are the
709 // same, that common type;
710 // - otherwise, the program is ill-formed.
711 //
712 // C++ core issue 1048 additionally removes top-level cv-qualifiers
713 // from the types of returned expressions to match the C++14 auto
714 // deduction rules.
715 //
716 // In addition, in blocks in non-C++ modes, if all of the return
717 // statements are enumerator-like expressions of some type T, where
718 // T has a name for linkage, then we infer the return type of the
719 // block to be that type.
720
721 // First case: no return statements, implicit void return type.
722 ASTContext &Ctx = getASTContext();
723 if (CSI.Returns.empty()) {
724 // It's possible there were simply no /valid/ return statements.
725 // In this case, the first one we found may have at least given us a type.
726 if (CSI.ReturnType.isNull())
727 CSI.ReturnType = Ctx.VoidTy;
728 return;
729 }
730
731 // Second case: at least one return statement has dependent type.
732 // Delay type checking until instantiation.
733 assert(!CSI.ReturnType.isNull() && "We should have a tentative return type.");
734 if (CSI.ReturnType->isDependentType())
735 return;
736
737 // Try to apply the enum-fuzz rule.
738 if (!getLangOpts().CPlusPlus) {
739 assert(isa<BlockScopeInfo>(CSI));
741 if (ED) {
744 return;
745 }
746 }
747
748 // Third case: only one return statement. Don't bother doing extra work!
749 if (CSI.Returns.size() == 1)
750 return;
751
752 // General case: many return statements.
753 // Check that they all have compatible return types.
754
755 // We require the return types to strictly match here.
756 // Note that we've already done the required promotions as part of
757 // processing the return statement.
758 for (const ReturnStmt *RS : CSI.Returns) {
759 const Expr *RetE = RS->getRetValue();
760
761 QualType ReturnType =
762 (RetE ? RetE->getType() : Context.VoidTy).getUnqualifiedType();
763 if (Context.getCanonicalFunctionResultType(ReturnType) ==
765 // Use the return type with the strictest possible nullability annotation.
766 auto RetTyNullability = ReturnType->getNullability();
767 auto BlockNullability = CSI.ReturnType->getNullability();
768 if (BlockNullability &&
769 (!RetTyNullability ||
770 hasWeakerNullability(*RetTyNullability, *BlockNullability)))
771 CSI.ReturnType = ReturnType;
772 continue;
773 }
774
775 // FIXME: This is a poor diagnostic for ReturnStmts without expressions.
776 // TODO: It's possible that the *first* return is the divergent one.
777 Diag(RS->getBeginLoc(),
778 diag::err_typecheck_missing_return_type_incompatible)
779 << ReturnType << CSI.ReturnType << isa<LambdaScopeInfo>(CSI);
780 // Continue iterating so that we keep emitting diagnostics.
781 }
782}
783
785 SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc,
786 std::optional<unsigned> NumExpansions, IdentifierInfo *Id,
787 bool IsDirectInit, Expr *&Init) {
788 // Create an 'auto' or 'auto&' TypeSourceInfo that we can use to
789 // deduce against.
790 QualType DeductType = Context.getAutoDeductType();
791 TypeLocBuilder TLB;
792 AutoTypeLoc TL = TLB.push<AutoTypeLoc>(DeductType);
793 TL.setNameLoc(Loc);
794 if (ByRef) {
795 DeductType = BuildReferenceType(DeductType, true, Loc, Id);
796 assert(!DeductType.isNull() && "can't build reference to auto");
797 TLB.push<ReferenceTypeLoc>(DeductType).setSigilLoc(Loc);
798 }
799 if (EllipsisLoc.isValid()) {
800 if (Init->containsUnexpandedParameterPack()) {
801 Diag(EllipsisLoc, getLangOpts().CPlusPlus20
802 ? diag::warn_cxx17_compat_init_capture_pack
803 : diag::ext_init_capture_pack);
804 DeductType = Context.getPackExpansionType(DeductType, NumExpansions,
805 /*ExpectPackInType=*/false);
806 TLB.push<PackExpansionTypeLoc>(DeductType).setEllipsisLoc(EllipsisLoc);
807 } else {
808 // Just ignore the ellipsis for now and form a non-pack variable. We'll
809 // diagnose this later when we try to capture it.
810 }
811 }
812 TypeSourceInfo *TSI = TLB.getTypeSourceInfo(Context, DeductType);
813
814 // Deduce the type of the init capture.
816 /*VarDecl*/nullptr, DeclarationName(Id), DeductType, TSI,
817 SourceRange(Loc, Loc), IsDirectInit, Init);
818 if (DeducedType.isNull())
819 return QualType();
820
821 // Are we a non-list direct initialization?
822 ParenListExpr *CXXDirectInit = dyn_cast<ParenListExpr>(Init);
823
824 // Perform initialization analysis and ensure any implicit conversions
825 // (such as lvalue-to-rvalue) are enforced.
826 InitializedEntity Entity =
828 InitializationKind Kind =
829 IsDirectInit
830 ? (CXXDirectInit ? InitializationKind::CreateDirect(
831 Loc, Init->getBeginLoc(), Init->getEndLoc())
833 : InitializationKind::CreateCopy(Loc, Init->getBeginLoc());
834
835 MultiExprArg Args = Init;
836 if (CXXDirectInit)
837 Args =
838 MultiExprArg(CXXDirectInit->getExprs(), CXXDirectInit->getNumExprs());
839 QualType DclT;
840 InitializationSequence InitSeq(*this, Entity, Kind, Args);
841 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Args, &DclT);
842
843 if (Result.isInvalid())
844 return QualType();
845
846 Init = Result.getAs<Expr>();
847 return DeducedType;
848}
849
851 SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc,
852 IdentifierInfo *Id, unsigned InitStyle, Expr *Init, DeclContext *DeclCtx) {
853 // FIXME: Retain the TypeSourceInfo from buildLambdaInitCaptureInitialization
854 // rather than reconstructing it here.
855 TypeSourceInfo *TSI = Context.getTrivialTypeSourceInfo(InitCaptureType, Loc);
856 if (auto PETL = TSI->getTypeLoc().getAs<PackExpansionTypeLoc>())
857 PETL.setEllipsisLoc(EllipsisLoc);
858
859 // Create a dummy variable representing the init-capture. This is not actually
860 // used as a variable, and only exists as a way to name and refer to the
861 // init-capture.
862 // FIXME: Pass in separate source locations for '&' and identifier.
863 VarDecl *NewVD = VarDecl::Create(Context, DeclCtx, Loc, Loc, Id,
864 InitCaptureType, TSI, SC_Auto);
865 NewVD->setInitCapture(true);
866 NewVD->setReferenced(true);
867 // FIXME: Pass in a VarDecl::InitializationStyle.
868 NewVD->setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle));
869 NewVD->markUsed(Context);
870 NewVD->setInit(Init);
871 if (NewVD->isParameterPack())
872 getCurLambda()->LocalPacks.push_back(NewVD);
873 return NewVD;
874}
875
876void Sema::addInitCapture(LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef) {
877 assert(Var->isInitCapture() && "init capture flag should be set");
878 LSI->addCapture(Var, /*isBlock=*/false, ByRef,
879 /*isNested=*/false, Var->getLocation(), SourceLocation(),
880 Var->getType(), /*Invalid=*/false);
881}
882
883// Unlike getCurLambda, getCurrentLambdaScopeUnsafe doesn't
884// check that the current lambda is in a consistent or fully constructed state.
886 assert(!S.FunctionScopes.empty());
887 return cast<LambdaScopeInfo>(S.FunctionScopes[S.FunctionScopes.size() - 1]);
888}
889
890static TypeSourceInfo *
892 // C++11 [expr.prim.lambda]p4:
893 // If a lambda-expression does not include a lambda-declarator, it is as
894 // if the lambda-declarator were ().
896 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
897 EPI.HasTrailingReturn = true;
898 EPI.TypeQuals.addConst();
900 if (AS != LangAS::Default)
902
903 // C++1y [expr.prim.lambda]:
904 // The lambda return type is 'auto', which is replaced by the
905 // trailing-return type if provided and/or deduced from 'return'
906 // statements
907 // We don't do this before C++1y, because we don't support deduced return
908 // types there.
909 QualType DefaultTypeForNoTrailingReturn = S.getLangOpts().CPlusPlus14
912 QualType MethodTy = S.Context.getFunctionType(DefaultTypeForNoTrailingReturn,
913 std::nullopt, EPI);
914 return S.Context.getTrivialTypeSourceInfo(MethodTy, Loc);
915}
916
918 Declarator &ParamInfo, Scope *CurScope,
920 bool &ExplicitResultType) {
921
922 ExplicitResultType = false;
923
924 assert(
925 (ParamInfo.getDeclSpec().getStorageClassSpec() ==
928 "Unexpected storage specifier");
929 bool IsLambdaStatic =
931
932 TypeSourceInfo *MethodTyInfo;
933
934 if (ParamInfo.getNumTypeObjects() == 0) {
935 MethodTyInfo = getDummyLambdaType(S, Loc);
936 } else {
937 // Check explicit parameters
938 S.CheckExplicitObjectLambda(ParamInfo);
939
941
942 bool HasExplicitObjectParameter =
944
945 ExplicitResultType = FTI.hasTrailingReturnType();
946 if (!FTI.hasMutableQualifier() && !IsLambdaStatic &&
947 !HasExplicitObjectParameter)
949
950 if (ExplicitResultType && S.getLangOpts().HLSL) {
951 QualType RetTy = FTI.getTrailingReturnType().get();
952 if (!RetTy.isNull()) {
953 // HLSL does not support specifying an address space on a lambda return
954 // type.
955 LangAS AddressSpace = RetTy.getAddressSpace();
956 if (AddressSpace != LangAS::Default)
958 diag::err_return_value_with_address_space);
959 }
960 }
961
962 MethodTyInfo = S.GetTypeForDeclarator(ParamInfo);
963 assert(MethodTyInfo && "no type from lambda-declarator");
964
965 // Check for unexpanded parameter packs in the method type.
966 if (MethodTyInfo->getType()->containsUnexpandedParameterPack())
967 S.DiagnoseUnexpandedParameterPack(Intro.Range.getBegin(), MethodTyInfo,
969 }
970 return MethodTyInfo;
971}
972
975
976 // C++20 [expr.prim.lambda.closure]p3:
977 // The closure type for a lambda-expression has a public inline function
978 // call operator (for a non-generic lambda) or function call operator
979 // template (for a generic lambda) whose parameters and return type are
980 // described by the lambda-expression's parameter-declaration-clause
981 // and trailing-return-type respectively.
982 DeclarationName MethodName =
984 DeclarationNameLoc MethodNameLoc =
988 DeclarationNameInfo(MethodName, IntroducerRange.getBegin(),
989 MethodNameLoc),
990 QualType(), /*Tinfo=*/nullptr, SC_None,
991 getCurFPFeatures().isFPConstrained(),
993 /*TrailingRequiresClause=*/nullptr);
994 Method->setAccess(AS_public);
995 return Method;
996}
997
999 CXXMethodDecl *CallOperator, CXXRecordDecl *Class,
1000 TemplateParameterList *TemplateParams) {
1001 assert(TemplateParams && "no template parameters");
1003 Context, Class, CallOperator->getLocation(), CallOperator->getDeclName(),
1004 TemplateParams, CallOperator);
1005 TemplateMethod->setAccess(AS_public);
1006 CallOperator->setDescribedFunctionTemplate(TemplateMethod);
1007}
1008
1010 CXXMethodDecl *Method, SourceLocation LambdaLoc,
1011 SourceLocation CallOperatorLoc, Expr *TrailingRequiresClause,
1012 TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind,
1014 bool HasExplicitResultType) {
1015
1017
1018 if (TrailingRequiresClause)
1019 Method->setTrailingRequiresClause(TrailingRequiresClause);
1020
1021 TemplateParameterList *TemplateParams =
1023
1024 DeclContext *DC = Method->getLexicalDeclContext();
1025 // DeclContext::addDecl() assumes that the DeclContext we're adding to is the
1026 // lexical context of the Method. Do so.
1027 Method->setLexicalDeclContext(LSI->Lambda);
1028 if (TemplateParams) {
1029 FunctionTemplateDecl *TemplateMethod =
1031 assert(TemplateMethod &&
1032 "AddTemplateParametersToLambdaCallOperator should have been called");
1033
1034 LSI->Lambda->addDecl(TemplateMethod);
1035 TemplateMethod->setLexicalDeclContext(DC);
1036 } else {
1037 LSI->Lambda->addDecl(Method);
1038 }
1039 LSI->Lambda->setLambdaIsGeneric(TemplateParams);
1040 LSI->Lambda->setLambdaTypeInfo(MethodTyInfo);
1041
1042 Method->setLexicalDeclContext(DC);
1043 Method->setLocation(LambdaLoc);
1044 Method->setInnerLocStart(CallOperatorLoc);
1045 Method->setTypeSourceInfo(MethodTyInfo);
1046 Method->setType(buildTypeForLambdaCallOperator(*this, LSI->Lambda,
1047 TemplateParams, MethodTyInfo));
1048 Method->setConstexprKind(ConstexprKind);
1049 Method->setStorageClass(SC);
1050 if (!Params.empty()) {
1051 CheckParmsForFunctionDef(Params, /*CheckParameterNames=*/false);
1052 Method->setParams(Params);
1053 for (auto P : Method->parameters()) {
1054 assert(P && "null in a parameter list");
1055 P->setOwningFunction(Method);
1056 }
1057 }
1058
1059 buildLambdaScopeReturnType(*this, LSI, Method, HasExplicitResultType);
1060}
1061
1063 Scope *CurrentScope) {
1064
1066 assert(LSI && "LambdaScopeInfo should be on stack!");
1067
1068 if (Intro.Default == LCD_ByCopy)
1069 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByval;
1070 else if (Intro.Default == LCD_ByRef)
1071 LSI->ImpCaptureStyle = LambdaScopeInfo::ImpCap_LambdaByref;
1072 LSI->CaptureDefaultLoc = Intro.DefaultLoc;
1073 LSI->IntroducerRange = Intro.Range;
1074 LSI->AfterParameterList = false;
1075
1076 assert(LSI->NumExplicitTemplateParams == 0);
1077
1078 // Determine if we're within a context where we know that the lambda will
1079 // be dependent, because there are template parameters in scope.
1080 CXXRecordDecl::LambdaDependencyKind LambdaDependencyKind =
1082 if (CurScope->getTemplateParamParent() != nullptr) {
1083 LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
1084 } else if (Scope *P = CurScope->getParent()) {
1085 // Given a lambda defined inside a requires expression,
1086 //
1087 // struct S {
1088 // S(auto var) requires requires { [&] -> decltype(var) { }; }
1089 // {}
1090 // };
1091 //
1092 // The parameter var is not injected into the function Decl at the point of
1093 // parsing lambda. In such scenarios, perceiving it as dependent could
1094 // result in the constraint being evaluated, which matches what GCC does.
1095 while (P->getEntity() && P->getEntity()->isRequiresExprBody())
1096 P = P->getParent();
1097 if (P->isFunctionDeclarationScope() &&
1098 llvm::any_of(P->decls(), [](Decl *D) {
1099 return isa<ParmVarDecl>(D) &&
1100 cast<ParmVarDecl>(D)->getType()->isTemplateTypeParmType();
1101 }))
1102 LambdaDependencyKind = CXXRecordDecl::LDK_AlwaysDependent;
1103 }
1104
1106 Intro.Range, /*Info=*/nullptr, LambdaDependencyKind, Intro.Default);
1107 LSI->Lambda = Class;
1108
1110 LSI->CallOperator = Method;
1111 // Temporarily set the lexical declaration context to the current
1112 // context, so that the Scope stack matches the lexical nesting.
1114
1115 PushDeclContext(CurScope, Method);
1116
1117 bool ContainsUnexpandedParameterPack = false;
1118
1119 // Distinct capture names, for diagnostics.
1120 llvm::DenseMap<IdentifierInfo *, ValueDecl *> CaptureNames;
1121
1122 // Handle explicit captures.
1123 SourceLocation PrevCaptureLoc =
1124 Intro.Default == LCD_None ? Intro.Range.getBegin() : Intro.DefaultLoc;
1125 for (auto C = Intro.Captures.begin(), E = Intro.Captures.end(); C != E;
1126 PrevCaptureLoc = C->Loc, ++C) {
1127 if (C->Kind == LCK_This || C->Kind == LCK_StarThis) {
1128 if (C->Kind == LCK_StarThis)
1129 Diag(C->Loc, !getLangOpts().CPlusPlus17
1130 ? diag::ext_star_this_lambda_capture_cxx17
1131 : diag::warn_cxx14_compat_star_this_lambda_capture);
1132
1133 // C++11 [expr.prim.lambda]p8:
1134 // An identifier or this shall not appear more than once in a
1135 // lambda-capture.
1136 if (LSI->isCXXThisCaptured()) {
1137 Diag(C->Loc, diag::err_capture_more_than_once)
1138 << "'this'" << SourceRange(LSI->getCXXThisCapture().getLocation())
1140 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1141 continue;
1142 }
1143
1144 // C++20 [expr.prim.lambda]p8:
1145 // If a lambda-capture includes a capture-default that is =,
1146 // each simple-capture of that lambda-capture shall be of the form
1147 // "&identifier", "this", or "* this". [ Note: The form [&,this] is
1148 // redundant but accepted for compatibility with ISO C++14. --end note ]
1149 if (Intro.Default == LCD_ByCopy && C->Kind != LCK_StarThis)
1150 Diag(C->Loc, !getLangOpts().CPlusPlus20
1151 ? diag::ext_equals_this_lambda_capture_cxx20
1152 : diag::warn_cxx17_compat_equals_this_lambda_capture);
1153
1154 // C++11 [expr.prim.lambda]p12:
1155 // If this is captured by a local lambda expression, its nearest
1156 // enclosing function shall be a non-static member function.
1157 QualType ThisCaptureType = getCurrentThisType();
1158 if (ThisCaptureType.isNull()) {
1159 Diag(C->Loc, diag::err_this_capture) << true;
1160 continue;
1161 }
1162
1163 CheckCXXThisCapture(C->Loc, /*Explicit=*/true, /*BuildAndDiagnose*/ true,
1164 /*FunctionScopeIndexToStopAtPtr*/ nullptr,
1165 C->Kind == LCK_StarThis);
1166 if (!LSI->Captures.empty())
1167 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1168 continue;
1169 }
1170
1171 assert(C->Id && "missing identifier for capture");
1172
1173 if (C->Init.isInvalid())
1174 continue;
1175
1176 ValueDecl *Var = nullptr;
1177 if (C->Init.isUsable()) {
1179 ? diag::warn_cxx11_compat_init_capture
1180 : diag::ext_init_capture);
1181
1182 // If the initializer expression is usable, but the InitCaptureType
1183 // is not, then an error has occurred - so ignore the capture for now.
1184 // for e.g., [n{0}] { }; <-- if no <initializer_list> is included.
1185 // FIXME: we should create the init capture variable and mark it invalid
1186 // in this case.
1187 if (C->InitCaptureType.get().isNull())
1188 continue;
1189
1190 if (C->Init.get()->containsUnexpandedParameterPack() &&
1191 !C->InitCaptureType.get()->getAs<PackExpansionType>())
1193
1194 unsigned InitStyle;
1195 switch (C->InitKind) {
1197 llvm_unreachable("not an init-capture?");
1199 InitStyle = VarDecl::CInit;
1200 break;
1202 InitStyle = VarDecl::CallInit;
1203 break;
1205 InitStyle = VarDecl::ListInit;
1206 break;
1207 }
1208 Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
1209 C->EllipsisLoc, C->Id, InitStyle,
1210 C->Init.get(), Method);
1211 assert(Var && "createLambdaInitCaptureVarDecl returned a null VarDecl?");
1212 if (auto *V = dyn_cast<VarDecl>(Var))
1213 CheckShadow(CurrentScope, V);
1214 PushOnScopeChains(Var, CurrentScope, false);
1215 } else {
1216 assert(C->InitKind == LambdaCaptureInitKind::NoInit &&
1217 "init capture has valid but null init?");
1218
1219 // C++11 [expr.prim.lambda]p8:
1220 // If a lambda-capture includes a capture-default that is &, the
1221 // identifiers in the lambda-capture shall not be preceded by &.
1222 // If a lambda-capture includes a capture-default that is =, [...]
1223 // each identifier it contains shall be preceded by &.
1224 if (C->Kind == LCK_ByRef && Intro.Default == LCD_ByRef) {
1225 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
1227 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1228 continue;
1229 } else if (C->Kind == LCK_ByCopy && Intro.Default == LCD_ByCopy) {
1230 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
1232 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1233 continue;
1234 }
1235
1236 // C++11 [expr.prim.lambda]p10:
1237 // The identifiers in a capture-list are looked up using the usual
1238 // rules for unqualified name lookup (3.4.1)
1239 DeclarationNameInfo Name(C->Id, C->Loc);
1240 LookupResult R(*this, Name, LookupOrdinaryName);
1241 LookupName(R, CurScope);
1242 if (R.isAmbiguous())
1243 continue;
1244 if (R.empty()) {
1245 // FIXME: Disable corrections that would add qualification?
1246 CXXScopeSpec ScopeSpec;
1247 DeclFilterCCC<VarDecl> Validator{};
1248 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
1249 continue;
1250 }
1251
1252 if (auto *BD = R.getAsSingle<BindingDecl>())
1253 Var = BD;
1254 else if (R.getAsSingle<FieldDecl>()) {
1255 Diag(C->Loc, diag::err_capture_class_member_does_not_name_variable)
1256 << C->Id;
1257 continue;
1258 } else
1259 Var = R.getAsSingle<VarDecl>();
1260 if (Var && DiagnoseUseOfDecl(Var, C->Loc))
1261 continue;
1262 }
1263
1264 // C++11 [expr.prim.lambda]p10:
1265 // [...] each such lookup shall find a variable with automatic storage
1266 // duration declared in the reaching scope of the local lambda expression.
1267 // Note that the 'reaching scope' check happens in tryCaptureVariable().
1268 if (!Var) {
1269 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
1270 continue;
1271 }
1272
1273 // C++11 [expr.prim.lambda]p8:
1274 // An identifier or this shall not appear more than once in a
1275 // lambda-capture.
1276 if (auto [It, Inserted] = CaptureNames.insert(std::pair{C->Id, Var});
1277 !Inserted) {
1278 if (C->InitKind == LambdaCaptureInitKind::NoInit &&
1279 !Var->isInitCapture()) {
1280 Diag(C->Loc, diag::err_capture_more_than_once)
1281 << C->Id << It->second->getBeginLoc()
1283 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1284 Var->setInvalidDecl();
1285 } else if (Var && Var->isPlaceholderVar(getLangOpts())) {
1287 } else {
1288 // Previous capture captured something different (one or both was
1289 // an init-capture): no fixit.
1290 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
1291 continue;
1292 }
1293 }
1294
1295 // Ignore invalid decls; they'll just confuse the code later.
1296 if (Var->isInvalidDecl())
1297 continue;
1298
1299 VarDecl *Underlying = Var->getPotentiallyDecomposedVarDecl();
1300
1301 if (!Underlying->hasLocalStorage()) {
1302 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
1303 Diag(Var->getLocation(), diag::note_previous_decl) << C->Id;
1304 continue;
1305 }
1306
1307 // C++11 [expr.prim.lambda]p23:
1308 // A capture followed by an ellipsis is a pack expansion (14.5.3).
1309 SourceLocation EllipsisLoc;
1310 if (C->EllipsisLoc.isValid()) {
1311 if (Var->isParameterPack()) {
1312 EllipsisLoc = C->EllipsisLoc;
1313 } else {
1314 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1315 << (C->Init.isUsable() ? C->Init.get()->getSourceRange()
1316 : SourceRange(C->Loc));
1317
1318 // Just ignore the ellipsis.
1319 }
1320 } else if (Var->isParameterPack()) {
1321 ContainsUnexpandedParameterPack = true;
1322 }
1323
1324 if (C->Init.isUsable()) {
1325 addInitCapture(LSI, cast<VarDecl>(Var), C->Kind == LCK_ByRef);
1326 PushOnScopeChains(Var, CurScope, false);
1327 } else {
1330 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
1331 }
1332 if (!LSI->Captures.empty())
1333 LSI->ExplicitCaptureRanges[LSI->Captures.size() - 1] = C->ExplicitRange;
1334 }
1336 LSI->ContainsUnexpandedParameterPack |= ContainsUnexpandedParameterPack;
1338}
1339
1341 SourceLocation MutableLoc) {
1342
1344 LSI->Mutable = MutableLoc.isValid();
1345 ContextRAII Context(*this, LSI->CallOperator, /*NewThisContext*/ false);
1346
1347 // C++11 [expr.prim.lambda]p9:
1348 // A lambda-expression whose smallest enclosing scope is a block scope is a
1349 // local lambda expression; any other lambda expression shall not have a
1350 // capture-default or simple-capture in its lambda-introducer.
1351 //
1352 // For simple-captures, this is covered by the check below that any named
1353 // entity is a variable that can be captured.
1354 //
1355 // For DR1632, we also allow a capture-default in any context where we can
1356 // odr-use 'this' (in particular, in a default initializer for a non-static
1357 // data member).
1358 if (Intro.Default != LCD_None &&
1359 !LSI->Lambda->getParent()->isFunctionOrMethod() &&
1360 (getCurrentThisType().isNull() ||
1361 CheckCXXThisCapture(SourceLocation(), /*Explicit=*/true,
1362 /*BuildAndDiagnose=*/false)))
1363 Diag(Intro.DefaultLoc, diag::err_capture_default_non_local);
1364}
1365
1369 PushDeclContext(LambdaScope, LSI->CallOperator);
1370
1371 for (const DeclaratorChunk::ParamInfo &P : Params) {
1372 auto *Param = cast<ParmVarDecl>(P.Param);
1373 Param->setOwningFunction(LSI->CallOperator);
1374 if (Param->getIdentifier())
1375 PushOnScopeChains(Param, LambdaScope, false);
1376 }
1377
1378 // After the parameter list, we may parse a noexcept/requires/trailing return
1379 // type which need to know whether the call operator constiture a dependent
1380 // context, so we need to setup the FunctionTemplateDecl of generic lambdas
1381 // now.
1382 TemplateParameterList *TemplateParams =
1384 if (TemplateParams) {
1386 TemplateParams);
1387 LSI->Lambda->setLambdaIsGeneric(true);
1389 TemplateParams->containsUnexpandedParameterPack();
1390 }
1391 LSI->AfterParameterList = true;
1392}
1393
1395 Declarator &ParamInfo,
1396 const DeclSpec &DS) {
1397
1400
1402 bool ExplicitResultType;
1403
1404 SourceLocation TypeLoc, CallOperatorLoc;
1405 if (ParamInfo.getNumTypeObjects() == 0) {
1406 CallOperatorLoc = TypeLoc = Intro.Range.getEnd();
1407 } else {
1408 unsigned Index;
1409 ParamInfo.isFunctionDeclarator(Index);
1410 const auto &Object = ParamInfo.getTypeObject(Index);
1411 TypeLoc =
1412 Object.Loc.isValid() ? Object.Loc : ParamInfo.getSourceRange().getEnd();
1413 CallOperatorLoc = ParamInfo.getSourceRange().getEnd();
1414 }
1415
1416 CXXRecordDecl *Class = LSI->Lambda;
1417 CXXMethodDecl *Method = LSI->CallOperator;
1418
1419 TypeSourceInfo *MethodTyInfo = getLambdaType(
1420 *this, Intro, ParamInfo, getCurScope(), TypeLoc, ExplicitResultType);
1421
1422 LSI->ExplicitParams = ParamInfo.getNumTypeObjects() != 0;
1423
1424 if (ParamInfo.isFunctionDeclarator() != 0 &&
1426 const auto &FTI = ParamInfo.getFunctionTypeInfo();
1427 Params.reserve(Params.size());
1428 for (unsigned I = 0; I < FTI.NumParams; ++I) {
1429 auto *Param = cast<ParmVarDecl>(FTI.Params[I].Param);
1430 Param->setScopeInfo(0, Params.size());
1431 Params.push_back(Param);
1432 }
1433 }
1434
1435 bool IsLambdaStatic =
1437
1439 Method, Intro.Range.getBegin(), CallOperatorLoc,
1440 ParamInfo.getTrailingRequiresClause(), MethodTyInfo,
1441 ParamInfo.getDeclSpec().getConstexprSpecifier(),
1442 IsLambdaStatic ? SC_Static : SC_None, Params, ExplicitResultType);
1443
1445
1446 // This represents the function body for the lambda function, check if we
1447 // have to apply optnone due to a pragma.
1448 AddRangeBasedOptnone(Method);
1449
1450 // code_seg attribute on lambda apply to the method.
1452 Method, /*IsDefinition=*/true))
1453 Method->addAttr(A);
1454
1455 // Attributes on the lambda apply to the method.
1456 ProcessDeclAttributes(CurScope, Method, ParamInfo);
1457
1458 // CUDA lambdas get implicit host and device attributes.
1459 if (getLangOpts().CUDA)
1460 CUDA().SetLambdaAttrs(Method);
1461
1462 // OpenMP lambdas might get assumumption attributes.
1463 if (LangOpts.OpenMP)
1465
1467
1468 for (auto &&C : LSI->Captures) {
1469 if (!C.isVariableCapture())
1470 continue;
1471 ValueDecl *Var = C.getVariable();
1472 if (Var && Var->isInitCapture()) {
1473 PushOnScopeChains(Var, CurScope, false);
1474 }
1475 }
1476
1477 auto CheckRedefinition = [&](ParmVarDecl *Param) {
1478 for (const auto &Capture : Intro.Captures) {
1479 if (Capture.Id == Param->getIdentifier()) {
1480 Diag(Param->getLocation(), diag::err_parameter_shadow_capture);
1481 Diag(Capture.Loc, diag::note_var_explicitly_captured_here)
1482 << Capture.Id << true;
1483 return false;
1484 }
1485 }
1486 return true;
1487 };
1488
1489 for (ParmVarDecl *P : Params) {
1490 if (!P->getIdentifier())
1491 continue;
1492 if (CheckRedefinition(P))
1493 CheckShadow(CurScope, P);
1494 PushOnScopeChains(P, CurScope);
1495 }
1496
1497 // C++23 [expr.prim.lambda.capture]p5:
1498 // If an identifier in a capture appears as the declarator-id of a parameter
1499 // of the lambda-declarator's parameter-declaration-clause or as the name of a
1500 // template parameter of the lambda-expression's template-parameter-list, the
1501 // program is ill-formed.
1502 TemplateParameterList *TemplateParams =
1504 if (TemplateParams) {
1505 for (const auto *TP : TemplateParams->asArray()) {
1506 if (!TP->getIdentifier())
1507 continue;
1508 for (const auto &Capture : Intro.Captures) {
1509 if (Capture.Id == TP->getIdentifier()) {
1510 Diag(Capture.Loc, diag::err_template_param_shadow) << Capture.Id;
1512 }
1513 }
1514 }
1515 }
1516
1517 // C++20: dcl.decl.general p4:
1518 // The optional requires-clause ([temp.pre]) in an init-declarator or
1519 // member-declarator shall be present only if the declarator declares a
1520 // templated function ([dcl.fct]).
1521 if (Expr *TRC = Method->getTrailingRequiresClause()) {
1522 // [temp.pre]/8:
1523 // An entity is templated if it is
1524 // - a template,
1525 // - an entity defined ([basic.def]) or created ([class.temporary]) in a
1526 // templated entity,
1527 // - a member of a templated entity,
1528 // - an enumerator for an enumeration that is a templated entity, or
1529 // - the closure type of a lambda-expression ([expr.prim.lambda.closure])
1530 // appearing in the declaration of a templated entity. [Note 6: A local
1531 // class, a local or block variable, or a friend function defined in a
1532 // templated entity is a templated entity. — end note]
1533 //
1534 // A templated function is a function template or a function that is
1535 // templated. A templated class is a class template or a class that is
1536 // templated. A templated variable is a variable template or a variable
1537 // that is templated.
1538
1539 // Note: we only have to check if this is defined in a template entity, OR
1540 // if we are a template, since the rest don't apply. The requires clause
1541 // applies to the call operator, which we already know is a member function,
1542 // AND defined.
1543 if (!Method->getDescribedFunctionTemplate() && !Method->isTemplated()) {
1544 Diag(TRC->getBeginLoc(), diag::err_constrained_non_templated_function);
1545 }
1546 }
1547
1548 // Enter a new evaluation context to insulate the lambda from any
1549 // cleanups from the enclosing full-expression.
1554 ExprEvalContexts.back().InImmediateFunctionContext =
1555 LSI->CallOperator->isConsteval();
1556 ExprEvalContexts.back().InImmediateEscalatingFunctionContext =
1557 getLangOpts().CPlusPlus20 && LSI->CallOperator->isImmediateEscalating();
1558}
1559
1561 bool IsInstantiation) {
1562 LambdaScopeInfo *LSI = cast<LambdaScopeInfo>(FunctionScopes.back());
1563
1564 // Leave the expression-evaluation context.
1567
1568 // Leave the context of the lambda.
1569 if (!IsInstantiation)
1571
1572 // Finalize the lambda.
1573 CXXRecordDecl *Class = LSI->Lambda;
1574 Class->setInvalidDecl();
1575 SmallVector<Decl*, 4> Fields(Class->fields());
1576 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
1578 CheckCompletedCXXClass(nullptr, Class);
1579
1581}
1582
1583template <typename Func>
1585 Sema &S, const FunctionProtoType &CallOpProto, Func F) {
1587 CallOpProto.isVariadic(), /*IsCXXMethod=*/false);
1589 CallOpProto.isVariadic(), /*IsCXXMethod=*/true);
1590 CallingConv CallOpCC = CallOpProto.getCallConv();
1591
1592 /// Implement emitting a version of the operator for many of the calling
1593 /// conventions for MSVC, as described here:
1594 /// https://devblogs.microsoft.com/oldnewthing/20150220-00/?p=44623.
1595 /// Experimentally, we determined that cdecl, stdcall, fastcall, and
1596 /// vectorcall are generated by MSVC when it is supported by the target.
1597 /// Additionally, we are ensuring that the default-free/default-member and
1598 /// call-operator calling convention are generated as well.
1599 /// NOTE: We intentionally generate a 'thiscall' on Win32 implicitly from the
1600 /// 'member default', despite MSVC not doing so. We do this in order to ensure
1601 /// that someone who intentionally places 'thiscall' on the lambda call
1602 /// operator will still get that overload, since we don't have the a way of
1603 /// detecting the attribute by the time we get here.
1604 if (S.getLangOpts().MSVCCompat) {
1605 CallingConv Convs[] = {
1607 DefaultFree, DefaultMember, CallOpCC};
1608 llvm::sort(Convs);
1609 llvm::iterator_range<CallingConv *> Range(
1610 std::begin(Convs), std::unique(std::begin(Convs), std::end(Convs)));
1611 const TargetInfo &TI = S.getASTContext().getTargetInfo();
1612
1613 for (CallingConv C : Range) {
1615 F(C);
1616 }
1617 return;
1618 }
1619
1620 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree) {
1621 F(DefaultFree);
1622 F(DefaultMember);
1623 } else {
1624 F(CallOpCC);
1625 }
1626}
1627
1628// Returns the 'standard' calling convention to be used for the lambda
1629// conversion function, that is, the 'free' function calling convention unless
1630// it is overridden by a non-default calling convention attribute.
1631static CallingConv
1633 const FunctionProtoType *CallOpProto) {
1635 CallOpProto->isVariadic(), /*IsCXXMethod=*/false);
1637 CallOpProto->isVariadic(), /*IsCXXMethod=*/true);
1638 CallingConv CallOpCC = CallOpProto->getCallConv();
1639
1640 // If the call-operator hasn't been changed, return both the 'free' and
1641 // 'member' function calling convention.
1642 if (CallOpCC == DefaultMember && DefaultMember != DefaultFree)
1643 return DefaultFree;
1644 return CallOpCC;
1645}
1646
1648 const FunctionProtoType *CallOpProto, CallingConv CC) {
1649 const FunctionProtoType::ExtProtoInfo CallOpExtInfo =
1650 CallOpProto->getExtProtoInfo();
1651 FunctionProtoType::ExtProtoInfo InvokerExtInfo = CallOpExtInfo;
1652 InvokerExtInfo.ExtInfo = InvokerExtInfo.ExtInfo.withCallingConv(CC);
1653 InvokerExtInfo.TypeQuals = Qualifiers();
1654 assert(InvokerExtInfo.RefQualifier == RQ_None &&
1655 "Lambda's call operator should not have a reference qualifier");
1656 return Context.getFunctionType(CallOpProto->getReturnType(),
1657 CallOpProto->getParamTypes(), InvokerExtInfo);
1658}
1659
1660/// Add a lambda's conversion to function pointer, as described in
1661/// C++11 [expr.prim.lambda]p6.
1662static void addFunctionPointerConversion(Sema &S, SourceRange IntroducerRange,
1664 CXXMethodDecl *CallOperator,
1665 QualType InvokerFunctionTy) {
1666 // This conversion is explicitly disabled if the lambda's function has
1667 // pass_object_size attributes on any of its parameters.
1668 auto HasPassObjectSizeAttr = [](const ParmVarDecl *P) {
1669 return P->hasAttr<PassObjectSizeAttr>();
1670 };
1671 if (llvm::any_of(CallOperator->parameters(), HasPassObjectSizeAttr))
1672 return;
1673
1674 // Add the conversion to function pointer.
1675 QualType PtrToFunctionTy = S.Context.getPointerType(InvokerFunctionTy);
1676
1677 // Create the type of the conversion function.
1680 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1681 // The conversion function is always const and noexcept.
1682 ConvExtInfo.TypeQuals = Qualifiers();
1683 ConvExtInfo.TypeQuals.addConst();
1684 ConvExtInfo.ExceptionSpec.Type = EST_BasicNoexcept;
1685 QualType ConvTy =
1686 S.Context.getFunctionType(PtrToFunctionTy, std::nullopt, ConvExtInfo);
1687
1688 SourceLocation Loc = IntroducerRange.getBegin();
1689 DeclarationName ConversionName
1691 S.Context.getCanonicalType(PtrToFunctionTy));
1692 // Construct a TypeSourceInfo for the conversion function, and wire
1693 // all the parameters appropriately for the FunctionProtoTypeLoc
1694 // so that everything works during transformation/instantiation of
1695 // generic lambdas.
1696 // The main reason for wiring up the parameters of the conversion
1697 // function with that of the call operator is so that constructs
1698 // like the following work:
1699 // auto L = [](auto b) { <-- 1
1700 // return [](auto a) -> decltype(a) { <-- 2
1701 // return a;
1702 // };
1703 // };
1704 // int (*fp)(int) = L(5);
1705 // Because the trailing return type can contain DeclRefExprs that refer
1706 // to the original call operator's variables, we hijack the call
1707 // operators ParmVarDecls below.
1708 TypeSourceInfo *ConvNamePtrToFunctionTSI =
1709 S.Context.getTrivialTypeSourceInfo(PtrToFunctionTy, Loc);
1710 DeclarationNameLoc ConvNameLoc =
1711 DeclarationNameLoc::makeNamedTypeLoc(ConvNamePtrToFunctionTSI);
1712
1713 // The conversion function is a conversion to a pointer-to-function.
1714 TypeSourceInfo *ConvTSI = S.Context.getTrivialTypeSourceInfo(ConvTy, Loc);
1715 FunctionProtoTypeLoc ConvTL =
1717 // Get the result of the conversion function which is a pointer-to-function.
1718 PointerTypeLoc PtrToFunctionTL =
1719 ConvTL.getReturnLoc().getAs<PointerTypeLoc>();
1720 // Do the same for the TypeSourceInfo that is used to name the conversion
1721 // operator.
1722 PointerTypeLoc ConvNamePtrToFunctionTL =
1723 ConvNamePtrToFunctionTSI->getTypeLoc().getAs<PointerTypeLoc>();
1724
1725 // Get the underlying function types that the conversion function will
1726 // be converting to (should match the type of the call operator).
1727 FunctionProtoTypeLoc CallOpConvTL =
1728 PtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1729 FunctionProtoTypeLoc CallOpConvNameTL =
1730 ConvNamePtrToFunctionTL.getPointeeLoc().getAs<FunctionProtoTypeLoc>();
1731
1732 // Wire up the FunctionProtoTypeLocs with the call operator's parameters.
1733 // These parameter's are essentially used to transform the name and
1734 // the type of the conversion operator. By using the same parameters
1735 // as the call operator's we don't have to fix any back references that
1736 // the trailing return type of the call operator's uses (such as
1737 // decltype(some_type<decltype(a)>::type{} + decltype(a){}) etc.)
1738 // - we can simply use the return type of the call operator, and
1739 // everything should work.
1740 SmallVector<ParmVarDecl *, 4> InvokerParams;
1741 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
1742 ParmVarDecl *From = CallOperator->getParamDecl(I);
1743
1744 InvokerParams.push_back(ParmVarDecl::Create(
1745 S.Context,
1746 // Temporarily add to the TU. This is set to the invoker below.
1748 From->getLocation(), From->getIdentifier(), From->getType(),
1749 From->getTypeSourceInfo(), From->getStorageClass(),
1750 /*DefArg=*/nullptr));
1751 CallOpConvTL.setParam(I, From);
1752 CallOpConvNameTL.setParam(I, From);
1753 }
1754
1756 S.Context, Class, Loc,
1757 DeclarationNameInfo(ConversionName, Loc, ConvNameLoc), ConvTy, ConvTSI,
1759 /*isInline=*/true, ExplicitSpecifier(),
1762 CallOperator->getBody()->getEndLoc());
1763 Conversion->setAccess(AS_public);
1764 Conversion->setImplicit(true);
1765
1766 // A non-generic lambda may still be a templated entity. We need to preserve
1767 // constraints when converting the lambda to a function pointer. See GH63181.
1768 if (Expr *Requires = CallOperator->getTrailingRequiresClause())
1769 Conversion->setTrailingRequiresClause(Requires);
1770
1771 if (Class->isGenericLambda()) {
1772 // Create a template version of the conversion operator, using the template
1773 // parameter list of the function call operator.
1774 FunctionTemplateDecl *TemplateCallOperator =
1775 CallOperator->getDescribedFunctionTemplate();
1776 FunctionTemplateDecl *ConversionTemplate =
1778 Loc, ConversionName,
1779 TemplateCallOperator->getTemplateParameters(),
1780 Conversion);
1781 ConversionTemplate->setAccess(AS_public);
1782 ConversionTemplate->setImplicit(true);
1783 Conversion->setDescribedFunctionTemplate(ConversionTemplate);
1784 Class->addDecl(ConversionTemplate);
1785 } else
1786 Class->addDecl(Conversion);
1787
1788 // If the lambda is not static, we need to add a static member
1789 // function that will be the result of the conversion with a
1790 // certain unique ID.
1791 // When it is static we just return the static call operator instead.
1792 if (CallOperator->isImplicitObjectMemberFunction()) {
1793 DeclarationName InvokerName =
1795 // FIXME: Instead of passing in the CallOperator->getTypeSourceInfo()
1796 // we should get a prebuilt TrivialTypeSourceInfo from Context
1797 // using FunctionTy & Loc and get its TypeLoc as a FunctionProtoTypeLoc
1798 // then rewire the parameters accordingly, by hoisting up the InvokeParams
1799 // loop below and then use its Params to set Invoke->setParams(...) below.
1800 // This would avoid the 'const' qualifier of the calloperator from
1801 // contaminating the type of the invoker, which is currently adjusted
1802 // in SemaTemplateDeduction.cpp:DeduceTemplateArguments. Fixing the
1803 // trailing return type of the invoker would require a visitor to rebuild
1804 // the trailing return type and adjusting all back DeclRefExpr's to refer
1805 // to the new static invoker parameters - not the call operator's.
1807 S.Context, Class, Loc, DeclarationNameInfo(InvokerName, Loc),
1808 InvokerFunctionTy, CallOperator->getTypeSourceInfo(), SC_Static,
1810 /*isInline=*/true, CallOperator->getConstexprKind(),
1811 CallOperator->getBody()->getEndLoc());
1812 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I)
1813 InvokerParams[I]->setOwningFunction(Invoke);
1814 Invoke->setParams(InvokerParams);
1815 Invoke->setAccess(AS_private);
1816 Invoke->setImplicit(true);
1817 if (Class->isGenericLambda()) {
1818 FunctionTemplateDecl *TemplateCallOperator =
1819 CallOperator->getDescribedFunctionTemplate();
1820 FunctionTemplateDecl *StaticInvokerTemplate =
1822 S.Context, Class, Loc, InvokerName,
1823 TemplateCallOperator->getTemplateParameters(), Invoke);
1824 StaticInvokerTemplate->setAccess(AS_private);
1825 StaticInvokerTemplate->setImplicit(true);
1826 Invoke->setDescribedFunctionTemplate(StaticInvokerTemplate);
1827 Class->addDecl(StaticInvokerTemplate);
1828 } else
1829 Class->addDecl(Invoke);
1830 }
1831}
1832
1833/// Add a lambda's conversion to function pointers, as described in
1834/// C++11 [expr.prim.lambda]p6. Note that in most cases, this should emit only a
1835/// single pointer conversion. In the event that the default calling convention
1836/// for free and member functions is different, it will emit both conventions.
1837static void addFunctionPointerConversions(Sema &S, SourceRange IntroducerRange,
1839 CXXMethodDecl *CallOperator) {
1840 const FunctionProtoType *CallOpProto =
1841 CallOperator->getType()->castAs<FunctionProtoType>();
1842
1844 S, *CallOpProto, [&](CallingConv CC) {
1845 QualType InvokerFunctionTy =
1846 S.getLambdaConversionFunctionResultType(CallOpProto, CC);
1847 addFunctionPointerConversion(S, IntroducerRange, Class, CallOperator,
1848 InvokerFunctionTy);
1849 });
1850}
1851
1852/// Add a lambda's conversion to block pointer.
1854 SourceRange IntroducerRange,
1856 CXXMethodDecl *CallOperator) {
1857 const FunctionProtoType *CallOpProto =
1858 CallOperator->getType()->castAs<FunctionProtoType>();
1860 CallOpProto, getLambdaConversionFunctionCallConv(S, CallOpProto));
1861 QualType BlockPtrTy = S.Context.getBlockPointerType(FunctionTy);
1862
1863 FunctionProtoType::ExtProtoInfo ConversionEPI(
1865 /*IsVariadic=*/false, /*IsCXXMethod=*/true));
1866 ConversionEPI.TypeQuals = Qualifiers();
1867 ConversionEPI.TypeQuals.addConst();
1868 QualType ConvTy =
1869 S.Context.getFunctionType(BlockPtrTy, std::nullopt, ConversionEPI);
1870
1871 SourceLocation Loc = IntroducerRange.getBegin();
1872 DeclarationName Name
1874 S.Context.getCanonicalType(BlockPtrTy));
1876 S.Context.getTrivialTypeSourceInfo(BlockPtrTy, Loc));
1878 S.Context, Class, Loc, DeclarationNameInfo(Name, Loc, NameLoc), ConvTy,
1882 CallOperator->getBody()->getEndLoc());
1883 Conversion->setAccess(AS_public);
1884 Conversion->setImplicit(true);
1885 Class->addDecl(Conversion);
1886}
1887
1889 SourceLocation ImplicitCaptureLoc,
1890 bool IsOpenMPMapping) {
1891 // VLA captures don't have a stored initialization expression.
1892 if (Cap.isVLATypeCapture())
1893 return ExprResult();
1894
1895 // An init-capture is initialized directly from its stored initializer.
1896 if (Cap.isInitCapture())
1897 return cast<VarDecl>(Cap.getVariable())->getInit();
1898
1899 // For anything else, build an initialization expression. For an implicit
1900 // capture, the capture notionally happens at the capture-default, so use
1901 // that location here.
1903 ImplicitCaptureLoc.isValid() ? ImplicitCaptureLoc : Cap.getLocation();
1904
1905 // C++11 [expr.prim.lambda]p21:
1906 // When the lambda-expression is evaluated, the entities that
1907 // are captured by copy are used to direct-initialize each
1908 // corresponding non-static data member of the resulting closure
1909 // object. (For array members, the array elements are
1910 // direct-initialized in increasing subscript order.) These
1911 // initializations are performed in the (unspecified) order in
1912 // which the non-static data members are declared.
1913
1914 // C++ [expr.prim.lambda]p12:
1915 // An entity captured by a lambda-expression is odr-used (3.2) in
1916 // the scope containing the lambda-expression.
1918 IdentifierInfo *Name = nullptr;
1919 if (Cap.isThisCapture()) {
1920 QualType ThisTy = getCurrentThisType();
1921 Expr *This = BuildCXXThisExpr(Loc, ThisTy, ImplicitCaptureLoc.isValid());
1922 if (Cap.isCopyCapture())
1923 Init = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
1924 else
1925 Init = This;
1926 } else {
1927 assert(Cap.isVariableCapture() && "unknown kind of capture");
1928 ValueDecl *Var = Cap.getVariable();
1929 Name = Var->getIdentifier();
1932 }
1933
1934 // In OpenMP, the capture kind doesn't actually describe how to capture:
1935 // variables are "mapped" onto the device in a process that does not formally
1936 // make a copy, even for a "copy capture".
1937 if (IsOpenMPMapping)
1938 return Init;
1939
1940 if (Init.isInvalid())
1941 return ExprError();
1942
1943 Expr *InitExpr = Init.get();
1945 Name, Cap.getCaptureType(), Loc);
1946 InitializationKind InitKind =
1948 InitializationSequence InitSeq(*this, Entity, InitKind, InitExpr);
1949 return InitSeq.Perform(*this, Entity, InitKind, InitExpr);
1950}
1951
1953 LambdaScopeInfo LSI = *cast<LambdaScopeInfo>(FunctionScopes.back());
1955 return BuildLambdaExpr(StartLoc, Body->getEndLoc(), &LSI);
1956}
1957
1960 switch (ICS) {
1962 return LCD_None;
1964 return LCD_ByCopy;
1967 return LCD_ByRef;
1969 llvm_unreachable("block capture in lambda");
1970 }
1971 llvm_unreachable("Unknown implicit capture style");
1972}
1973
1975 if (From.isInitCapture()) {
1976 Expr *Init = cast<VarDecl>(From.getVariable())->getInit();
1977 if (Init && Init->HasSideEffects(Context))
1978 return true;
1979 }
1980
1981 if (!From.isCopyCapture())
1982 return false;
1983
1984 const QualType T = From.isThisCapture()
1986 : From.getCaptureType();
1987
1988 if (T.isVolatileQualified())
1989 return true;
1990
1991 const Type *BaseT = T->getBaseElementTypeUnsafe();
1992 if (const CXXRecordDecl *RD = BaseT->getAsCXXRecordDecl())
1993 return !RD->isCompleteDefinition() || !RD->hasTrivialCopyConstructor() ||
1994 !RD->hasTrivialDestructor();
1995
1996 return false;
1997}
1998
2000 const Capture &From) {
2001 if (CaptureHasSideEffects(From))
2002 return false;
2003
2004 if (From.isVLATypeCapture())
2005 return false;
2006
2007 // FIXME: maybe we should warn on these if we can find a sensible diagnostic
2008 // message
2009 if (From.isInitCapture() &&
2011 return false;
2012
2013 auto diag = Diag(From.getLocation(), diag::warn_unused_lambda_capture);
2014 if (From.isThisCapture())
2015 diag << "'this'";
2016 else
2017 diag << From.getVariable();
2018 diag << From.isNonODRUsed();
2019 diag << FixItHint::CreateRemoval(CaptureRange);
2020 return true;
2021}
2022
2023/// Create a field within the lambda class or captured statement record for the
2024/// given capture.
2026 const sema::Capture &Capture) {
2028 QualType FieldType = Capture.getCaptureType();
2029
2030 TypeSourceInfo *TSI = nullptr;
2031 if (Capture.isVariableCapture()) {
2032 const auto *Var = dyn_cast_or_null<VarDecl>(Capture.getVariable());
2033 if (Var && Var->isInitCapture())
2034 TSI = Var->getTypeSourceInfo();
2035 }
2036
2037 // FIXME: Should we really be doing this? A null TypeSourceInfo seems more
2038 // appropriate, at least for an implicit capture.
2039 if (!TSI)
2040 TSI = Context.getTrivialTypeSourceInfo(FieldType, Loc);
2041
2042 // Build the non-static data member.
2043 FieldDecl *Field =
2044 FieldDecl::Create(Context, RD, /*StartLoc=*/Loc, /*IdLoc=*/Loc,
2045 /*Id=*/nullptr, FieldType, TSI, /*BW=*/nullptr,
2046 /*Mutable=*/false, ICIS_NoInit);
2047 // If the variable being captured has an invalid type, mark the class as
2048 // invalid as well.
2049 if (!FieldType->isDependentType()) {
2050 if (RequireCompleteSizedType(Loc, FieldType,
2051 diag::err_field_incomplete_or_sizeless)) {
2052 RD->setInvalidDecl();
2053 Field->setInvalidDecl();
2054 } else {
2055 NamedDecl *Def;
2056 FieldType->isIncompleteType(&Def);
2057 if (Def && Def->isInvalidDecl()) {
2058 RD->setInvalidDecl();
2059 Field->setInvalidDecl();
2060 }
2061 }
2062 }
2063 Field->setImplicit(true);
2064 Field->setAccess(AS_private);
2065 RD->addDecl(Field);
2066
2068 Field->setCapturedVLAType(Capture.getCapturedVLAType());
2069
2070 return Field;
2071}
2072
2074 LambdaScopeInfo *LSI) {
2075 // Collect information from the lambda scope.
2077 SmallVector<Expr *, 4> CaptureInits;
2078 SourceLocation CaptureDefaultLoc = LSI->CaptureDefaultLoc;
2079 LambdaCaptureDefault CaptureDefault =
2082 CXXMethodDecl *CallOperator;
2083 SourceRange IntroducerRange;
2084 bool ExplicitParams;
2085 bool ExplicitResultType;
2086 CleanupInfo LambdaCleanup;
2087 bool ContainsUnexpandedParameterPack;
2088 bool IsGenericLambda;
2089 {
2090 CallOperator = LSI->CallOperator;
2091 Class = LSI->Lambda;
2092 IntroducerRange = LSI->IntroducerRange;
2093 ExplicitParams = LSI->ExplicitParams;
2094 ExplicitResultType = !LSI->HasImplicitReturnType;
2095 LambdaCleanup = LSI->Cleanup;
2096 ContainsUnexpandedParameterPack = LSI->ContainsUnexpandedParameterPack;
2097 IsGenericLambda = Class->isGenericLambda();
2098
2099 CallOperator->setLexicalDeclContext(Class);
2100 Decl *TemplateOrNonTemplateCallOperatorDecl =
2101 CallOperator->getDescribedFunctionTemplate()
2102 ? CallOperator->getDescribedFunctionTemplate()
2103 : cast<Decl>(CallOperator);
2104
2105 // FIXME: Is this really the best choice? Keeping the lexical decl context
2106 // set as CurContext seems more faithful to the source.
2107 TemplateOrNonTemplateCallOperatorDecl->setLexicalDeclContext(Class);
2108
2110
2111 // True if the current capture has a used capture or default before it.
2112 bool CurHasPreviousCapture = CaptureDefault != LCD_None;
2113 SourceLocation PrevCaptureLoc = CurHasPreviousCapture ?
2114 CaptureDefaultLoc : IntroducerRange.getBegin();
2115
2116 for (unsigned I = 0, N = LSI->Captures.size(); I != N; ++I) {
2117 const Capture &From = LSI->Captures[I];
2118
2119 if (From.isInvalid())
2120 return ExprError();
2121
2122 assert(!From.isBlockCapture() && "Cannot capture __block variables");
2123 bool IsImplicit = I >= LSI->NumExplicitCaptures;
2124 SourceLocation ImplicitCaptureLoc =
2125 IsImplicit ? CaptureDefaultLoc : SourceLocation();
2126
2127 // Use source ranges of explicit captures for fixits where available.
2128 SourceRange CaptureRange = LSI->ExplicitCaptureRanges[I];
2129
2130 // Warn about unused explicit captures.
2131 bool IsCaptureUsed = true;
2132 if (!CurContext->isDependentContext() && !IsImplicit &&
2133 !From.isODRUsed()) {
2134 // Initialized captures that are non-ODR used may not be eliminated.
2135 // FIXME: Where did the IsGenericLambda here come from?
2136 bool NonODRUsedInitCapture =
2137 IsGenericLambda && From.isNonODRUsed() && From.isInitCapture();
2138 if (!NonODRUsedInitCapture) {
2139 bool IsLast = (I + 1) == LSI->NumExplicitCaptures;
2140 SourceRange FixItRange;
2141 if (CaptureRange.isValid()) {
2142 if (!CurHasPreviousCapture && !IsLast) {
2143 // If there are no captures preceding this capture, remove the
2144 // following comma.
2145 FixItRange = SourceRange(CaptureRange.getBegin(),
2146 getLocForEndOfToken(CaptureRange.getEnd()));
2147 } else {
2148 // Otherwise, remove the comma since the last used capture.
2149 FixItRange = SourceRange(getLocForEndOfToken(PrevCaptureLoc),
2150 CaptureRange.getEnd());
2151 }
2152 }
2153
2154 IsCaptureUsed = !DiagnoseUnusedLambdaCapture(FixItRange, From);
2155 }
2156 }
2157
2158 if (CaptureRange.isValid()) {
2159 CurHasPreviousCapture |= IsCaptureUsed;
2160 PrevCaptureLoc = CaptureRange.getEnd();
2161 }
2162
2163 // Map the capture to our AST representation.
2164 LambdaCapture Capture = [&] {
2165 if (From.isThisCapture()) {
2166 // Capturing 'this' implicitly with a default of '[=]' is deprecated,
2167 // because it results in a reference capture. Don't warn prior to
2168 // C++2a; there's nothing that can be done about it before then.
2169 if (getLangOpts().CPlusPlus20 && IsImplicit &&
2170 CaptureDefault == LCD_ByCopy) {
2171 Diag(From.getLocation(), diag::warn_deprecated_this_capture);
2172 Diag(CaptureDefaultLoc, diag::note_deprecated_this_capture)
2174 getLocForEndOfToken(CaptureDefaultLoc), ", this");
2175 }
2176 return LambdaCapture(From.getLocation(), IsImplicit,
2178 } else if (From.isVLATypeCapture()) {
2179 return LambdaCapture(From.getLocation(), IsImplicit, LCK_VLAType);
2180 } else {
2181 assert(From.isVariableCapture() && "unknown kind of capture");
2182 ValueDecl *Var = From.getVariable();
2183 LambdaCaptureKind Kind =
2185 return LambdaCapture(From.getLocation(), IsImplicit, Kind, Var,
2186 From.getEllipsisLoc());
2187 }
2188 }();
2189
2190 // Form the initializer for the capture field.
2191 ExprResult Init = BuildCaptureInit(From, ImplicitCaptureLoc);
2192
2193 // FIXME: Skip this capture if the capture is not used, the initializer
2194 // has no side-effects, the type of the capture is trivial, and the
2195 // lambda is not externally visible.
2196
2197 // Add a FieldDecl for the capture and form its initializer.
2198 BuildCaptureField(Class, From);
2199 Captures.push_back(Capture);
2200 CaptureInits.push_back(Init.get());
2201
2202 if (LangOpts.CUDA)
2203 CUDA().CheckLambdaCapture(CallOperator, From);
2204 }
2205
2206 Class->setCaptures(Context, Captures);
2207
2208 // C++11 [expr.prim.lambda]p6:
2209 // The closure type for a lambda-expression with no lambda-capture
2210 // has a public non-virtual non-explicit const conversion function
2211 // to pointer to function having the same parameter and return
2212 // types as the closure type's function call operator.
2213 if (Captures.empty() && CaptureDefault == LCD_None)
2214 addFunctionPointerConversions(*this, IntroducerRange, Class,
2215 CallOperator);
2216
2217 // Objective-C++:
2218 // The closure type for a lambda-expression has a public non-virtual
2219 // non-explicit const conversion function to a block pointer having the
2220 // same parameter and return types as the closure type's function call
2221 // operator.
2222 // FIXME: Fix generic lambda to block conversions.
2223 if (getLangOpts().Blocks && getLangOpts().ObjC && !IsGenericLambda)
2224 addBlockPointerConversion(*this, IntroducerRange, Class, CallOperator);
2225
2226 // Finalize the lambda class.
2227 SmallVector<Decl*, 4> Fields(Class->fields());
2228 ActOnFields(nullptr, Class->getLocation(), Class, Fields, SourceLocation(),
2230 CheckCompletedCXXClass(nullptr, Class);
2231 }
2232
2233 Cleanup.mergeFrom(LambdaCleanup);
2234
2235 LambdaExpr *Lambda = LambdaExpr::Create(Context, Class, IntroducerRange,
2236 CaptureDefault, CaptureDefaultLoc,
2237 ExplicitParams, ExplicitResultType,
2238 CaptureInits, EndLoc,
2239 ContainsUnexpandedParameterPack);
2240 // If the lambda expression's call operator is not explicitly marked constexpr
2241 // and we are not in a dependent context, analyze the call operator to infer
2242 // its constexpr-ness, suppressing diagnostics while doing so.
2243 if (getLangOpts().CPlusPlus17 && !CallOperator->isInvalidDecl() &&
2244 !CallOperator->isConstexpr() &&
2245 !isa<CoroutineBodyStmt>(CallOperator->getBody()) &&
2246 !Class->getDeclContext()->isDependentContext()) {
2247 CallOperator->setConstexprKind(
2252 }
2253
2254 // Emit delayed shadowing warnings now that the full capture list is known.
2256
2258 switch (ExprEvalContexts.back().Context) {
2259 // C++11 [expr.prim.lambda]p2:
2260 // A lambda-expression shall not appear in an unevaluated operand
2261 // (Clause 5).
2265 // C++1y [expr.const]p2:
2266 // A conditional-expression e is a core constant expression unless the
2267 // evaluation of e, following the rules of the abstract machine, would
2268 // evaluate [...] a lambda-expression.
2269 //
2270 // This is technically incorrect, there are some constant evaluated contexts
2271 // where this should be allowed. We should probably fix this when DR1607 is
2272 // ratified, it lays out the exact set of conditions where we shouldn't
2273 // allow a lambda-expression.
2276 // We don't actually diagnose this case immediately, because we
2277 // could be within a context where we might find out later that
2278 // the expression is potentially evaluated (e.g., for typeid).
2279 ExprEvalContexts.back().Lambdas.push_back(Lambda);
2280 break;
2281
2285 break;
2286 }
2287 }
2288
2289 return MaybeBindToTemporary(Lambda);
2290}
2291
2293 SourceLocation ConvLocation,
2294 CXXConversionDecl *Conv,
2295 Expr *Src) {
2296 // Make sure that the lambda call operator is marked used.
2297 CXXRecordDecl *Lambda = Conv->getParent();
2298 CXXMethodDecl *CallOperator
2299 = cast<CXXMethodDecl>(
2300 Lambda->lookup(
2302 CallOperator->setReferenced();
2303 CallOperator->markUsed(Context);
2304
2307 CurrentLocation, Src);
2308 if (!Init.isInvalid())
2309 Init = ActOnFinishFullExpr(Init.get(), /*DiscardedValue*/ false);
2310
2311 if (Init.isInvalid())
2312 return ExprError();
2313
2314 // Create the new block to be returned.
2316
2317 // Set the type information.
2318 Block->setSignatureAsWritten(CallOperator->getTypeSourceInfo());
2319 Block->setIsVariadic(CallOperator->isVariadic());
2320 Block->setBlockMissingReturnType(false);
2321
2322 // Add parameters.
2324 for (unsigned I = 0, N = CallOperator->getNumParams(); I != N; ++I) {
2325 ParmVarDecl *From = CallOperator->getParamDecl(I);
2326 BlockParams.push_back(ParmVarDecl::Create(
2327 Context, Block, From->getBeginLoc(), From->getLocation(),
2328 From->getIdentifier(), From->getType(), From->getTypeSourceInfo(),
2329 From->getStorageClass(),
2330 /*DefArg=*/nullptr));
2331 }
2332 Block->setParams(BlockParams);
2333
2334 Block->setIsConversionFromLambda(true);
2335
2336 // Add capture. The capture uses a fake variable, which doesn't correspond
2337 // to any actual memory location. However, the initializer copy-initializes
2338 // the lambda object.
2339 TypeSourceInfo *CapVarTSI =
2341 VarDecl *CapVar = VarDecl::Create(Context, Block, ConvLocation,
2342 ConvLocation, nullptr,
2343 Src->getType(), CapVarTSI,
2344 SC_None);
2345 BlockDecl::Capture Capture(/*variable=*/CapVar, /*byRef=*/false,
2346 /*nested=*/false, /*copy=*/Init.get());
2347 Block->setCaptures(Context, Capture, /*CapturesCXXThis=*/false);
2348
2349 // Add a fake function body to the block. IR generation is responsible
2350 // for filling in the actual body, which cannot be expressed as an AST.
2351 Block->setBody(new (Context) CompoundStmt(ConvLocation));
2352
2353 // Create the block literal expression.
2354 Expr *BuildBlock = new (Context) BlockExpr(Block, Conv->getConversionType());
2355 ExprCleanupObjects.push_back(Block);
2357
2358 return BuildBlock;
2359}
2360
2365 return FD;
2366 }
2367
2369 return FD->getInstantiatedFromDecl();
2370
2372 if (!FTD)
2373 return nullptr;
2374
2377
2378 return FTD->getTemplatedDecl();
2379}
2380
2384 LocalInstantiationScope &Scope, bool ShouldAddDeclsFromParentScope)
2385 : FunctionScopeRAII(SemaRef) {
2386 if (!isLambdaCallOperator(FD)) {
2388 return;
2389 }
2390
2391 SemaRef.RebuildLambdaScopeInfo(cast<CXXMethodDecl>(FD));
2392
2393 FunctionDecl *FDPattern = getPatternFunctionDecl(FD);
2394 if (!FDPattern)
2395 return;
2396
2397 if (!ShouldAddDeclsFromParentScope)
2398 return;
2399
2400 FunctionDecl *InnermostFD = FD, *InnermostFDPattern = FDPattern;
2402 ParentInstantiations;
2403 while (true) {
2404 FDPattern =
2405 dyn_cast<FunctionDecl>(getLambdaAwareParentOfDeclContext(FDPattern));
2406 FD = dyn_cast<FunctionDecl>(getLambdaAwareParentOfDeclContext(FD));
2407
2408 if (!FDPattern || !FD)
2409 break;
2410
2411 ParentInstantiations.emplace_back(FDPattern, FD);
2412 }
2413
2414 // Add instantiated parameters and local vars to scopes, starting from the
2415 // outermost lambda to the innermost lambda. This ordering ensures that
2416 // parameters in inner lambdas can correctly depend on those defined
2417 // in outer lambdas, e.g. auto L = [](auto... x) {
2418 // return [](decltype(x)... y) { }; // `y` depends on `x`
2419 // };
2420
2421 for (const auto &[FDPattern, FD] : llvm::reverse(ParentInstantiations)) {
2422 SemaRef.addInstantiatedParametersToScope(FD, FDPattern, Scope, MLTAL);
2423 SemaRef.addInstantiatedLocalVarsToScope(FD, FDPattern, Scope);
2424
2425 if (isLambdaCallOperator(FD))
2426 SemaRef.addInstantiatedCapturesToScope(FD, FDPattern, Scope, MLTAL);
2427 }
2428
2429 SemaRef.addInstantiatedCapturesToScope(InnermostFD, InnermostFDPattern, Scope,
2430 MLTAL);
2431}
#define V(N, I)
Definition: ASTContext.h:3341
This file provides some common utility functions for processing Lambda related AST Constructs.
StringRef P
const Decl * D
IndirectLocalPath & Path
Expr * E
Defines the clang::Expr interface and subclasses for C++ expressions.
uint32_t Id
Definition: SemaARM.cpp:1144
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,...
Definition: SemaLambda.cpp:571
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...
Definition: SemaLambda.cpp:643
static TypeSourceInfo * getLambdaType(Sema &S, LambdaIntroducer &Intro, Declarator &ParamInfo, Scope *CurScope, SourceLocation Loc, bool &ExplicitResultType)
Definition: SemaLambda.cpp:917
static std::optional< unsigned > getStackIndexOfNearestEnclosingCaptureReadyLambda(ArrayRef< const clang::sema::FunctionScopeInfo * > FunctionScopes, ValueDecl *VarToCapture)
Examines the FunctionScopeInfo stack to determine the nearest enclosing lambda (to the current lambda...
Definition: SemaLambda.cpp:69
static FunctionDecl * getPatternFunctionDecl(FunctionDecl *FD)
static LambdaScopeInfo * getCurrentLambdaScopeUnsafe(Sema &S)
Definition: SemaLambda.cpp:885
static void adjustBlockReturnsToEnum(Sema &S, ArrayRef< ReturnStmt * > returns, QualType returnType)
Adjust the given return statements so that they formally return the given type.
Definition: SemaLambda.cpp:664
static TemplateParameterList * getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef)
Definition: SemaLambda.cpp:235
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)
Definition: SemaLambda.cpp:509
static TypeSourceInfo * getDummyLambdaType(Sema &S, SourceLocation Loc=SourceLocation())
Definition: SemaLambda.cpp:891
static QualType buildTypeForLambdaCallOperator(Sema &S, clang::CXXRecordDecl *Class, TemplateParameterList *TemplateParams, TypeSourceInfo *MethodTypeInfo)
Definition: SemaLambda.cpp:365
static bool isInInlineFunction(const DeclContext *DC)
Determine whether the given context is or is enclosed in an inline function.
Definition: SemaLambda.cpp:269
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.
SourceRange Range
Definition: SemaObjC.cpp:758
SourceLocation Loc
Definition: SemaObjC.cpp:759
This file declares semantic analysis for OpenMP constructs and clauses.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:187
TranslationUnitDecl * getTranslationUnitDecl() const
Definition: ASTContext.h:1101
CanQualType getCanonicalFunctionResultType(QualType ResultType) const
Adjust the given function result type.
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
DeclarationNameTable DeclarationNames
Definition: ASTContext.h:664
QualType getRecordType(const RecordDecl *Decl) const
QualType getPackExpansionType(QualType Pattern, std::optional< unsigned > NumExpansions, bool ExpectPackInType=true)
Form a pack expansion type with the given pattern.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
Definition: ASTContext.h:2628
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Definition: ASTContext.h:2644
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType DependentTy
Definition: ASTContext.h:1147
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
Definition: ASTContext.h:1637
IdentifierTable & Idents
Definition: ASTContext.h:660
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location,...
llvm::DenseMap< const CXXMethodDecl *, CXXCastPath > LambdaCastPaths
For capturing lambdas with an explicit object parameter whose type is derived from the lambda type,...
Definition: ASTContext.h:1209
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
CanQualType VoidTy
Definition: ASTContext.h:1119
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
Definition: ASTContext.h:1615
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:779
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
ExternalASTSource * getExternalSource() const
Retrieve a pointer to the external AST source associated with this AST context, if any.
Definition: ASTContext.h:1227
PtrTy get() const
Definition: Ownership.h:170
Attr - This represents one attribute.
Definition: Attr.h:42
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3860
A binding in a decomposition declaration.
Definition: DeclCXX.h:4111
A class which contains all the information about a particular captured value.
Definition: Decl.h:4477
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition: Decl.h:4471
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Definition: Decl.cpp:5415
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition: Expr.h:6365
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
Represents a C++ conversion function within a class.
Definition: DeclCXX.h:2866
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, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2928
QualType getConversionType() const
Returns the type that this conversion function is converting to.
Definition: DeclCXX.h:2906
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2064
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:2500
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2190
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, Expr *TrailingRequiresClause=nullptr)
Definition: DeclCXX.cpp:2312
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
void setLambdaTypeInfo(TypeSourceInfo *TS)
Definition: DeclCXX.h:1870
void setLambdaIsGeneric(bool IsGeneric)
Definition: DeclCXX.h:1881
static CXXRecordDecl * CreateLambda(const ASTContext &C, DeclContext *DC, TypeSourceInfo *Info, SourceLocation Loc, unsigned DependencyKind, bool IsGeneric, LambdaCaptureDefault CaptureDefault)
Definition: DeclCXX.cpp:148
bool isCapturelessLambda() const
Definition: DeclCXX.h:1069
Represents a C++ nested-name-specifier or a global scope specifier.
Definition: DeclSpec.h:74
void mergeFrom(CleanupInfo Rhs)
Definition: CleanupInfo.h:38
void setExprNeedsCleanups(bool SideEffects)
Definition: CleanupInfo.h:28
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1611
ConditionalOperator - The ?: ternary operator.
Definition: Expr.h:4213
reference front() const
Definition: DeclBase.h:1392
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
Definition: DeclBase.h:1436
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2090
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC.
Definition: DeclBase.h:2219
bool isFileContext() const
Definition: DeclBase.h:2161
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Definition: DeclBase.cpp:1333
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
Definition: DeclBase.h:2106
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
Definition: DeclBase.cpp:1852
bool isTranslationUnit() const
Definition: DeclBase.h:2166
bool isRecord() const
Definition: DeclBase.h:2170
void addDecl(Decl *D)
Add the declaration D into this context.
Definition: DeclBase.cpp:1766
bool isFunctionOrMethod() const
Definition: DeclBase.h:2142
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:1265
Captures information about "declaration specifiers".
Definition: DeclSpec.h:247
SCS getStorageClassSpec() const
Definition: DeclSpec.h:501
bool SetTypeQual(TQ T, SourceLocation Loc)
Definition: DeclSpec.cpp:1020
ConstexprSpecKind getConstexprSpecifier() const
Definition: DeclSpec.h:832
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
void addAttr(Attr *A)
Definition: DeclBase.cpp:1013
bool isParameterPack() const
Whether this declaration is a parameter pack.
Definition: DeclBase.cpp:242
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
Definition: DeclBase.cpp:154
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Definition: DeclBase.cpp:567
bool isTemplated() const
Determine whether this declaration is a templated entity (whether it is.
Definition: DeclBase.cpp:284
bool isInvalidDecl() const
Definition: DeclBase.h:595
void setAccess(AccessSpecifier AS)
Definition: DeclBase.h:509
SourceLocation getLocation() const
Definition: DeclBase.h:446
void setImplicit(bool I=true)
Definition: DeclBase.h:601
void setReferenced(bool R=true)
Definition: DeclBase.h:630
void setLocation(SourceLocation L)
Definition: DeclBase.h:447
DeclContext * getDeclContext()
Definition: DeclBase.h:455
DeclContext * getLexicalDeclContext()
getLexicalDeclContext - The declaration context where this Decl was lexically declared (LexicalDC).
Definition: DeclBase.h:908
void setLexicalDeclContext(DeclContext *DC)
Definition: DeclBase.cpp:362
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.
DeclarationName getCXXOperatorName(OverloadedOperatorKind Op)
Get the name of the overloadable C++ operator corresponding to Op.
The name of a declaration.
void setInnerLocStart(SourceLocation L)
Definition: Decl.h:775
SourceLocation getBeginLoc() const LLVM_READONLY
Definition: Decl.h:783
void setTypeSourceInfo(TypeSourceInfo *TI)
Definition: Decl.h:766
void setTrailingRequiresClause(Expr *TrailingRequiresClause)
Definition: Decl.cpp:2001
Expr * getTrailingRequiresClause()
Get the constraint-expression introduced by the trailing requires-clause in the function/member decla...
Definition: Decl.h:807
TypeSourceInfo * getTypeSourceInfo() const
Definition: Decl.h:760
Information about one declarator, including the parsed type information and the identifier.
Definition: DeclSpec.h:1903
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
Definition: DeclSpec.h:2459
const DeclaratorChunk & getTypeObject(unsigned i) const
Return the specified TypeInfo from this declarator.
Definition: DeclSpec.h:2401
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
Definition: DeclSpec.h:2050
Expr * getTrailingRequiresClause()
Sets a trailing requires clause for this declarator.
Definition: DeclSpec.h:2636
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
Definition: DeclSpec.h:2397
bool isExplicitObjectMemberFunction()
Definition: DeclSpec.cpp:427
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
Definition: DeclSpec.h:2085
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
Definition: DeclSpec.h:2490
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
Definition: Type.h:6341
An instance of this object exists for each enum constant that is defined.
Definition: Decl.h:3274
Represents an enum.
Definition: Decl.h:3844
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5991
Store information needed for an explicit specifier.
Definition: DeclCXX.h:1901
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition: ExprCXX.h:3473
This represents one expression.
Definition: Expr.h:110
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3066
QualType getType() const
Definition: Expr.h:142
Represents difference between two FPOptions values.
Definition: LangOptions.h:947
bool isFPConstrained() const
Definition: LangOptions.h:875
Represents a member of a struct/union/class.
Definition: Decl.h:3030
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:4531
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
Definition: Diagnostic.h:123
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:97
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:1062
const Expr * getSubExpr() const
Definition: Expr.h:1057
Represents a function declaration or definition.
Definition: Decl.h:1932
const ParmVarDecl * getParamDecl(unsigned i) const
Definition: Decl.h:2669
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3224
ConstexprSpecKind getConstexprKind() const
Definition: Decl.h:2401
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
Definition: Decl.cpp:4033
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition: Decl.cpp:4028
QualType getReturnType() const
Definition: Decl.h:2717
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2646
FunctionTemplateDecl * getPrimaryTemplate() const
Retrieve the primary template that this function template specialization either specializes or was in...
Definition: Decl.cpp:4148
bool isVariadic() const
Whether this function is variadic.
Definition: Decl.cpp:3077
@ TK_MemberSpecialization
Definition: Decl.h:1944
@ TK_DependentNonTemplate
Definition: Decl.h:1953
TemplatedKind getTemplatedKind() const
What kind of templated function this is.
Definition: Decl.cpp:3979
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition: Decl.h:2395
bool isImmediateEscalating() const
Definition: Decl.cpp:3256
FunctionDecl * getInstantiatedFromDecl() const
Definition: Decl.cpp:4052
void setConstexprKind(ConstexprSpecKind CSK)
Definition: Decl.h:2398
bool isConsteval() const
Definition: Decl.h:2407
void setStorageClass(StorageClass SClass)
Sets the storage class as written in the source.
Definition: Decl.h:2765
FunctionDecl * getInstantiatedFromMemberFunction() const
If this function is an instantiation of a member function of a class template specialization,...
Definition: Decl.cpp:4000
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3678
void setParams(ArrayRef< ParmVarDecl * > NewParamInfo)
Definition: Decl.h:2677
Represents a prototype with parameter type info, e.g.
Definition: Type.h:5002
bool isVariadic() const
Whether this function prototype is variadic.
Definition: Type.h:5379
ExtProtoInfo getExtProtoInfo() const
Definition: Type.h:5266
ArrayRef< QualType > getParamTypes() const
Definition: Type.h:5262
Declaration of a template function.
Definition: DeclTemplate.h:957
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:1509
ExtInfo withCallingConv(CallingConv cc) const
Definition: Type.h:4534
CallingConv getCallConv() const
Definition: Type.h:4641
QualType getReturnType() const
Definition: Type.h:4630
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:3675
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat, FPOptionsOverride FPO)
Definition: Expr.cpp:2074
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)
Describes the sequence of initializations required to initialize a given object or reference with a s...
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.
Definition: SemaInit.cpp:7521
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.
Definition: LambdaCapture.h:25
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1954
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:1294
A stack-allocated class that identifies which local variable declaration instantiations are present i...
Definition: Template.h:365
Represents the results of name lookup.
Definition: Lookup.h:46
DeclClass * getAsSingle() const
Definition: Lookup.h:558
bool empty() const
Return true if no decls were found.
Definition: Lookup.h:362
bool isAmbiguous() const
Definition: Lookup.h:324
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:249
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition: Decl.h:270
bool isPlaceholderVar(const LangOptions &LangOpts) const
Definition: Decl.cpp:1089
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition: Decl.h:315
PtrTy get() const
Definition: Ownership.h:80
Represents a pack expansion of types.
Definition: Type.h:6960
Expr ** getExprs()
Definition: Expr.h:5856
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Definition: Expr.h:5845
Represents a parameter to a function.
Definition: Decl.h:1722
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:2903
Wrapper for source info for pointers.
Definition: TypeLoc.h:1301
A (possibly-)qualified type.
Definition: Type.h:941
QualType getDesugaredType(const ASTContext &Context) const
Return the specified type with any "sugar" removed from the type.
Definition: Type.h:1303
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
LangAS getAddressSpace() const
Return the address space of this type.
Definition: Type.h:7876
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition: Type.h:7951
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition: Type.h:7844
The collection of all-type qualifiers we support.
Definition: Type.h:319
void addAddressSpace(LangAS space)
Definition: Type.h:584
void addConst()
Definition: Type.h:447
Represents a struct/union/class.
Definition: Decl.h:4145
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3029
void setRetValue(Expr *E)
Definition: Stmt.h:3062
SourceLocation getBeginLoc() const
Definition: Stmt.h:3086
Expr * getRetValue()
Definition: Stmt.h:3060
Scope - A scope is a transient data structure that is used while parsing the program.
Definition: Scope.h:41
const Scope * getParent() const
getParent - Return the scope that this is nested in.
Definition: Scope.h:270
Scope * getTemplateParamParent()
Definition: Scope.h:315
SemaDiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID, bool DeferHint=false)
Emit a diagnostic.
Definition: SemaBase.cpp:60
Sema & SemaRef
Definition: SemaBase.h:40
void CheckLambdaCapture(CXXMethodDecl *D, const sema::Capture &Capture)
Definition: SemaCUDA.cpp:952
void SetLambdaAttrs(CXXMethodDecl *Method)
Set device or host device attributes on the given lambda operator() method.
Definition: SemaCUDA.cpp:997
void ActOnFinishedFunctionDefinitionInOpenMPAssumeScope(Decl *D)
Act on D, a function definition inside of an omp [begin/end] assumes.
A RAII object to temporarily push a declaration context.
Definition: Sema.h:3023
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:493
Attr * getImplicitCodeSegOrSectionAttrForFunction(const FunctionDecl *FD, bool IsDefinition)
Returns an implicit CodeSegAttr if a __declspec(code_seg) is found on a containing class.
Definition: SemaDecl.cpp:10917
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:763
bool DiagnoseEmptyLookup(Scope *S, CXXScopeSpec &SS, LookupResult &R, CorrectionCandidateCallback &CCC, TemplateArgumentListInfo *ExplicitTemplateArgs=nullptr, ArrayRef< Expr * > Args=std::nullopt, DeclContext *LookupCtx=nullptr, TypoExpr **Out=nullptr)
Diagnose an empty lookup.
Definition: SemaExpr.cpp:2446
ExprResult CreateBuiltinUnaryOp(SourceLocation OpLoc, UnaryOperatorKind Opc, Expr *InputExpr, bool IsAfterAmp=false)
Definition: SemaExpr.cpp:15288
void BuildBasePathArray(const CXXBasePaths &Paths, CXXCastPath &BasePath)
bool RequireCompleteSizedType(SourceLocation Loc, QualType T, unsigned DiagID, const Ts &...Args)
Definition: Sema.h:7873
@ LookupOrdinaryName
Ordinary name lookup, which finds ordinary names (functions, variables, typedefs, etc....
Definition: Sema.h:9015
QualType deduceVarTypeFromInitializer(VarDecl *VDecl, DeclarationName Name, QualType Type, TypeSourceInfo *TSI, SourceRange Range, bool DirectInit, Expr *Init)
Definition: SemaDecl.cpp:12822
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...
Definition: SemaLambda.cpp:850
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:1179
ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, sema::LambdaScopeInfo *LSI)
Complete a lambda-expression having processed and attached the lambda body.
CXXRecordDecl * createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info, unsigned LambdaDependencyKind, LambdaCaptureDefault CaptureDefault)
Create a new lambda closure type.
Definition: SemaLambda.cpp:249
SemaCUDA & CUDA()
Definition: Sema.h:1124
void PushExpressionEvaluationContext(ExpressionEvaluationContext NewContext, Decl *LambdaContextDecl=nullptr, ExpressionEvaluationContextRecord::ExpressionKind Type=ExpressionEvaluationContextRecord::EK_Other)
Definition: SemaExpr.cpp:17182
SmallVector< sema::FunctionScopeInfo *, 4 > FunctionScopes
Stack containing information about each of the nested function, block, and method scopes that are cur...
Definition: Sema.h:900
PoppedFunctionScopePtr PopFunctionScopeInfo(const sema::AnalysisBasedWarnings::Policy *WP=nullptr, const Decl *D=nullptr, QualType BlockType=QualType())
Pop a function (or block or lambda or captured region) scope from the stack.
Definition: Sema.cpp:2296
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)
Definition: SemaLambda.cpp:998
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...
Definition: SemaAttr.cpp:1162
void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var, bool ByRef)
Add an init-capture to a lambda scope.
Definition: SemaLambda.cpp:876
FieldDecl * BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture)
Build a FieldDecl suitable to hold the given capture.
sema::LambdaScopeInfo * RebuildLambdaScopeInfo(CXXMethodDecl *CallOperator)
Definition: SemaDecl.cpp:15389
ASTContext & Context
Definition: Sema.h:962
SemaObjC & ObjC()
Definition: Sema.h:1164
void PushOnScopeChains(NamedDecl *D, Scope *S, bool AddToContext=true)
Add this decl to the scope shadowed decl chains.
Definition: SemaDecl.cpp:1496
ASTContext & getASTContext() const
Definition: Sema.h:560
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.
Definition: SemaExpr.cpp:18696
void PopExpressionEvaluationContext()
Definition: SemaExpr.cpp:17603
std::string getAmbiguousPathsDisplayString(CXXBasePaths &Paths)
Builds a string representing ambiguous paths from a specific derived class to different subobjects of...
sema::LambdaScopeInfo * getCurGenericLambda()
Retrieve the current generic lambda info, if any.
Definition: Sema.cpp:2434
void handleLambdaNumbering(CXXRecordDecl *Class, CXXMethodDecl *Method, std::optional< CXXRecordDecl::LambdaNumbering > NumberingOverride=std::nullopt)
Number lambda for linkage purposes if necessary.
Definition: SemaLambda.cpp:456
LangAS getDefaultCXXMethodAddrSpace() const
Returns default addr space for method qualifiers.
Definition: Sema.cpp:1586
ExprResult BuildCaptureInit(const sema::Capture &Capture, SourceLocation ImplicitCaptureLoc, bool IsOpenMPMapping=false)
Initialize the given capture with a suitable expression.
FPOptions & getCurFPFeatures()
Definition: Sema.h:555
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Calls Lexer::getLocForEndOfToken()
Definition: Sema.cpp:84
@ UPPC_Initializer
An initializer.
Definition: Sema.h:13923
@ UPPC_DeclarationType
The type of an arbitrary declaration.
Definition: Sema.h:13896
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.
Definition: SemaLambda.cpp:523
const LangOptions & getLangOpts() const
Definition: Sema.h:553
bool CaptureHasSideEffects(const sema::Capture &From)
Does copying/destroying the captured variable have side effects?
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 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:960
sema::LambdaScopeInfo * getCurLambda(bool IgnoreNonLambdaCapturingScope=false)
Retrieve the current lambda scope info, if any.
Definition: Sema.cpp:2409
bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, const sema::Capture &From)
Diagnose if an explicit lambda capture is unused.
QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, std::optional< unsigned > NumExpansions, IdentifierInfo *Id, bool DirectInit, Expr *&Init)
Definition: SemaLambda.cpp:784
void CheckCXXDefaultArguments(FunctionDecl *FD)
Helpers for dealing with blocks and functions.
CleanupInfo Cleanup
Used to control the generation of ExprWithCleanups.
Definition: Sema.h:6487
void DiagnoseShadowingLambdaDecls(const sema::LambdaScopeInfo *LSI)
Diagnose shadowing for variables shadowed in the lambda record LambdaRD when these variables are capt...
Definition: SemaDecl.cpp:8314
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.
Definition: SemaType.cpp:1844
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R, bool NeedsADL, bool AcceptInvalidDecl=false)
Definition: SemaExpr.cpp:3175
void DiagPlaceholderVariableDefinition(SourceLocation Loc)
DeclContext * CurContext
CurContext - This is the current declaration context of parsing.
Definition: Sema.h:1097
bool inTemplateInstantiation() const
Determine whether we are currently performing template instantiation.
Definition: Sema.h:13490
TryCaptureKind
Definition: Sema.h:6613
@ TryCapture_Implicit
Definition: Sema.h:6614
@ TryCapture_ExplicitByVal
Definition: Sema.h:6615
@ TryCapture_ExplicitByRef
Definition: Sema.h:6616
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...
Definition: SemaLambda.cpp:545
Decl * ActOnFinishFunctionBody(Decl *Decl, Stmt *Body)
Definition: SemaDecl.cpp:15745
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 DiagnoseUseOfDecl(NamedDecl *D, ArrayRef< SourceLocation > Locs, const ObjCInterfaceDecl *UnknownObjCClass=nullptr, bool ObjCPropertyAccess=false, bool AvoidPartialAvailabilityChecks=false, ObjCInterfaceDecl *ClassReciever=nullptr, bool SkipTrailingRequiresClause=false)
Determine whether the use of this declaration is valid, and emit any corresponding diagnostics.
Definition: SemaExpr.cpp:216
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.
Definition: SemaDecl.cpp:8198
@ Normal
A normal translation unit fragment.
Definition: Sema.h:650
SmallVector< ExprWithCleanups::CleanupObject, 8 > ExprCleanupObjects
ExprCleanupObjects - This is the stack of objects requiring cleanup that are created by the current f...
Definition: Sema.h:6491
@ UnevaluatedAbstract
The current expression occurs within an unevaluated operand that unconditionally permits abstract ref...
@ UnevaluatedList
The current expression occurs within a braced-init-list within an unevaluated operand.
@ ConstantEvaluated
The current context is "potentially evaluated" in C++11 terms, but the expression is evaluated at com...
@ DiscardedStatement
The current expression occurs within a discarded statement.
@ PotentiallyEvaluated
The current expression is potentially evaluated at run time, which means that code may be generated t...
@ Unevaluated
The current expression and its subexpressions occur within an unevaluated operand (C++11 [expr]p7),...
@ ImmediateFunctionContext
In addition of being constant evaluated, the current expression occurs in an immediate function conte...
@ PotentiallyEvaluatedIfUsed
The current expression is potentially evaluated, but any declarations referenced inside that expressi...
TypeSourceInfo * GetTypeForDeclarator(Declarator &D)
GetTypeForDeclarator - Convert the type for the specified declarator to Type instances.
Definition: SemaType.cpp:5653
bool RequireCompleteType(SourceLocation Loc, QualType T, CompleteTypeKind Kind, TypeDiagnoser &Diagnoser)
Ensure that the type T is a complete type.
Definition: SemaType.cpp:8907
void ActOnFields(Scope *S, SourceLocation RecLoc, Decl *TagDecl, ArrayRef< Decl * > Fields, SourceLocation LBrac, SourceLocation RBrac, const ParsedAttributesView &AttrList)
Definition: SemaDecl.cpp:18865
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()
Definition: SemaExpr.cpp:17681
SmallVector< ExpressionEvaluationContextRecord, 8 > ExprEvalContexts
A stack of expression evaluation contexts.
Definition: Sema.h:7946
void PushDeclContext(Scope *S, DeclContext *DC)
Set the current declaration context until it gets popped.
Definition: SemaDecl.cpp:1307
CXXMethodDecl * CreateLambdaCallOperator(SourceRange IntroducerRange, CXXRecordDecl *Class)
Definition: SemaLambda.cpp:973
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI)
Deduce a block or lambda's return type based on the return statements present in the body.
Definition: SemaLambda.cpp:691
ExprResult PerformCopyInitialization(const InitializedEntity &Entity, SourceLocation EqualLoc, ExprResult Init, bool TopLevelOfInitList=false, bool AllowExplicit=false)
Definition: SemaInit.cpp:9655
void PopDeclContext()
Definition: SemaDecl.cpp:1314
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)
std::tuple< MangleNumberingContext *, Decl * > getCurrentMangleNumberContext(const DeclContext *DC)
Compute the mangling number context for a lambda expression or block literal.
Definition: SemaLambda.cpp:282
void CompleteLambdaCallOperator(CXXMethodDecl *Method, SourceLocation LambdaLoc, SourceLocation CallOperatorLoc, Expr *TrailingRequiresClause, TypeSourceInfo *MethodTyInfo, ConstexprSpecKind ConstexprKind, StorageClass SC, ArrayRef< ParmVarDecl * > Params, bool HasExplicitResultType)
void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI)
Note that we have finished the explicit captures for the given lambda.
Definition: SemaLambda.cpp:541
bool IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base)
Determine whether the type Derived is a C++ class that is derived from the type Base.
@ CheckValid
Identify whether this function satisfies the formal rules for constexpr functions in the current lanu...
bool DiagnoseInvalidExplicitObjectParameterInLambda(CXXMethodDecl *Method, SourceLocation CallLoc)
Returns true if the explicit object parameter was invalid.
Definition: SemaLambda.cpp:393
bool LookupName(LookupResult &R, Scope *S, bool AllowBuiltinCreation=false, bool ForceNoCPlusPlus=false)
Perform unqualified name lookup starting from a given scope.
void NoteTemplateParameterLocation(const NamedDecl &Decl)
ExprResult ActOnFinishFullExpr(Expr *Expr, bool DiscardedValue)
Definition: Sema.h:8293
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
A trivial tuple used to represent a source range.
SourceLocation getEnd() const
SourceLocation getBegin() const
bool isValid() const
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:4417
Stmt - This represents one statement.
Definition: Stmt.h:84
SourceLocation getEndLoc() const LLVM_READONLY
Definition: Stmt.cpp:350
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type?
Definition: Decl.h:3785
Exposes information about the current target.
Definition: TargetInfo.h:218
virtual CallingConvCheckResult checkCallingConvention(CallingConv CC) const
Determines whether a given calling convention is valid for the target.
Definition: TargetInfo.h:1694
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
Definition: DeclTemplate.h:413
Stores a list of template parameters for a TemplateDecl and its derived classes.
Definition: DeclTemplate.h:73
bool containsUnexpandedParameterPack() const
Determine whether this template parameter list contains an unexpanded parameter pack.
ArrayRef< NamedDecl * > asArray()
Definition: DeclTemplate.h:139
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: Type.h:7721
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
Definition: TypeLoc.h:256
QualType getType() const
Return the type wrapped by this type source info.
Definition: Type.h:7732
void setNameLoc(SourceLocation Loc)
Definition: TypeLoc.h:539
The base class of the type hierarchy.
Definition: Type.h:1829
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1882
bool isVoidType() const
Definition: Type.h:8319
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
Definition: Type.cpp:2071
CanQualType getCanonicalTypeUnqualified() const
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8607
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2695
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
Definition: Type.h:2354
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition: Type.h:8490
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
Definition: Type.h:8453
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types,...
Definition: Type.cpp:2362
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8540
std::optional< NullabilityKind > getNullability() const
Determine the nullability of the given type.
Definition: Type.cpp:4693
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:667
void setType(QualType newType)
Definition: Decl.h:679
QualType getType() const
Definition: Decl.h:678
VarDecl * getPotentiallyDecomposedVarDecl()
Definition: DeclCXX.cpp:3339
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.cpp:5370
Represents a variable declaration or definition.
Definition: Decl.h:879
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, const IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
Definition: Decl.cpp:2133
void setInitStyle(InitializationStyle Style)
Definition: Decl.h:1393
void setInitCapture(bool IC)
Definition: Decl.h:1522
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition: Decl.h:1519
InitializationStyle
Initialization styles.
Definition: Decl.h:882
@ ListInit
Direct list-initialization (C++11)
Definition: Decl.h:890
@ CInit
C-style initialization with assignment.
Definition: Decl.h:884
@ CallInit
Call-style initialization (C++98)
Definition: Decl.h:887
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition: Decl.h:1132
void setInit(Expr *I)
Definition: Decl.cpp:2442
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition: Decl.h:1116
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack.
Definition: Decl.cpp:2651
ValueDecl * getVariable() const
Definition: ScopeInfo.h:675
bool isVariableCapture() const
Definition: ScopeInfo.h:650
bool isBlockCapture() const
Definition: ScopeInfo.h:656
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
Definition: ScopeInfo.h:686
bool isNonODRUsed() const
Definition: ScopeInfo.h:667
bool isODRUsed() const
Definition: ScopeInfo.h:666
bool isInitCapture() const
Determine whether this capture is an init-capture.
Definition: ScopeInfo.cpp:223
bool isInvalid() const
Definition: ScopeInfo.h:661
bool isVLATypeCapture() const
Definition: ScopeInfo.h:657
SourceLocation getEllipsisLoc() const
Retrieve the source location of the ellipsis, whose presence indicates that the capture is a pack exp...
Definition: ScopeInfo.h:690
bool isThisCapture() const
Definition: ScopeInfo.h:649
QualType getCaptureType() const
Retrieve the capture type for this capture, which is effectively the type of the non-static data memb...
Definition: ScopeInfo.h:695
bool isCopyCapture() const
Definition: ScopeInfo.h:654
const VariableArrayType * getCapturedVLAType() const
Definition: ScopeInfo.h:680
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
Definition: ScopeInfo.h:729
bool isCaptured(ValueDecl *Var) const
Determine whether the given variable has been captured.
Definition: ScopeInfo.h:758
SmallVector< Capture, 4 > Captures
Captures - The captures.
Definition: ScopeInfo.h:721
ImplicitCaptureStyle ImpCaptureStyle
Definition: ScopeInfo.h:708
Capture & getCXXThisCapture()
Retrieve the capture of C++ 'this', if it has been captured.
Definition: ScopeInfo.h:752
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
Definition: ScopeInfo.h:749
void addCapture(ValueDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Definition: ScopeInfo.h:731
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:214
SourceLocation PotentialThisCaptureLocation
Definition: ScopeInfo.h:950
void finishedExplicitCaptures()
Note when all explicit captures have been added.
Definition: ScopeInfo.h:958
bool ContainsUnexpandedParameterPack
Whether the lambda contains an unexpanded parameter pack.
Definition: ScopeInfo.h:899
SmallVector< NamedDecl *, 4 > LocalPacks
Packs introduced by this lambda, if any.
Definition: ScopeInfo.h:902
CleanupInfo Cleanup
Whether any of the capture expressions requires cleanups.
Definition: ScopeInfo.h:896
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
Definition: ScopeInfo.h:878
bool ExplicitParams
Whether the (empty) parameter list is explicit.
Definition: ScopeInfo.h:893
TemplateParameterList * GLTemplateParameterList
If this is a generic lambda, and the template parameter list has been created (from the TemplateParam...
Definition: ScopeInfo.h:915
ExprResult RequiresClause
The requires-clause immediately following the explicit template parameter list, if any.
Definition: ScopeInfo.h:910
SourceRange ExplicitTemplateParamsRange
Source range covering the explicit template parameter list (if it exists).
Definition: ScopeInfo.h:905
CXXRecordDecl * Lambda
The class that describes the lambda.
Definition: ScopeInfo.h:865
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
Definition: ScopeInfo.h:886
SourceLocation CaptureDefaultLoc
Source location of the '&' or '=' specifying the default capture type, if any.
Definition: ScopeInfo.h:882
llvm::DenseMap< unsigned, SourceRange > ExplicitCaptureRanges
A map of explicit capture indices to their introducer source ranges.
Definition: ScopeInfo.h:939
bool AfterParameterList
Indicate that we parsed the parameter list at which point the mutability of the lambda is known.
Definition: ScopeInfo.h:873
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Definition: ScopeInfo.h:868
bool Mutable
Whether this is a mutable lambda.
Definition: ScopeInfo.h:890
Defines the clang::TargetInfo interface.
The JSON file list parser is used to communicate input to InstallAPI.
@ CPlusPlus20
Definition: LangStandard.h:60
@ CPlusPlus
Definition: LangStandard.h:56
@ CPlusPlus14
Definition: LangStandard.h:58
@ CPlusPlus17
Definition: LangStandard.h:59
if(T->getSizeExpr()) TRY_TO(TraverseStmt(const_cast< Expr * >(T -> getSizeExpr())))
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Definition: ASTLambda.h:95
std::optional< unsigned > getStackIndexOfNearestEnclosingCaptureCapableLambda(ArrayRef< const sema::FunctionScopeInfo * > FunctionScopes, ValueDecl *VarToCapture, Sema &S)
Examines the FunctionScopeInfo stack to determine the nearest enclosing lambda (to the current lambda...
Definition: SemaLambda.cpp:180
ConstexprSpecKind
Define the kind of constexpr specifier.
Definition: Specifiers.h:35
@ ICIS_NoInit
No in-class initializer.
Definition: Specifiers.h:272
@ RQ_None
No ref-qualifier was provided.
Definition: Type.h:1778
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
bool isLambdaCallWithExplicitObjectParameter(const DeclContext *DC)
Definition: ASTLambda.h:38
StorageClass
Storage classes.
Definition: Specifiers.h:248
@ SC_Auto
Definition: Specifiers.h:256
@ SC_Static
Definition: Specifiers.h:252
@ SC_None
Definition: Specifiers.h:250
bool FTIHasSingleVoidParameter(const DeclaratorChunk::FunctionTypeInfo &FTI)
Definition: SemaInternal.h:25
@ CopyInit
[a = b], [a = {b}]
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition: ASTLambda.h:27
@ Result
The result type of a method or function.
bool hasWeakerNullability(NullabilityKind L, NullabilityKind R)
Return true if L has a weaker nullability annotation than R.
Definition: Specifiers.h:357
ActionResult< Expr * > ExprResult
Definition: Ownership.h:248
ExprResult ExprError()
Definition: Ownership.h:264
LangAS
Defines the address space values used by the address space qualifier of QualType.
Definition: AddressSpaces.h:25
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:135
StringRef getLambdaStaticInvokerName()
Definition: ASTLambda.h:22
const FunctionProtoType * T
CallingConv
CallingConv - Specifies the calling convention that a function uses.
Definition: Specifiers.h:278
@ CC_C
Definition: Specifiers.h:279
@ CC_X86VectorCall
Definition: Specifiers.h:283
@ CC_X86StdCall
Definition: Specifiers.h:280
@ CC_X86FastCall
Definition: Specifiers.h:281
@ Class
The "class" keyword introduces the elaborated-type-specifier.
@ EST_BasicNoexcept
noexcept
@ AS_public
Definition: Specifiers.h:124
@ AS_private
Definition: Specifiers.h:126
MutableArrayRef< Expr * > MultiExprArg
Definition: Ownership.h:258
Information about how a lambda is numbered within its context.
Definition: DeclCXX.h:1802
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:1595
bool hasTrailingReturnType() const
Determine whether this function declarator had a trailing-return-type.
Definition: DeclSpec.h:1586
ParsedType getTrailingReturnType() const
Get the trailing-return-type for this function declarator.
Definition: DeclSpec.h:1589
bool hasMutableQualifier() const
Determine whether this lambda-declarator contains a 'mutable' qualifier.
Definition: DeclSpec.h:1558
ParamInfo - An array of paraminfo objects is allocated whenever a function declarator is parsed.
Definition: DeclSpec.h:1333
ExceptionSpecificationType Type
The kind of exception specification this is.
Definition: Type.h:5061
Extra information about a function prototype.
Definition: Type.h:5087
ExceptionSpecInfo ExceptionSpec
Definition: Type.h:5094
FunctionType::ExtInfo ExtInfo
Definition: Type.h:5088
unsigned NumExplicitTemplateParams
The number of parameters in the template parameter list that were explicitly specified by the user,...
Definition: DeclSpec.h:2886
SmallVector< NamedDecl *, 4 > TemplateParams
Store the list of the template parameters for a generic lambda or an abbreviated function template.
Definition: DeclSpec.h:2899
Represents a complete lambda introducer.
Definition: DeclSpec.h:2835
SmallVector< LambdaCapture, 4 > Captures
Definition: DeclSpec.h:2860
SourceLocation DefaultLoc
Definition: DeclSpec.h:2858
LambdaCaptureDefault Default
Definition: DeclSpec.h:2859
An RAII helper that pops function a function scope on exit.
Definition: Sema.h:982