Skip to content

[clang][bytecode] Fail on mutable reads from revisited variables #133064

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
Mar 26, 2025
Merged
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
12 changes: 11 additions & 1 deletion clang/lib/AST/ByteCode/Interp.cpp
Original file line number Diff line number Diff line change
@@ -602,8 +602,18 @@ bool CheckMutable(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
// In C++14 onwards, it is permitted to read a mutable member whose
// lifetime began within the evaluation.
if (S.getLangOpts().CPlusPlus14 &&
Ptr.block()->getEvalID() == S.Ctx.getEvalID())
Ptr.block()->getEvalID() == S.Ctx.getEvalID()) {
// FIXME: This check is necessary because (of the way) we revisit
// variables in Compiler.cpp:visitDeclRef. Revisiting a so far
// unknown variable will get the same EvalID and we end up allowing
// reads from mutable members of it.
if (!S.inConstantContext()) {
if (const VarDecl *VD = Ptr.block()->getDescriptor()->asVarDecl();
VD && VD->hasLocalStorage())
return false;
}
return true;
}

const SourceInfo &Loc = S.Current->getSource(OpPC);
const FieldDecl *Field = Ptr.getField();
36 changes: 36 additions & 0 deletions clang/test/AST/ByteCode/codegen-mutable-read.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
// RUN: %clang_cc1 -triple x86_64-linux -emit-llvm -o - %s | FileCheck %s
// RUN: %clang_cc1 -triple x86_64-linux -emit-llvm -o - %s -fexperimental-new-constant-interpreter | FileCheck %s


/// In the if expression below, the read from s.i should fail.
/// If it doesn't, and we actually read the value 0, the call to
/// func() will always occur, resuliting in a runtime failure.

struct S {
mutable int i = 0;
};

void func() {
__builtin_abort();
};

void setI(const S &s) {
s.i = 12;
}

int main() {
const S s;

setI(s);

if (s.i == 0)
func();

return 0;
}

// CHECK: define dso_local noundef i32 @main()
// CHECK: br
// CHECK: if.then
// CHECK: if.end
// CHECK: ret i32 0