Skip to content

Rust does not have type-based alias analysis #4536

@narpfel

Description

@narpfel

Summary

gccrs seems to compile pointers/pointer casts with C’s strict aliasing/type-based alias analysis (TBAA) semantics, i. e. with the assumption that a pointer to type T cannot alias a pointer to type U for T != U. This is not true in Rust.

Reproducer

I tried this code:

#![feature(no_core)]
#![no_core]

extern "C" {
    fn malloc(n: u64) -> *mut u8;
}

pub fn f() -> i32 {
    unsafe {
        let p = malloc(4) as *mut i32;
        *p = 27;
        *(p as *mut i16) = 42;
        *p
    }
}

pub fn main() -> i32 {
    f()
}

Does the code make use of any (1.49) nightly feature ?

  • Nightly

Godbolt link

https://godbolt.org/z/889vTb4eK

Actual behavior

The current behaviour is that gccrs ignores writes to *p through *mut i16 pointers when compiling with optimisations (-O2 and above): f returns 27 (like the equivalent C code when compiled with GCC 15.2). This is incorrect in Rust.

Expected behavior

f should return 42.

GCC Version

679aad3

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions