rust-lang / rust-memory-model

Collecting examples and information to help design a memory model for Rust.
Apache License 2.0
126 stars 15 forks source link

Forbid fabricating reference #22

Closed sanxiyn closed 2 years ago

sanxiyn commented 8 years ago
fn f() -> i32 {
    let x = 1234;
    g();
    x
}

It is desirable to allow optimizing the above program such that 1234 is always returned and no memory store is made. (1234 can be directly loaded to register.) Looking at LLVM IR, Rust already performs such optimization.

C memory model allows this optimization. I think whatever Rust memory model we decide on should allow this optimization. But as I understand, strict interpretation of "pointers are just integers" does not allow this optimization. For example, g() can iterate from 0 to usize::MAX, casting integer to pointer, compare pointed value to 1234, and when it is 1234 replace it with 1235. In general, if pointers are just integers, g() can fabricate reference to x. Optimization is valid in C, because "pointer to x" cannot be fabricated from any integer, even the integer that has same value as "pointer to x".

A Formal C Memory Model Supporting Integer-Pointer Casts (PLDI 2015) investigates this issue in detail.

arielb1 commented 8 years ago

In detail? Every memory model that allows access to non-address-taken temps is worthless wrt. optimizing compilers. The interesting points come when Rust allows temporary access to temps.

RalfJung commented 2 years ago

Stacked Borrows indeed allows that optimization, and I don't think anyone is proposing a model that would not allow this. Some more intricate examples are part of the Stacked Borrows test suite that we would also use to evaluate alternative models. Hence, closing for now.