23 #include "llvm/ADT/STLExtras.h" 24 using namespace clang;
70 unsigned CurScopeIndex = FunctionScopes.size() - 1;
71 while (CurScopeIndex > 0 && isa<clang::sema::CapturedRegionScopeInfo>(
72 FunctionScopes[CurScopeIndex]))
75 isa<clang::sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]) &&
76 "The function on the top of sema's function-info stack must be a lambda");
79 const bool IsCapturingThis = !VarToCapture;
80 const bool IsCapturingVariable = !IsCapturingThis;
84 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex])->CallOperator;
88 cast<sema::LambdaScopeInfo>(FunctionScopes[CurScopeIndex]);
96 if (IsCapturingVariable &&
98 return NoLambdaIsCaptureReady;
117 if (IsCapturingVariable && !LSI->
isCaptured(VarToCapture))
118 return NoLambdaIsCaptureReady;
120 return NoLambdaIsCaptureReady;
124 assert(CurScopeIndex);
130 assert(CurScopeIndex < (FunctionScopes.size() - 1));
134 return CurScopeIndex + 1;
135 return NoLambdaIsCaptureReady;
182 if (!OptionalStackIndex)
183 return NoLambdaIsCaptureCapable;
185 const unsigned IndexOfCaptureReadyLambda = OptionalStackIndex.getValue();
186 assert(((IndexOfCaptureReadyLambda != (FunctionScopes.size() - 1)) ||
188 "The capture ready lambda for a potential capture can only be the " 189 "current lambda if it is a generic lambda");
192 cast<sema::LambdaScopeInfo>(FunctionScopes[IndexOfCaptureReadyLambda]);
195 const bool IsCapturingThis = !VarToCapture;
196 const bool IsCapturingVariable = !IsCapturingThis;
198 if (IsCapturingVariable) {
203 const bool CanCaptureVariable =
209 DeclRefType, &IndexOfCaptureReadyLambda);
210 if (!CanCaptureVariable)
211 return NoLambdaIsCaptureCapable;
216 const bool CanCaptureThis =
220 &IndexOfCaptureReadyLambda);
222 return NoLambdaIsCaptureCapable;
224 return IndexOfCaptureReadyLambda;
265 if (
const FunctionDecl *FD = dyn_cast<FunctionDecl>(DC))
277 Decl *&ManglingContextDecl) {
280 ManglingContextDecl = ExprEvalContexts.back().ManglingContextDecl;
294 if (ManglingContextDecl) {
295 if (
ParmVarDecl *Param = dyn_cast<ParmVarDecl>(ManglingContextDecl)) {
298 if (LexicalDC->isRecord())
299 Kind = DefaultArgument;
300 }
else if (
VarDecl *Var = dyn_cast<VarDecl>(ManglingContextDecl)) {
301 if (Var->getDeclContext()->isRecord())
302 Kind = StaticDataMember;
303 else if (Var->getMostRecentDecl()->isInline())
304 Kind = InlineVariable;
305 else if (Var->getDescribedVarTemplate())
306 Kind = VariableTemplate;
307 else if (
auto *VTS = dyn_cast<VarTemplateSpecializationDecl>(Var)) {
308 if (!VTS->isExplicitSpecialization())
309 Kind = VariableTemplate;
311 }
else if (isa<FieldDecl>(ManglingContextDecl)) {
319 bool IsInNonspecializedTemplate =
320 inTemplateInstantiation() || CurContext->isDependentContext();
325 if ((IsInNonspecializedTemplate &&
326 !(ManglingContextDecl && isa<ParmVarDecl>(ManglingContextDecl))) ||
328 ManglingContextDecl =
nullptr;
329 while (
auto *CD = dyn_cast<CapturedDecl>(DC))
334 ManglingContextDecl =
nullptr;
338 case StaticDataMember:
340 if (!IsInNonspecializedTemplate) {
341 ManglingContextDecl =
nullptr;
349 case DefaultArgument:
353 case VariableTemplate:
355 return &ExprEvalContexts.back().getMangleNumberingContext(Context);
358 llvm_unreachable(
"unexpected context");
364 assert(ManglingContextDecl &&
"Need to have a context declaration");
365 if (!MangleNumbering)
367 return *MangleNumbering;
374 Optional<std::pair<unsigned, Decl *>> Mangling) {
384 if (Result->isUndeducedType()) {
385 Result = SubstAutoType(Result, Context.
DependentTy);
404 Context, Class, EndLoc,
407 MethodType, MethodTypeInfo,
SC_None,
408 true, ConstexprKind, EndLoc);
420 if (TemplateMethod) {
427 if (!Params.empty()) {
429 CheckParmsForFunctionDef(Params,
433 P->setOwningFunction(Method);
439 Decl *ManglingContextDecl;
442 ManglingContextDecl)) {
443 unsigned ManglingNumber = MCtx->getManglingNumber(Method);
457 bool ExplicitResultType,
461 LSI->
Lambda = LambdaClass;
471 if (ExplicitResultType) {
477 diag::err_lambda_incomplete_result)) {
494 assert(LSI &&
"Expected a lambda scope");
496 "Already acted on explicit template parameters");
498 "Explicit template parameters should come " 499 "before invented (auto) ones");
500 assert(!TParams.empty() &&
501 "No template parameters to act on");
511 for (
unsigned p = 0, NumParams = CallOperator->
getNumParams();
512 p < NumParams; ++
p) {
520 for (
const auto &
Capture : Captures) {
524 Diag(
Capture.Loc, diag::note_var_explicitly_captured_here)
529 CheckShadow(CurScope, Param);
531 PushOnScopeChains(Param, CurScope);
551 = dyn_cast<EnumConstantDecl>(DRE->getDecl())) {
552 return cast<EnumDecl>(D->getDeclContext());
560 if (BO->getOpcode() == BO_Comma)
567 if (
StmtExpr *SE = dyn_cast<StmtExpr>(E)) {
568 if (
Expr *last = dyn_cast_or_null<Expr>(SE->getSubStmt()->body_back()))
589 if (ICE->getCastKind() == CK_IntegralCast)
597 return ET->getDecl();
620 if (!ED)
return nullptr;
623 for (++i; i != e; ++
i) {
639 i = returns.begin(), e = returns.end();
i != e; ++
i) {
651 Expr *E = (cleanups ? cleanups->getSubExpr() : retValue);
655 cleanups->setSubExpr(E);
666 assert((!isa<LambdaScopeInfo>(CSI) || !getLangOpts().
CPlusPlus14) &&
667 "lambda expressions use auto deduction in C++14 onwards");
704 assert(!CSI.
ReturnType.
isNull() &&
"We should have a tentative return type.");
709 if (!getLangOpts().CPlusPlus) {
710 assert(isa<BlockScopeInfo>(CSI));
733 (RetE ? RetE->
getType() : Context.
VoidTy).getUnqualifiedType();
739 if (BlockNullability &&
740 (!RetTyNullability ||
749 diag::err_typecheck_missing_return_type_incompatible)
750 << ReturnType << CSI.
ReturnType << isa<LambdaScopeInfo>(CSI);
765 DeductType = BuildReferenceType(DeductType,
true, Loc, Id);
766 assert(!DeductType.
isNull() &&
"can't build reference to auto");
772 ? diag::warn_cxx17_compat_init_capture_pack
773 : diag::ext_init_capture_pack);
823 unsigned InitStyle,
Expr *Init) {
828 PETL.setEllipsisLoc(EllipsisLoc);
835 Loc, Id, InitCaptureType, TSI,
SC_Auto);
839 NewVD->
setInitStyle(static_cast<VarDecl::InitializationStyle>(InitStyle));
846 assert(Var->
isInitCapture() &&
"init capture flag should be set");
856 assert(LSI &&
"LambdaScopeInfo should be on stack!");
863 assert(TemplateParamScope &&
864 "Lambda with explicit template param list should establish a " 865 "template param scope");
866 assert(TemplateParamScope->getParent());
867 KnownDependent = TemplateParamScope->getParent()
868 ->getTemplateParamParent() !=
nullptr;
875 bool ExplicitParams =
true;
876 bool ExplicitResultType =
true;
877 bool ContainsUnexpandedParameterPack =
false;
887 EPI.TypeQuals.addConst();
894 QualType DefaultTypeForNoTrailingReturn =
900 ExplicitParams =
false;
901 ExplicitResultType =
false;
905 "lambda-declarator is a function");
912 if (!FTI.hasMutableQualifier()) {
917 MethodTyInfo = GetTypeForDeclarator(ParamInfo, CurScope);
918 assert(MethodTyInfo &&
"no type from lambda-declarator");
921 ExplicitResultType = FTI.hasTrailingReturnType();
924 Params.reserve(FTI.NumParams);
925 for (
unsigned i = 0, e = FTI.NumParams;
i != e; ++
i)
926 Params.push_back(cast<ParmVarDecl>(FTI.Params[
i].Param));
931 ContainsUnexpandedParameterPack =
true;
935 KnownDependent, Intro.
Default);
938 startLambdaDefinition(Class, Intro.
Range, MethodTyInfo, EndLoc, Params,
941 CheckCXXDefaultArguments(Method);
945 AddRangeBasedOptnone(Method);
948 if (
Attr *A = getImplicitCodeSegOrSectionAttrForFunction(Method,
true))
952 ProcessDeclAttributes(CurScope, Method, ParamInfo);
956 if (getLangOpts().CUDA)
957 CUDASetLambdaAttrs(Method);
960 PushDeclContext(CurScope, Method);
964 ExplicitParams, ExplicitResultType, !Method->
isConst());
978 (getCurrentThisType().isNull() ||
984 llvm::SmallSet<IdentifierInfo*, 8> CaptureNames;
990 PrevCaptureLoc = C->Loc, ++C) {
994 ? diag::ext_star_this_lambda_capture_cxx17
995 : diag::warn_cxx14_compat_star_this_lambda_capture);
1001 Diag(C->Loc, diag::err_capture_more_than_once)
1004 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1015 ? diag::ext_equals_this_lambda_capture_cxx2a
1016 : diag::warn_cxx17_compat_equals_this_lambda_capture);
1021 QualType ThisCaptureType = getCurrentThisType();
1022 if (ThisCaptureType.
isNull()) {
1023 Diag(C->Loc, diag::err_this_capture) <<
true;
1027 CheckCXXThisCapture(C->Loc,
true,
true,
1035 assert(C->Id &&
"missing identifier for capture");
1037 if (C->Init.isInvalid())
1041 if (C->Init.isUsable()) {
1043 ? diag::warn_cxx11_compat_init_capture
1044 : diag::ext_init_capture);
1051 if (C->InitCaptureType.get().isNull())
1054 if (C->Init.get()->containsUnexpandedParameterPack() &&
1056 ContainsUnexpandedParameterPack =
true;
1059 switch (C->InitKind) {
1061 llvm_unreachable(
"not an init-capture?");
1072 Var = createLambdaInitCaptureVarDecl(C->Loc, C->InitCaptureType.get(),
1073 C->EllipsisLoc, C->Id, InitStyle,
1080 PushOnScopeChains(Var, CurScope,
false);
1083 "init capture has valid but null init?");
1091 Diag(C->Loc, diag::err_reference_capture_with_reference_default)
1093 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1096 Diag(C->Loc, diag::err_copy_capture_with_copy_default)
1098 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1107 LookupName(R, CurScope);
1114 if (DiagnoseEmptyLookup(CurScope, ScopeSpec, R, Validator))
1119 if (Var && DiagnoseUseOfDecl(Var, C->Loc))
1126 if (!CaptureNames.insert(C->Id).second) {
1128 Diag(C->Loc, diag::err_capture_more_than_once)
1131 SourceRange(getLocForEndOfToken(PrevCaptureLoc), C->Loc));
1135 Diag(C->Loc, diag::err_capture_more_than_once) << C->Id;
1144 Diag(C->Loc, diag::err_capture_does_not_name_variable) << C->Id;
1153 Diag(C->Loc, diag::err_capture_non_automatic_variable) << C->Id;
1161 if (C->EllipsisLoc.isValid()) {
1163 EllipsisLoc = C->EllipsisLoc;
1165 Diag(C->EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
1166 << (C->Init.isUsable() ? C->Init.get()->getSourceRange()
1172 ContainsUnexpandedParameterPack =
true;
1175 if (C->Init.isUsable()) {
1176 addInitCapture(LSI, Var);
1179 TryCapture_ExplicitByVal;
1180 tryCaptureVariable(Var, C->Loc, Kind, EllipsisLoc);
1185 finishLambdaExplicitCaptures(LSI);
1190 addLambdaParameters(Intro.
Captures, Method, CurScope);
1194 PushExpressionEvaluationContext(
1195 ExpressionEvaluationContext::PotentiallyEvaluated);
1199 bool IsInstantiation) {
1203 DiscardCleanupsInEvaluationContext();
1204 PopExpressionEvaluationContext();
1207 if (!IsInstantiation)
1216 CheckCompletedCXXClass(Class);
1218 PopFunctionScopeInfo();
1234 "Lambda's call operator should not have a reference qualifier");
1247 auto HasPassObjectSizeAttr = [](
const ParmVarDecl *
P) {
1248 return P->hasAttr<PassObjectSizeAttr>();
1250 if (llvm::any_of(CallOperator->
parameters(), HasPassObjectSizeAttr))
1264 ConvExtInfo.TypeQuals.addConst();
1322 for (
unsigned I = 0, N = CallOperator->
getNumParams(); I != N; ++I) {
1332 CallOpConvTL.setParam(I, From);
1333 CallOpConvNameTL.setParam(I, From);
1352 Loc, ConversionName,
1358 Class->
addDecl(ConversionTemplate);
1380 for (
unsigned I = 0, N = CallOperator->
getNumParams(); I != N; ++I)
1381 InvokerParams[I]->setOwningFunction(Invoke);
1389 S.
Context, Class, Loc, InvokerName,
1395 Class->
addDecl(StaticInvokerTemplate);
1413 ConversionEPI.TypeQuals.addConst();
1434 bool IsOpenMPMapping) {
1464 QualType ThisTy = getCurrentThisType();
1465 Expr *This = BuildCXXThisExpr(Loc, ThisTy, ImplicitCaptureLoc.
isValid());
1467 Init = CreateBuiltinUnaryOp(Loc, UO_Deref, This);
1473 Name = Var->getIdentifier();
1474 Init = BuildDeclarationNameExpr(
1481 if (IsOpenMPMapping)
1493 return InitSeq.
Perform(*
this, Entity, InitKind, InitExpr);
1500 return BuildLambdaExpr(StartLoc, Body->
getEndLoc(), &LSI);
1514 llvm_unreachable(
"block capture in lambda");
1516 llvm_unreachable(
"Unknown implicit capture style");
1530 ? getCurrentThisType()->getPointeeType()
1538 return !RD->isCompleteDefinition() || !RD->hasTrivialCopyConstructor() ||
1539 !RD->hasTrivialDestructor();
1546 if (CaptureHasSideEffects(From))
1552 auto diag =
Diag(From.
getLocation(), diag::warn_unused_lambda_capture);
1572 if (Var->isInitCapture())
1588 if (RequireCompleteType(Loc, FieldType, diag::err_field_incomplete)) {
1621 bool ExplicitParams;
1622 bool ExplicitResultType;
1624 bool ContainsUnexpandedParameterPack;
1625 bool IsGenericLambda;
1637 Decl *TemplateOrNonTemplateCallOperatorDecl =
1640 : cast<Decl>(CallOperator);
1643 Class->
addDecl(TemplateOrNonTemplateCallOperatorDecl);
1645 PopExpressionEvaluationContext();
1648 bool CurHasPreviousCapture = CaptureDefault !=
LCD_None;
1650 CaptureDefaultLoc : IntroducerRange.
getBegin();
1652 for (
unsigned I = 0, N = LSI->
Captures.size(); I != N; ++I) {
1658 assert(!From.
isBlockCapture() &&
"Cannot capture __block variables");
1667 bool IsCaptureUsed =
true;
1668 if (!CurContext->isDependentContext() && !IsImplicit &&
1672 bool NonODRUsedInitCapture =
1674 if (!NonODRUsedInitCapture) {
1678 if (!CurHasPreviousCapture && !IsLast) {
1682 getLocForEndOfToken(CaptureRange.
getEnd()));
1685 FixItRange =
SourceRange(getLocForEndOfToken(PrevCaptureLoc),
1690 IsCaptureUsed = !DiagnoseUnusedLambdaCapture(FixItRange, From);
1695 CurHasPreviousCapture |= IsCaptureUsed;
1696 PrevCaptureLoc = CaptureRange.
getEnd();
1705 if (getLangOpts().CPlusPlus2a && IsImplicit &&
1708 Diag(CaptureDefaultLoc, diag::note_deprecated_this_capture)
1710 getLocForEndOfToken(CaptureDefaultLoc),
", this");
1727 ExprResult Init = BuildCaptureInit(From, ImplicitCaptureLoc);
1734 BuildCaptureField(Class, From);
1735 Captures.push_back(Capture);
1736 CaptureInits.push_back(Init.get());
1744 if (Captures.empty() && CaptureDefault ==
LCD_None)
1754 if (getLangOpts().Blocks && getLangOpts().ObjC && !IsGenericLambda)
1761 CheckCompletedCXXClass(Class);
1764 Cleanup.mergeFrom(LambdaCleanup);
1767 CaptureDefault, CaptureDefaultLoc,
1769 ExplicitParams, ExplicitResultType,
1770 CaptureInits, EndLoc,
1771 ContainsUnexpandedParameterPack);
1777 !isa<CoroutineBodyStmt>(CallOperator->
getBody()) &&
1781 (CheckConstexprFunctionDecl(CallOperator) &&
1782 CheckConstexprFunctionBody(CallOperator, CallOperator->
getBody()))
1788 DiagnoseShadowingLambdaDecls(LSI);
1790 if (!CurContext->isDependentContext()) {
1791 switch (ExprEvalContexts.back().Context) {
1795 case ExpressionEvaluationContext::Unevaluated:
1796 case ExpressionEvaluationContext::UnevaluatedList:
1797 case ExpressionEvaluationContext::UnevaluatedAbstract:
1807 case ExpressionEvaluationContext::ConstantEvaluated:
1811 ExprEvalContexts.back().Lambdas.push_back(Lambda);
1814 case ExpressionEvaluationContext::DiscardedStatement:
1815 case ExpressionEvaluationContext::PotentiallyEvaluated:
1816 case ExpressionEvaluationContext::PotentiallyEvaluatedIfUsed:
1821 return MaybeBindToTemporary(Lambda);
1831 = cast<CXXMethodDecl>(
1840 CurrentLocation, Src);
1842 Init = ActOnFinishFullExpr(Init.
get(),
false);
1857 for (
unsigned I = 0, N = CallOperator->
getNumParams(); I != N; ++I) {
1875 ConvLocation,
nullptr,
1888 ExprCleanupObjects.push_back(Block);
1889 Cleanup.setExprNeedsCleanups(
true);
void setImplicit(bool I=true)
Represents a function declaration or definition.
SourceRange IntroducerRange
Source range covering the lambda introducer [...].
DeclaratorChunk::FunctionTypeInfo & getFunctionTypeInfo()
getFunctionTypeInfo - Retrieves the function type info object (looking through parentheses).
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
SourceLocation getBeginLoc() const
A class which contains all the information about a particular captured value.
if(T->getSizeExpr()) TRY_TO(TraverseStmt(T -> getSizeExpr()))
unsigned getRawEncoding() const
When a SourceLocation itself cannot be used, this returns an (opaque) 32-bit integer encoding for it...
A (possibly-)qualified type.
bool ExplicitParams
Whether the (empty) parameter list is explicit.
TemplateParameterList * GLTemplateParameterList
If this is a generic lambda, and the template parameter list has been created (from the TemplateParam...
bool SetTypeQual(TQ T, SourceLocation Loc)
Stmt - This represents one statement.
An instance of this object exists for each enum constant that is defined.
QualType ReturnType
ReturnType - The target type of return statements in this context, or null if unknown.
StorageClass getStorageClass() const
Returns the storage class as written in the source.
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
QualType getCaptureType() const
Retrieve the capture type for this capture, which is effectively the type of the non-static data memb...
Decl - This represents one declaration (or definition), e.g.
bool isVariadic() const
Whether this function prototype is variadic.
LambdaCaptureDefault
The default, if any, capture method for a lambda expression.
CanQualType getCanonicalFunctionResultType(QualType ResultType) const
Adjust the given function result type.
ExprResult BuildBlockForLambdaConversion(SourceLocation CurrentLocation, SourceLocation ConvLocation, CXXConversionDecl *Conv, Expr *Src)
bool isCopyCapture() const
static InitializationKind CreateDirect(SourceLocation InitLoc, SourceLocation LParenLoc, SourceLocation RParenLoc)
Create a direct initialization.
QualType getBlockPointerType(QualType T) const
Return the uniqued reference to the type for a block of the specified type.
The base class of the type hierarchy.
void setParams(ArrayRef< ParmVarDecl *> NewParamInfo)
bool isFunctionDeclarator(unsigned &idx) const
isFunctionDeclarator - This method returns true if the declarator is a function declarator (looking t...
RefQualifierKind RefQualifier
A container of type source information.
Store information needed for an explicit specifier.
QualType getConversionType() const
Returns the type that this conversion function is converting to.
void setInitStyle(InitializationStyle Style)
Describes the capture of a variable or of this, or of a C++1y init-capture.
This file provides some common utility functions for processing Lambda related AST Constructs...
Represents a variable declaration or definition.
bool DiagnoseUnusedLambdaCapture(SourceRange CaptureRange, const sema::Capture &From)
Diagnose if an explicit lambda capture is unused.
Information about one declarator, including the parsed type information and the identifier.
QualType getReturnType() const
VarDecl * createLambdaInitCaptureVarDecl(SourceLocation Loc, QualType InitCaptureType, SourceLocation EllipsisLoc, IdentifierInfo *Id, unsigned InitStyle, Expr *Init)
Create a dummy variable within the declcontext of the lambda's call operator, for name lookup purpose...
const T * getAs() const
Member-template getAs<specific type>'.
Extra information about a function prototype.
bool isInvalidDecl() const
Stores a list of template parameters for a TemplateDecl and its derived classes.
MangleNumberingContext & getMangleNumberingContext(ASTContext &Ctx)
Retrieve the mangling numbering context, used to consistently number constructs like lambdas for mang...
static InitializationKind CreateDirectList(SourceLocation InitLoc)
bool tryCaptureVariable(VarDecl *Var, SourceLocation Loc, TryCaptureKind Kind, SourceLocation EllipsisLoc, bool BuildAndDiagnose, QualType &CaptureType, QualType &DeclRefType, const unsigned *const FunctionScopeIndexToStopAt)
Try to capture the given variable.
bool CaptureHasSideEffects(const sema::Capture &From)
Does copying/destroying the captured variable have side effects?
Represents an expression – generally a full-expression – that introduces cleanups to be run at the ...
Represents a parameter to a function.
CXXRecordDecl * createLambdaClosureType(SourceRange IntroducerRange, TypeSourceInfo *Info, bool KnownDependent, LambdaCaptureDefault CaptureDefault)
Create a new lambda closure type.
Defines the clang::Expr interface and subclasses for C++ expressions.
The collection of all-type qualifiers we support.
tok::TokenKind ContextKind
static CXXMethodDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, StorageClass SC, bool isInline, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation)
bool FTIHasNonVoidParameters(const DeclaratorChunk::FunctionTypeInfo &FTI)
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Represents a struct/union/class.
Scope * getTemplateParamParent()
FunctionType::ExtInfo ExtInfo
One of these records is kept for each identifier that is lexed.
sema::LambdaScopeInfo * getCurGenericLambda()
Retrieve the current generic lambda info, if any.
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
ArrayRef< QualType > getParamTypes() const
field_range fields() const
TypeSourceInfo * getTypeSourceInfo(ASTContext &Context, QualType T)
Creates a TypeSourceInfo for the given type.
SourceLocation getBeginLoc() const LLVM_READONLY
std::unique_ptr< MangleNumberingContext > createMangleNumberingContext() const
LambdaCaptureKind
The different capture forms in a lambda introducer.
Represents a member of a struct/union/class.
bool isReferenceType() const
bool Equals(const DeclContext *DC) const
Determine whether this declaration context is equivalent to the declaration context DC...
void setParams(ArrayRef< ParmVarDecl *> NewParamInfo)
SourceLocation getBeginLoc() const LLVM_READONLY
static CXXRecordDecl * CreateLambda(const ASTContext &C, DeclContext *DC, TypeSourceInfo *Info, SourceLocation Loc, bool DependentLambda, bool IsGeneric, LambdaCaptureDefault CaptureDefault)
bool ContainsUnexpandedParameterPack
Whether the lambda contains an unexpanded parameter pack.
An r-value expression (a pr-value in the C++11 taxonomy) produces a temporary value.
ArrayRef< ParmVarDecl * > parameters() const
DeclClass * getAsSingle() const
bool isThisCapture() const
void setNameLoc(SourceLocation Loc)
Represents the results of name lookup.
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
RAII class used to indicate that we are performing provisional semantic analysis to determine the val...
< Capturing the *this object by copy
static LambdaCaptureDefault mapImplicitCaptureStyle(CapturingScopeInfo::ImplicitCaptureStyle ICS)
static InitializedEntity InitializeLambdaToBlock(SourceLocation BlockVarLoc, QualType Type, bool NRVO)
Keeps track of the mangled names of lambda expressions and block literals within a particular context...
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
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...
unsigned getNumTypeObjects() const
Return the number of types applied to this declarator.
const VariableArrayType * getCapturedVLAType() const
bool containsUnexpandedParameterPack() const
Whether this type is or contains an unexpanded parameter pack, used to support C++0x variadic templat...
A builtin binary operation expression such as "x + y" or "x <= y".
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
void setLambdaMangling(unsigned ManglingNumber, Decl *ContextDecl)
Set the mangling number and context declaration for a lambda class.
void finishedExplicitCaptures()
Note when all explicit captures have been added.
DeclContext * getLambdaAwareParentOfDeclContext(DeclContext *DC)
Scope - A scope is a transient data structure that is used while parsing the program.
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...
void addInitCapture(sema::LambdaScopeInfo *LSI, VarDecl *Var)
Add an init-capture to a lambda scope.
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...
bool hasNameForLinkage() const
Is this tag type named, either directly or via being defined in a typedef of this type...
Represents a C++ nested-name-specifier or a global scope specifier.
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
unsigned NumExplicitTemplateParams
The number of parameters in the template parameter list that were explicitly specified by the user...
static VarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S)
const LangOptions & getLangOpts() const
bool isLambdaCallOperator(const CXXMethodDecl *MD)
ExprResult BuildCaptureInit(const sema::Capture &Capture, SourceLocation ImplicitCaptureLoc, bool IsOpenMPMapping=false)
Initialize the given capture with a suitable expression.
static FunctionTemplateDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L, DeclarationName Name, TemplateParameterList *Params, NamedDecl *Decl)
Create a function template node.
StringRef getLambdaStaticInvokerName()
QualType getLambdaConversionFunctionResultType(const FunctionProtoType *CallOpType)
Get the return type to use for a lambda's conversion function(s) to function pointer type...
static void addFunctionPointerConversion(Sema &S, SourceRange IntroducerRange, CXXRecordDecl *Class, CXXMethodDecl *CallOperator)
Add a lambda's conversion to function pointer, as described in C++11 [expr.prim.lambda]p6.
DeclSpec & getOrCreateMethodQualifiers()
void addLambdaParameters(ArrayRef< LambdaIntroducer::LambdaCapture > Captures, CXXMethodDecl *CallOperator, Scope *CurScope)
Introduce the lambda parameters into scope.
CallingConv getDefaultCallingConvention(bool IsVariadic, bool IsCXXMethod, bool IsBuiltin=false) const
Retrieves the default calling convention for the current target.
TypeSpecTypeLoc pushTypeSpec(QualType T)
Pushes space for a typespec TypeLoc.
CleanupInfo Cleanup
Whether any of the capture expressions requires cleanups.
TyLocType push(QualType T)
Pushes space for a new TypeLoc of the given type.
lookup_result lookup(DeclarationName Name) const
lookup - Find the declarations (if any) with the given Name in this context.
ExtInfo withCallingConv(CallingConv cc) const
ImplicitCaptureStyle ImpCaptureStyle
bool isIntegralOrUnscopedEnumerationType() const
Determine whether this type is an integral or unscoped enumeration type.
ConditionalOperator - The ?: ternary operator.
Sema - This implements semantic analysis and AST building for C.
CompoundStmt - This represents a group of statements like { stmt stmt }.
bool Mutable
Whether this is a mutable lambda.
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
SmallVector< ReturnStmt *, 4 > Returns
The list of return statements that occur within the function or block, if there is any chance of appl...
Represents a prototype with parameter type info, e.g.
static ImplicitCastExpr * Create(const ASTContext &Context, QualType T, CastKind Kind, Expr *Operand, const CXXCastPath *BasePath, ExprValueKind Cat)
DeclarationNameTable DeclarationNames
void finishLambdaExplicitCaptures(sema::LambdaScopeInfo *LSI)
Note that we have finished the explicit captures for the given lambda.
SourceLocation getEllipsisLoc() const
Retrieve the source location of the ellipsis, whose presence indicates that the capture is a pack exp...
SmallVector< LambdaCapture, 4 > Captures
SourceLocation PotentialThisCaptureLocation
unsigned NumExplicitCaptures
The number of captures in the Captures list that are explicit captures.
TypeSourceInfo * getTrivialTypeSourceInfo(QualType T, SourceLocation Loc=SourceLocation()) const
Allocate a TypeSourceInfo where all locations have been initialized to a given location, which defaults to the empty location.
bool isVariableCapture() const
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
TemplateParameterList * getTemplateParameters() const
Get the list of template parameters.
static CXXConversionDecl * Create(ASTContext &C, CXXRecordDecl *RD, SourceLocation StartLoc, const DeclarationNameInfo &NameInfo, QualType T, TypeSourceInfo *TInfo, bool isInline, ExplicitSpecifier ES, ConstexprSpecKind ConstexprKind, SourceLocation EndLocation)
DeclContext * getLexicalParent()
getLexicalParent - Returns the containing lexical DeclContext.
CXXMethodDecl * CallOperator
The lambda's compiler-generated operator().
Represents a block literal declaration, which is like an unnamed FunctionDecl.
ExprResult ActOnLambdaExpr(SourceLocation StartLoc, Stmt *Body, Scope *CurScope)
ActOnLambdaExpr - This is called when the body of a lambda expression was successfully completed...
This represents one expression.
bool isVariadic() const
Whether this function is variadic.
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
This file defines the classes used to store parsed information about declaration-specifiers and decla...
const T * castAs() const
Member-template castAs<specific type>.
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
T getAs() const
Convert to the specified TypeLoc type, returning a null TypeLoc if this TypeLoc is not of the desired...
void setInvalidDecl(bool Invalid=true)
setInvalidDecl - Indicates the Decl had a semantic error.
void setRetValue(Expr *E)
bool isFileContext() const
DeclContext * getDeclContext()
static TemplateParameterList * getGenericLambdaTemplateParameterList(LambdaScopeInfo *LSI, Sema &SemaRef)
llvm::DenseMap< unsigned, SourceRange > ExplicitCaptureRanges
A map of explicit capture indices to their introducer source ranges.
void buildLambdaScope(sema::LambdaScopeInfo *LSI, CXXMethodDecl *CallOperator, SourceRange IntroducerRange, LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc, bool ExplicitParams, bool ExplicitResultType, bool Mutable)
Endow the lambda scope info with the relevant properties.
bool isCaptured(VarDecl *Var) const
Determine whether the given variable has been captured.
bool isFunctionOrMethod() const
Capture & getCapture(VarDecl *Var)
Retrieve the capture of the given variable, if it has been captured already.
Direct list-initialization (C++11)
static LambdaExpr * Create(const ASTContext &C, CXXRecordDecl *Class, SourceRange IntroducerRange, LambdaCaptureDefault CaptureDefault, SourceLocation CaptureDefaultLoc, ArrayRef< LambdaCapture > Captures, bool ExplicitParams, bool ExplicitResultType, ArrayRef< Expr *> CaptureInits, SourceLocation ClosingBrace, bool ContainsUnexpandedParameterPack)
Construct a new lambda expression.
static bool isInInlineFunction(const DeclContext *DC)
Determine whether the given context is or is enclosed in an inline function.
DeclContext * getParent()
getParent - Returns the containing DeclContext.
ReturnStmt - This represents a return, optionally of an expression: return; return 4;...
SourceLocation getEnd() const
QualType getFunctionType(QualType ResultTy, ArrayRef< QualType > Args, const FunctionProtoType::ExtProtoInfo &EPI) const
Return a normal function type with a typed argument list.
struct CXXOpName CXXOperatorName
bool isDependentContext() const
Determines whether this context is dependent on a template parameter.
Common base class for placeholders for types that get replaced by placeholder type deduction: C++11 a...
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Represents a C++ conversion function within a class.
QualType getTypeDeclType(const TypeDecl *Decl, const TypeDecl *PrevDecl=nullptr) const
Return the unique reference to the type for the specified type declaration.
SourceLocation getLocation() const
Retrieve the location at which this variable was captured.
bool isNull() const
Return true if this QualType doesn't point to a type yet.
CallingConv
CallingConv - Specifies the calling convention that a function uses.
TypeLoc getReturnLoc() const
static TemplateParameterList * Create(const ASTContext &C, SourceLocation TemplateLoc, SourceLocation LAngleLoc, ArrayRef< NamedDecl *> Params, SourceLocation RAngleLoc, Expr *RequiresClause)
SourceLocation getEndLoc() const LLVM_READONLY
static InitializationKind CreateCopy(SourceLocation InitLoc, SourceLocation EqualLoc, bool AllowExplicitConvs=false)
Create a copy initialization.
ConstexprSpecKind getConstexprSpecifier() const
void setIsVariadic(bool value)
ExprResult BuildLambdaExpr(SourceLocation StartLoc, SourceLocation EndLoc, sema::LambdaScopeInfo *LSI)
Complete a lambda-expression having processed and attached the lambda body.
QualType getPackExpansionType(QualType Pattern, Optional< unsigned > NumExpansions)
SmallVector< NamedDecl *, 4 > TemplateParams
Store the list of the template parameters for a generic lambda.
void setIsConversionFromLambda(bool val=true)
SourceLocation DefaultLoc
bool hasWeakerNullability(NullabilityKind L, NullabilityKind R)
Return true if L has a weaker nullability annotation than R.
ActionResult - This structure is used while parsing/acting on expressions, stmts, etc...
VarDecl * getVariable() const
ExtProtoInfo getExtProtoInfo() const
unsigned getNumExprs() const
Return the number of expressions in this paren list.
Encodes a location in the source.
IdentifierInfo & get(StringRef Name)
Return the identifier token info for the specified named identifier.
QualType getReturnType() const
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums...
static InitializedEntity InitializeLambdaCapture(IdentifierInfo *VarID, QualType FieldType, SourceLocation Loc)
Create the initialization entity for a lambda capture.
CXXRecordDecl * Lambda
The class that describes the lambda.
static Optional< unsigned > getStackIndexOfNearestEnclosingCaptureReadyLambda(ArrayRef< const clang::sema::FunctionScopeInfo *> FunctionScopes, VarDecl *VarToCapture)
Examines the FunctionScopeInfo stack to determine the nearest enclosing lambda (to the current lambda...
SourceRange ExplicitTemplateParamsRange
Source range covering the explicit template parameter list (if it exists).
MutableArrayRef< Expr * > MultiExprArg
void setReferenced(bool R=true)
CXXMethodDecl * startLambdaDefinition(CXXRecordDecl *Class, SourceRange IntroducerRange, TypeSourceInfo *MethodType, SourceLocation EndLoc, ArrayRef< ParmVarDecl *> Params, ConstexprSpecKind ConstexprKind, Optional< std::pair< unsigned, Decl *>> Mangling=None)
Start the definition of a lambda expression.
Represents a static or instance method of a struct/union/class.
No ref-qualifier was provided.
C-style initialization with assignment.
const ParmVarDecl * getParamDecl(unsigned i) const
bool isVLATypeCapture() const
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Describes the kind of initialization being performed, along with location information for tokens rela...
SmallVector< Capture, 4 > Captures
Captures - The captures.
ImplicitCastExpr - Allows us to explicitly represent implicit type conversions, which have no direct ...
MangleNumberingContext * getCurrentMangleNumberContext(const DeclContext *DC, Decl *&ManglingContextDecl)
Compute the mangling number context for a lambda expression or block literal.
SourceLocation CaptureDefaultLoc
Source location of the '&' or '=' specifying the default capture type, if any.
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
static EnumDecl * findEnumForBlockReturn(Expr *E)
If this expression is an enumerator-like expression of some type T, return the type T; otherwise...
Represents a pack expansion of types.
DeclarationNameLoc - Additional source/type location info for a declaration name. ...
SourceRange getSourceRange() const LLVM_READONLY
Get the source range that spans this declarator.
This file provides some common utility functions for processing Lambdas.
static ParmVarDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, StorageClass S, Expr *DefArg)
Dataflow Directional Tag Classes.
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...
void setBody(CompoundStmt *B)
ConstexprSpecKind
Define the kind of constexpr specifier.
bool isValid() const
Return true if this is a valid SourceLocation object.
LambdaCaptureDefault Default
DeclContext - This is used only as base class of specific decl types that can act as declaration cont...
void deduceClosureReturnType(sema::CapturingScopeInfo &CSI)
Deduce a block or lambda's return type based on the return statements present in the body...
Optional< unsigned > getStackIndexOfNearestEnclosingCaptureCapableLambda(ArrayRef< const sema::FunctionScopeInfo *> FunctionScopes, VarDecl *VarToCapture, Sema &S)
Examines the FunctionScopeInfo stack to determine the nearest enclosing lambda (to the current lambda...
static FixItHint CreateRemoval(CharSourceRange RemoveRange)
Create a code modification hint that removes the given source range.
const Expr * getInit() const
static void addBlockPointerConversion(Sema &S, SourceRange IntroducerRange, CXXRecordDecl *Class, CXXMethodDecl *CallOperator)
Add a lambda's conversion to block pointer.
The name of a declaration.
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined...
MangleNumberingContext & getManglingNumberContext(const DeclContext *DC)
Retrieve the context for computing mangling numbers in the given DeclContext.
bool isParameterPack() const
Determine whether this variable is actually a function parameter pack or init-capture pack...
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
DeclarationNameInfo - A collector data type for bundling together a DeclarationName and the correspnd...
void ActOnLambdaExplicitTemplateParameterList(SourceLocation LAngleLoc, ArrayRef< NamedDecl *> TParams, SourceLocation RAngleLoc)
This is called after parsing the explicit template parameter list on a lambda (if it exists) in C++2a...
bool isUndeducedType() const
Determine whether this type is an undeduced type, meaning that it somehow involves a C++11 'auto' typ...
void setInitCapture(bool IC)
Capturing variable-length array type.
void ActOnStartOfLambdaDefinition(LambdaIntroducer &Intro, Declarator &ParamInfo, Scope *CurScope)
ActOnStartOfLambdaDefinition - This is called just before we start parsing the body of a lambda; it a...
void setConstexprKind(ConstexprSpecKind CSK)
TypeSourceInfo * getTypeSourceInfo() const
bool hasSameType(QualType T1, QualType T2) const
Determine whether the given types T1 and T2 are equivalent.
Simple template class for restricting typo correction candidates to ones having a single Decl* of the...
QualType getAutoDeductType() const
C++11 deduction pattern for 'auto' type.
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.
void addDecl(Decl *D)
Add the declaration D into this context.
Optional< NullabilityKind > getNullability(const ASTContext &context) const
Determine the nullability of the given type.
Capturing the *this object by reference.
void markUsed(ASTContext &C)
Mark the declaration used, in the sense of odr-use.
Capture & getCXXThisCapture()
Retrieve the capture of C++ 'this', if it has been captured.
bool isIncompleteType(NamedDecl **Def=nullptr) const
Types are partitioned into 3 broad categories (C99 6.2.5p1): object types, function types...
FieldDecl * BuildCaptureField(RecordDecl *RD, const sema::Capture &Capture)
Build a FieldDecl suitable to hold the given capture.
CanQualType getCanonicalType(QualType T) const
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
void setSignatureAsWritten(TypeSourceInfo *Sig)
TypeLoc getTypeLoc() const
Return the TypeLoc wrapper for the type source info.
bool isInitCapture() const
Determine whether this capture is an init-capture.
static BlockDecl * Create(ASTContext &C, DeclContext *DC, SourceLocation L)
Call-style initialization (C++98)
TranslationUnitDecl * getTranslationUnitDecl() const
void addCapture(VarDecl *Var, bool isBlock, bool isByref, bool isNested, SourceLocation Loc, SourceLocation EllipsisLoc, QualType CaptureType, bool Invalid)
Describes the sequence of initializations required to initialize a given object or reference with a s...
ActionResult< Expr * > ExprResult
Represents a C++ struct/union/class.
const DeclSpec & getDeclSpec() const
getDeclSpec - Return the declaration-specifier that this declarator was declared with.
bool isCXXThisCaptured() const
Determine whether the C++ 'this' is captured.
bool containsUnexpandedParameterPack() const
Whether this expression contains an unexpanded parameter pack (for C++11 variadic templates)...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
void setCapturedVLAType(const VariableArrayType *VLAType)
Set the captured variable length array type for this field.
Defines the clang::TargetInfo interface.
Represents a complete lambda introducer.
bool HasImplicitReturnType
void setDescribedFunctionTemplate(FunctionTemplateDecl *Template)
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
A reference to a declared variable, function, enum, etc.
bool isNonODRUsed() const
bool empty() const
Return true if no decls were found.
void setCaptures(ASTContext &Context, ArrayRef< Capture > Captures, bool CapturesCXXThis)
A trivial tuple used to represent a source range.
void setLexicalDeclContext(DeclContext *DC)
This represents a decl that may have a name.
bool isTranslationUnit() const
void setAccess(AccessSpecifier AS)
void setBlockMissingReturnType(bool val=true)
Describes an entity that is being initialized.
QualType buildLambdaInitCaptureInitialization(SourceLocation Loc, bool ByRef, SourceLocation EllipsisLoc, Optional< unsigned > NumExpansions, IdentifierInfo *Id, bool DirectInit, Expr *&Init)
static FieldDecl * Create(const ASTContext &C, DeclContext *DC, SourceLocation StartLoc, SourceLocation IdLoc, IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo, Expr *BW, bool Mutable, InClassInitStyle InitStyle)
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Wrapper for source info for pointers.
SourceLocation getBegin() const
bool isBlockCapture() const
static void adjustBlockReturnsToEnum(Sema &S, ArrayRef< ReturnStmt *> returns, QualType returnType)
Adjust the given return statements so that they formally return the given type.
Declaration of a template function.
Attr - This represents one attribute.
SourceLocation getLocation() const
QualType getType() const
Return the type wrapped by this type source info.
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point...