Skip to content

Commit 02d98a2

Browse files
committed
Reapply "[Clang][Sema] Fix crash when 'this' is used in a dependent class scope function template specialization that instantiates to a static member function (llvm#87541, llvm#88311)"
Reapplies llvm#87541 and llvm#88311 addressing the bug which caused expressions naming overload sets to be incorrectly rebuilt, as well as the bug which caused base class members to always be treated as overload sets.
1 parent 7089c35 commit 02d98a2

16 files changed

+376
-124
lines changed

clang/docs/ReleaseNotes.rst

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -529,6 +529,8 @@ Bug Fixes to C++ Support
529529
- Fix an issue caused by not handling invalid cases when substituting into the parameter mapping of a constraint. Fixes (#GH86757).
530530
- Fixed a bug that prevented member function templates of class templates declared with a deduced return type
531531
from being explicitly specialized for a given implicit instantiation of the class template.
532+
- Fixed a crash when ``this`` is used in a dependent class scope function template specialization
533+
that instantiates to a static member function.
532534

533535
- Fix crash when inheriting from a cv-qualified type. Fixes:
534536
(`#35603 <https://github.com/llvm/llvm-project/issues/35603>`_)

clang/include/clang/AST/ExprCXX.h

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3219,7 +3219,8 @@ class UnresolvedLookupExpr final
32193219
Create(const ASTContext &Context, CXXRecordDecl *NamingClass,
32203220
NestedNameSpecifierLoc QualifierLoc,
32213221
const DeclarationNameInfo &NameInfo, bool RequiresADL, bool Overloaded,
3222-
UnresolvedSetIterator Begin, UnresolvedSetIterator End);
3222+
UnresolvedSetIterator Begin, UnresolvedSetIterator End,
3223+
bool KnownDependent);
32233224

32243225
// After canonicalization, there may be dependent template arguments in
32253226
// CanonicalConverted But none of Args is dependent. When any of

clang/include/clang/Sema/Sema.h

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -5452,7 +5452,8 @@ class Sema final : public SemaBase {
54525452

54535453
ExprResult BuildDeclarationNameExpr(const CXXScopeSpec &SS, LookupResult &R,
54545454
bool NeedsADL,
5455-
bool AcceptInvalidDecl = false);
5455+
bool AcceptInvalidDecl = false,
5456+
bool NeedUnresolved = false);
54565457
ExprResult BuildDeclarationNameExpr(
54575458
const CXXScopeSpec &SS, const DeclarationNameInfo &NameInfo, NamedDecl *D,
54585459
NamedDecl *FoundD = nullptr,
@@ -6595,7 +6596,10 @@ class Sema final : public SemaBase {
65956596
SourceLocation RParenLoc);
65966597

65976598
//// ActOnCXXThis - Parse 'this' pointer.
6598-
ExprResult ActOnCXXThis(SourceLocation loc);
6599+
ExprResult ActOnCXXThis(SourceLocation Loc);
6600+
6601+
/// Check whether the type of 'this' is valid in the current context.
6602+
bool CheckCXXThisType(SourceLocation Loc, QualType Type);
65996603

66006604
/// Build a CXXThisExpr and mark it referenced in the current context.
66016605
Expr *BuildCXXThisExpr(SourceLocation Loc, QualType Type, bool IsImplicit);
@@ -7018,10 +7022,14 @@ class Sema final : public SemaBase {
70187022
///@{
70197023

70207024
public:
7025+
/// Check whether an expression might be an implicit class member access.
7026+
bool isPotentialImplicitMemberAccess(const CXXScopeSpec &SS, LookupResult &R,
7027+
bool IsAddressOfOperand);
7028+
70217029
ExprResult BuildPossibleImplicitMemberExpr(
70227030
const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
7023-
const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
7024-
UnresolvedLookupExpr *AsULE = nullptr);
7031+
const TemplateArgumentListInfo *TemplateArgs, const Scope *S);
7032+
70257033
ExprResult
70267034
BuildImplicitMemberExpr(const CXXScopeSpec &SS, SourceLocation TemplateKWLoc,
70277035
LookupResult &R,

clang/lib/AST/ASTImporter.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8562,7 +8562,7 @@ ASTNodeImporter::VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E) {
85628562
return UnresolvedLookupExpr::Create(
85638563
Importer.getToContext(), *ToNamingClassOrErr, *ToQualifierLocOrErr,
85648564
ToNameInfo, E->requiresADL(), E->isOverloaded(), ToDecls.begin(),
8565-
ToDecls.end());
8565+
ToDecls.end(), /*KnownDependent=*/E->isTypeDependent());
85668566
}
85678567

