Avatar ·

Why doesn't Rust optimize code by assuming no aliasing of two mutable references?

Hi everyone! I'm learning Rust and trying to understand how the compiler uses safety guarantees for code optimization. It is known that in Rust, mutable references (`&mut T`) are unique: only one mutable reference to data can exist at any given time. This rule is guaranteed by the compiler at the borrow checking stage. It would seem that this should give LLVM powerful optimization hints, similar to `restrict` in C/C++. However, I noticed that in some simple benchmarks, Rust generates code that does not use this assumption. Here's a simple example: ```rust pub fn add_assign(x: &mut u32, y: &mut u32) { *x += *y; *x += *y; } ``` I expected the compiler to optimize this into `*x += *y * 2`, since `x` and `y` cannot point to the same memory.