3 ms·
I think it will break a lot less code than you think. The C standard has a subtlety with regards to const in that it allows you to (for example) cast away the
by moefh 7y ago
I think it will break a lot less code than you think.
The C standard has a subtlety with regards to const in that it allows you to (for example) cast away the const-ness of a pointer and use it to write to it, as long as the original memory was not const (i.e., it was gratuitously cast to const). That's used by a lot of code, and LLVM still respects that.
This optimization (AFAIK) only removes stores that are disallowed by the standard, which is when the memory itself you're trying to store to was actually declared const. This would most likely cause a crash anyway, the memory would in most cases be inside a read-only segment. The bug report mentioned is from code inside a kernel, not from a normal executable that would be loaded with proper memory protection (like making read-only sections actually read-only), which is probably why the code worked without the optimization.
See the example in[1]:
- The function g casts away the const to write to the pointed memory, the generated assembly does what you'd expect (it contains a store).
- The function f tries to write to memory the compiler knows is actually const, clang optimizes the store away. Trying to actually write there would crash if the program was loaded in a normal OS, since the memory is inside a read-only segment.
[1] https://godbolt.org/z/as3Mh5 https://godbolt.org/z/as3Mh5
- account42 7y agoYou can have const variables on the stack. Those will not have hardware write protection but it's still undefined to write to them.