Comment by bluGill
8 hours ago
however you certainly can do that. The point of unaligned is the hardware can't load it from a single memory location in one address. It needs two accesses. And in that time, the value of one of the two addresses that the hardware has to load can change.
I would hope you're not so stupid as to design hardware that relies on this, but the fact is it certainly is possible for someone to do that. And if you do that, there is nothing that the compiler or the standard can do. It can't be done correctly
Yeah, the unaligned accesses aren't going to be atomic unless the hardware supports it.
> And in that time, the value of one of the two addresses that the hardware has to load can change.
You mean volatile addresses that could spontaneously change in the middle of the reads? Like memory mapped I/O addresses?
I would expect these to have stricter access requirements than arbitrary general purpose memory locations.
> I would hope you're not so stupid as to design hardware that relies on this
You and me both.
> And if you do that, there is nothing that the compiler or the standard can do. It can't be done correctly
Anything that does that is broken and terrible anyway. It really shouldn't contaminate language design. It's the sort of thing that compilers should be adding attributes for, rather than constraining the language to the point nothing works correctly and making us use attributes on everything to restore some sane baseline behavior.
> Anything that does that is broken and terrible anyway
which is why it is undefined behaviour. the optimizer writers have told me consistently that if they can assume you're not doing this thing that's stupid anyway, they can make my code faster. And since I'm not doing that stupid thing anyway, I want my code to be faster.
Unaligned memory access isn't really stupid though. Not in the general case. Not to the point where it should give the compiler free reign to crash things or introduce security holes. It should just introduce a performance regression instead, which is a tractable problem. Just measure it and fix it by making things aligned.
Compilers can add some custom attributes that encode whatever semantics the badly designed hardware requires. This lets it freely break incorrect code in the small sections that are actually handling those special variables, while allowing the rest of the language to make sense.