Skip to content

-Copt-level=2 may miscompile valid code #131761

Not planned
Not planned
@shao-hua-li

Description

@shao-hua-li

I tried this code:

pub fn a() -> i32 {
    return 0;
}
pub fn b() -> i32 {
    return 0;
}
pub fn main() {
    if Some(b as fn() -> i32) != Some(a as fn() -> i32) {
        println!("OK\n");
    }
}

I expected to see this happen: -Copt-level=0/1/2/3 should give the same result

Instead, this happened:

% rustc test.rs -Copt-level=1 &&./test
OK
% rustc test.rs -Copt-level=2 &&./test
%

Meta

rustc --version --verbose:

rustc 1.84.0-nightly (9322d183f 2024-10-14)
binary: rustc
commit-hash: 9322d183f45e0fd5a509820874cc5ff27744a479
commit-date: 2024-10-14
host: x86_64-unknown-linux-gnu
release: 1.84.0-nightly
LLVM version: 19.1.1

Activity

added
needs-triageThis issue may need triage. Remove it if it has been sufficiently triaged.
on Oct 15, 2024
added
C-discussionCategory: Discussion or questions that doesn't represent real issues.
and removed
C-bugCategory: This is a bug.
needs-triageThis issue may need triage. Remove it if it has been sufficiently triaged.
on Oct 15, 2024
saethlin

saethlin commented on Oct 15, 2024

@saethlin
Member

This is not a bug, you're tripping over rust-lang/unsafe-code-guidelines#522.

In short:

Functions, vtables, and consts do not have a unique stable address

The program above has different behavior because the functions are merged at some opt levels. Note that function addresses truly are unstable, not only can you get merges like this, a single function can have multiple addresses in a single program.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    C-discussionCategory: Discussion or questions that doesn't represent real issues.

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @shao-hua-li@saethlin@rustbot@Noratrieb

        Issue actions

          -Copt-level=2 may miscompile valid code · Issue #131761 · rust-lang/rust