Is this a bug with write_volatile or am I missing something?

Hi, sooo, it looks to me like write_volatile has a bug with arrays.

This code:

let reg = 0x4000000 as *mut [u16; 1];
*reg = [0x8000];

compiles to this:

mov     word ptr [67108864], -32768

While this code:

let reg = 0x4000000 as *mut [u16; 1];
write_volatile(reg, [0x8000]);

compiles to this:

mov     word ptr [rsp - 2], -32768
movzx   eax, word ptr [rsp - 2]
mov     word ptr [67108864], ax

Shouldn't they compile to the same thing?

Both

let reg = 0x4000000 as *mut u16;
*reg = 0x8000;

and

let reg = 0x4000000 as *mut u16;
write_volatile(reg, 0x8000);

compile to:

mov     word ptr [67108864], -32768

Also checked with u32 instead of u16 and got the same results: Godbolt.

Don't want to open an issue until I'm more confident that this is a bug.

Never mind, found this issue, it is a bug: Unnecessary stack writes when using write_volatile with arrays · Issue #82944 · rust-lang/rust · GitHub

1 Like

There are no guarantees about "good" codegen, whatever you think "good" should be.

Both only store through pointer once, so technically they're meeting the write_volatile behaviour.

1 Like