Skip to content

[clang][Interp] Handle virtual calls with covariant return types #101218

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 23 additions & 1 deletion clang/lib/AST/Interp/Interp.h
Original file line number Diff line number Diff line change
Expand Up @@ -2628,7 +2628,29 @@ inline bool CallVirt(InterpState &S, CodePtr OpPC, const Function *Func,
}
}

return Call(S, OpPC, Func, VarArgSize);
if (!Call(S, OpPC, Func, VarArgSize))
return false;

// Covariant return types. The return type of Overrider is a pointer
// or reference to a class type.
if (Overrider != InitialFunction &&
Overrider->getReturnType()->isPointerOrReferenceType() &&
InitialFunction->getReturnType()->isPointerOrReferenceType()) {
QualType OverriderPointeeType =
Overrider->getReturnType()->getPointeeType();
QualType InitialPointeeType =
InitialFunction->getReturnType()->getPointeeType();
// We've called Overrider above, but calling code expects us to return what
// InitialFunction returned. According to the rules for covariant return
// types, what InitialFunction returns needs to be a base class of what
// Overrider returns. So, we need to do an upcast here.
unsigned Offset = S.getContext().collectBaseOffset(
InitialPointeeType->getAsRecordDecl(),
OverriderPointeeType->getAsRecordDecl());
return GetPtrBasePop(S, OpPC, Offset);
}

return true;
}

inline bool CallBI(InterpState &S, CodePtr &PC, const Function *Func,
Expand Down
21 changes: 21 additions & 0 deletions clang/test/AST/Interp/cxx2a.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,24 @@ consteval int aConstevalFunction() { // both-error {{consteval function never pr
return 0;
}
/// We're NOT calling the above function. The diagnostics should appear anyway.

namespace Covariant {
struct A {
virtual constexpr char f() const { return 'Z'; }
char a = f();
};

struct D : A {};
struct Covariant1 {
D d;
virtual const A *f() const;
};

struct Covariant3 : Covariant1 {
constexpr virtual const D *f() const { return &this->d; }
};

constexpr Covariant3 cb;
constexpr const Covariant1 *cb1 = &cb;
static_assert(cb1->f()->a == 'Z');
}
Loading