Optimization by the compiler of non-volatile and volatile IO-operations

Hey,

I have a question regarding the optimization of non-volatile IO-operations by the compiler. More specific I want to know if it can happen that an operation like

unsafe { ptr::write_bytes(self.string.as_ptr() as *mut c_void, 0u8, self.string.len()) };

is not executed because the compiler optimize it out.

I've read in this context about 'volatile_set_memory' which has however no stable interface like write_bytes.

There's no guarantees about whether any non-volatile operation happens or not: if removing it doesn't change the semantics of a correct program, the compiler is allowed to remove it (of course, in general, it is halting-problem hard to deduce that removing something doesn't change behaviour, but compilers do deduce some cases). E.g. zeroing memory before freeing it can be removed, because the compiler assumes that that memory won't be read before being reinitialised: doing so would be undefined behaviour*. Getting a guarantee about this is part of what volatility is, so, if you really need it, for now you'll have to use the unstable API to truly be sure it won't be removed.

(* I believe it's a little more subtle than this, but I also believe this captures the intent.)

1 Like

Okay, thank you for clarifying this to me :slight_smile: Seems that I have to review some of my code now. And hopefully the volatile API becomes stable soon.