85688568
ExpectedStmt

clang/lib/AST/ExprCXX.cpp

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -374,14 +374,15 @@ UnresolvedLookupExpr *UnresolvedLookupExpr::Create(
374374
const ASTContext &Context, CXXRecordDecl *NamingClass,
375375
NestedNameSpecifierLoc QualifierLoc, const DeclarationNameInfo &NameInfo,
376376
bool RequiresADL, bool Overloaded, UnresolvedSetIterator Begin,
377-
UnresolvedSetIterator End) {
377+
UnresolvedSetIterator End, bool KnownDependent) {
378378
unsigned NumResults = End - Begin;
379379
unsigned Size = totalSizeToAlloc<DeclAccessPair, ASTTemplateKWAndArgsInfo,
380380
TemplateArgumentLoc>(NumResults, 0, 0);
381381
void *Mem = Context.Allocate(Size, alignof(UnresolvedLookupExpr));
382-
return new (Mem) UnresolvedLookupExpr(Context, NamingClass, QualifierLoc,
383-
SourceLocation(), NameInfo, RequiresADL,
384-
Overloaded, nullptr, Begin, End, false);
382+
return new (Mem) UnresolvedLookupExpr(
383+
Context, NamingClass, QualifierLoc,
384+
/*TemplateKWLoc=*/SourceLocation(), NameInfo, RequiresADL, Overloaded,
385+
/*TemplateArgs=*/nullptr, Begin, End, KnownDependent);
385386
}
386387

387388
UnresolvedLookupExpr *UnresolvedLookupExpr::Create(

clang/lib/Sema/SemaCoroutine.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -823,7 +823,7 @@ ExprResult Sema::BuildOperatorCoawaitLookupExpr(Scope *S, SourceLocation Loc) {
823823
Expr *CoawaitOp = UnresolvedLookupExpr::Create(
824824
Context, /*NamingClass*/ nullptr, NestedNameSpecifierLoc(),
825825
DeclarationNameInfo(OpName, Loc), /*RequiresADL*/ true, IsOverloaded,
826-
Functions.begin(), Functions.end());
826+
Functions.begin(), Functions.end(), /*KnownDependent=*/false);
827827
assert(CoawaitOp);
828828
return CoawaitOp;
829829
}

clang/lib/Sema/SemaDecl.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1240,7 +1240,7 @@ Sema::NameClassification Sema::ClassifyName(Scope *S, CXXScopeSpec &SS,
12401240
return NameClassification::OverloadSet(UnresolvedLookupExpr::Create(
12411241
Context, Result.getNamingClass(), SS.getWithLocInContext(Context),
12421242
Result.getLookupNameInfo(), ADL, Result.isOverloadedResult(),
1243-
Result.begin(), Result.end()));
1243+
Result.begin(), Result.end(), /*KnownDependent=*/false));
12441244
}
12451245

12461246
ExprResult

clang/lib/Sema/SemaExpr.cpp

Lines changed: 10 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -2917,26 +2917,9 @@ Sema::ActOnIdExpression(Scope *S, CXXScopeSpec &SS,
29172917
// to get this right here so that we don't end up making a
29182918
// spuriously dependent expression if we're inside a dependent
29192919
// instance method.
2920-
if (getLangOpts().CPlusPlus && !R.empty() &&
2921-
(*R.begin())->isCXXClassMember()) {
2922-
bool MightBeImplicitMember;
2923-
if (!IsAddressOfOperand)
2924-
MightBeImplicitMember = true;
2925-
else if (!SS.isEmpty())
2926-
MightBeImplicitMember = false;
2927-
else if (R.isOverloadedResult())
2928-
MightBeImplicitMember = false;
2929-
else if (R.isUnresolvableResult())
2930-
MightBeImplicitMember = true;
2931-
else
2932-
MightBeImplicitMember = isa<FieldDecl>(R.getFoundDecl()) ||
2933-
isa<IndirectFieldDecl>(R.getFoundDecl()) ||
2934-
isa<MSPropertyDecl>(R.getFoundDecl());
2935-
2936-
if (MightBeImplicitMember)
2937-
return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc,
2938-
R, TemplateArgs, S);
2939-
}
2920+
if (isPotentialImplicitMemberAccess(SS, R, IsAddressOfOperand))
2921+
return BuildPossibleImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs,
2922+
S);
29402923

