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