29412924
if (TemplateArgs || TemplateKWLoc.isValid()) {
29422925

@@ -3447,10 +3430,11 @@ static bool ShouldLookupResultBeMultiVersionOverload(const LookupResult &R) {
34473430

34483431
ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
34493432
LookupResult &R, bool NeedsADL,
3450-
bool AcceptInvalidDecl) {
3433+
bool AcceptInvalidDecl,
3434+
bool NeedUnresolved) {
34513435
// If this is a single, fully-resolved result and we don't need ADL,
34523436
// just build an ordinary singleton decl ref.
3453-
if (!NeedsADL && R.isSingleResult() &&
3437+
if (!NeedUnresolved && !NeedsADL && R.isSingleResult() &&
34543438
!R.getAsSingle<FunctionTemplateDecl>() &&
34553439
!ShouldLookupResultBeMultiVersionOverload(R))
34563440
return BuildDeclarationNameExpr(SS, R.getLookupNameInfo(), R.getFoundDecl(),
@@ -3470,12 +3454,10 @@ ExprResult Sema::BuildDeclarationNameExpr(const CXXScopeSpec &SS,
34703454
// we've picked a target.
34713455
R.suppressDiagnostics();
34723456

3473-
UnresolvedLookupExpr *ULE
3474-
= UnresolvedLookupExpr::Create(Context, R.getNamingClass(),
3475-
SS.getWithLocInContext(Context),
3476-
R.getLookupNameInfo(),
3477-
NeedsADL, R.isOverloadedResult(),
3478-
R.begin(), R.end());
3457+
UnresolvedLookupExpr *ULE = UnresolvedLookupExpr::Create(
3458+
Context, R.getNamingClass(), SS.getWithLocInContext(Context),
3459+
R.getLookupNameInfo(), NeedsADL, R.isOverloadedResult(), R.begin(),
3460+
R.end(), NeedUnresolved);
34793461

34803462
return ULE;
34813463
}

clang/lib/Sema/SemaExprCXX.cpp

Lines changed: 32 additions & 29 deletions
Original file line numberDiff line numberDiff line change
@@ -1416,26 +1416,42 @@ bool Sema::CheckCXXThisCapture(SourceLocation Loc, const bool Explicit,
14161416
}
14171417

14181418
ExprResult Sema::ActOnCXXThis(SourceLocation Loc) {
1419-
/// C++ 9.3.2: In the body of a non-static member function, the keyword this
1420-
/// is a non-lvalue expression whose value is the address of the object for
1421-
/// which the function is called.
1419+
// C++20 [expr.prim.this]p1:
1420+
// The keyword this names a pointer to the object for which an
1421+
// implicit object member function is invoked or a non-static
1422+
// data member's initializer is evaluated.
14221423
QualType ThisTy = getCurrentThisType();
14231424

1424-
if (ThisTy.isNull()) {
1425-
DeclContext *DC = getFunctionLevelDeclContext();
1425+
if (CheckCXXThisType(Loc, ThisTy))
1426+
return ExprError();
14261427

1427-
if (const auto *Method = dyn_cast<CXXMethodDecl>(DC);
1428-
Method && Method->isExplicitObjectMemberFunction()) {
1429-
return Diag(Loc, diag::err_invalid_this_use) << 1;
1430-
}
1428+
return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false);
1429+
}
14311430

1432-
if (isLambdaCallWithExplicitObjectParameter(CurContext))
1433-
return Diag(Loc, diag::err_invalid_this_use) << 1;
1431+
bool Sema::CheckCXXThisType(SourceLocation Loc, QualType Type) {
1432+
if (!Type.isNull())
1433+
return false;
14341434

1435-
return Diag(Loc, diag::err_invalid_this_use) << 0;
1435+
// C++20 [expr.prim.this]p3:
1436+
// If a declaration declares a member function or member function template
1437+
// of a class X, the expression this is a prvalue of type
1438+
// "pointer to cv-qualifier-seq X" wherever X is the current class between
1439+
// the optional cv-qualifier-seq and the end of the function-definition,
1440+
// member-declarator, or declarator. It shall not appear within the
1441+
// declaration of either a static member function or an explicit object
1442+
// member function of the current class (although its type and value
1443+
// category are defined within such member functions as they are within
1444+
// an implicit object member function).
1445+
DeclContext *DC = getFunctionLevelDeclContext();
1446+
if (const auto *Method = dyn_cast<CXXMethodDecl>(DC);
1447+
Method && Method->isExplicitObjectMemberFunction()) {
1448+
Diag(Loc, diag::err_invalid_this_use) << 1;
1449+
} else if (isLambdaCallWithExplicitObjectParameter(CurContext)) {
1450+
Diag(Loc, diag::err_invalid_this_use) << 1;
1451+
} else {
1452+
Diag(Loc, diag::err_invalid_this_use) << 0;
14361453
}
1437-
1438-
return BuildCXXThisExpr(Loc, ThisTy, /*IsImplicit=*/false);
1454+
return true;
14391455
}
14401456

14411457
Expr *Sema::BuildCXXThisExpr(SourceLocation Loc, QualType Type,
@@ -8642,21 +8658,8 @@ static ExprResult attemptRecovery(Sema &SemaRef,
86428658

86438659
// Detect and handle the case where the decl might be an implicit
86448660
// member.
8645-
bool MightBeImplicitMember;
8646-
if (!Consumer.isAddressOfOperand())
8647-
MightBeImplicitMember = true;
8648-
else if (!NewSS.isEmpty())
8649-
MightBeImplicitMember = false;
8650-
else if (R.isOverloadedResult())
8651-
MightBeImplicitMember = false;
8652-
else if (R.isUnresolvableResult())
8653-
MightBeImplicitMember = true;
8654-
else
8655-
MightBeImplicitMember = isa<FieldDecl>(ND) ||
8656-
isa<IndirectFieldDecl>(ND) ||
8657-
isa<MSPropertyDecl>(ND);
8658-
8659-
if (MightBeImplicitMember)
8661+
if (SemaRef.isPotentialImplicitMemberAccess(
8662+
NewSS, R, Consumer.isAddressOfOperand()))
86608663
return SemaRef.BuildPossibleImplicitMemberExpr(
86618664
NewSS, /*TemplateKWLoc*/ SourceLocation(), R,
86628665
/*TemplateArgs*/ nullptr, /*S*/ nullptr);

clang/lib/Sema/SemaExprMember.cpp

Lines changed: 49 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -61,6 +61,10 @@ enum IMAKind {
6161
/// The reference is a contextually-permitted abstract member reference.
6262
IMA_Abstract,
6363

64+
/// Whether the context is static is dependent on the enclosing template (i.e.
65+
/// in a dependent class scope explicit specialization).
66+
IMA_Dependent,
67+
6468
/// The reference may be to an unresolved using declaration and the
6569
/// context is not an instance method.
6670
IMA_Unresolved_StaticOrExplicitContext,
@@ -91,10 +95,18 @@ static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
9195

9296
DeclContext *DC = SemaRef.getFunctionLevelDeclContext();
9397

94-
bool isStaticOrExplicitContext =
95-
SemaRef.CXXThisTypeOverride.isNull() &&
96-
(!isa<CXXMethodDecl>(DC) || cast<CXXMethodDecl>(DC)->isStatic() ||
97-
cast<CXXMethodDecl>(DC)->isExplicitObjectMemberFunction());
98+
bool couldInstantiateToStatic = false;
99+
bool isStaticOrExplicitContext = SemaRef.CXXThisTypeOverride.isNull();
100+
101+
if (auto *MD = dyn_cast<CXXMethodDecl>(DC)) {
102+
if (MD->isImplicitObjectMemberFunction()) {
103+
isStaticOrExplicitContext = false;
104+
// A dependent class scope function template explicit specialization
105+
// that is neither declared 'static' nor with an explicit object
106+
// parameter could instantiate to a static or non-static member function.
107+
couldInstantiateToStatic = MD->getDependentSpecializationInfo();
108+
}
109+
}
98110

99111
if (R.isUnresolvableResult())
100112
return isStaticOrExplicitContext ? IMA_Unresolved_StaticOrExplicitContext
@@ -123,6 +135,9 @@ static IMAKind ClassifyImplicitMemberAccess(Sema &SemaRef,
123135
if (Classes.empty())
124136
return IMA_Static;
125137

138+
if (couldInstantiateToStatic)
139+
return IMA_Dependent;
140+
126141
// C++11 [expr.prim.general]p12:
127142
// An id-expression that denotes a non-static data member or non-static
128143
// member function of a class can only be used:
@@ -263,32 +278,52 @@ static void diagnoseInstanceReference(Sema &SemaRef,
263278
}
264279
}
265280

281+
bool Sema::isPotentialImplicitMemberAccess(const CXXScopeSpec &SS,
282+
LookupResult &R,
283+
bool IsAddressOfOperand) {
284+
if (!getLangOpts().CPlusPlus)
285+
return false;
286+
else if (R.empty() || !R.begin()->isCXXClassMember())
287+
return false;
288+
else if (!IsAddressOfOperand)
289+
return true;
290+
else if (!SS.isEmpty())
291+
return false;
292+
else if (R.isOverloadedResult())
293+
return false;
294+
else if (R.isUnresolvableResult())
295+
return true;
296+
else
297+
return isa<FieldDecl, IndirectFieldDecl, MSPropertyDecl>(R.getFoundDecl());
298+
}
299+
266300
/// Builds an expression which might be an implicit member expression.
267301
ExprResult Sema::BuildPossibleImplicitMemberExpr(
268302
const CXXScopeSpec &SS, SourceLocation TemplateKWLoc, LookupResult &R,
269-
const TemplateArgumentListInfo *TemplateArgs, const Scope *S,
270-
UnresolvedLookupExpr *AsULE) {
271-
switch (ClassifyImplicitMemberAccess(*this, R)) {
303+
const TemplateArgumentListInfo *TemplateArgs, const Scope *S) {
304+
switch (IMAKind Classification = ClassifyImplicitMemberAccess(*this, R)) {
272305
case IMA_Instance:
273-
return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, true, S);
274-
275306
case IMA_Mixed:
276307
case IMA_Mixed_Unrelated:
277308
case IMA_Unresolved:
278-
return BuildImplicitMemberExpr(SS, TemplateKWLoc, R, TemplateArgs, false,
279-
S);
280-
309+
return BuildImplicitMemberExpr(
310+
SS, TemplateKWLoc, R, TemplateArgs,
311+
/*IsKnownInstance=*/Classification == IMA_Instance, S);
281312
case IMA_Field_Uneval_Context:
282313
Diag(R.getNameLoc(), diag::warn_cxx98_compat_non_static_member_use)
283314
<< R.getLookupNameInfo().getName();
284315
[[fallthrough]];
285316
case IMA_Static:
286317
case IMA_Abstract:
318+
case IMA_Dependent:
287319
case IMA_Mixed_StaticOrExplicitContext:
288320
case IMA_Unresolved_StaticOrExplicitContext:
289321
if (TemplateArgs || TemplateKWLoc.isValid())
290-
return BuildTemplateIdExpr(SS, TemplateKWLoc, R, false, TemplateArgs);
291-
return AsULE ? AsULE : BuildDeclarationNameExpr(SS, R, false);
322+
return BuildTemplateIdExpr(SS, TemplateKWLoc, R, /*RequiresADL=*/false,
323+
TemplateArgs);
324+
return BuildDeclarationNameExpr(
325+
SS, R, /*NeedsADL=*/false, /*AcceptInvalidDecl=*/false,
326+
/*NeedUnresolved=*/Classification == IMA_Dependent);
292327

293328
case IMA_Error_StaticOrExplicitContext:
294329
case IMA_Error_Unrelated:

0 commit comments

Comments
 (0)