logoalt Hacker News

wat10000 • today at 4:28 PM • 2 replies • view on HN

That depends entirely on how you define “the semantics.” Any optimizing compiler has to draw a line between what the program is meant to do and how the emitted code actually makes it happen. The proper location of that line is not obvious. Can it turn x++,x++ into x+=2? That’s normally fine, potentially disastrous if x is a memory mapped register on an external device.

C and C++ happen to have a particularly restrictive view on what “the semantics” of a program really are, such that there are a lot of things you can write in syntactically-legal C that officially erase the semantic meaning of the code. Within that definition of the program’s semantics, gcc’s optimizer is not supposed to change them, and any such change would be a bug. You’re taking a more expansive view of program semantics than the actual language specifies. If you do that, then any optimizing compiler is going to consider it to be acceptable to violate your special bespoke definition of them.


Replies

oriolid • today at 6:04 PM

> Can it turn x++,x++ into x+=2

For this particular example the line should be clear. If the variable is volatile, memory access can't be removed or reordered. If it's not volatile, everything is fair game.

Mandatory Godbolt link: https://godbolt.org/z/fjKs4hbjo

marcosdumay • today at 4:38 PM

> The proper location of that line is not obvious.

If that's true, you have a bad language.

What is known to be the case with C, but this is not a desirable nor a necessary state of affairs. A language can and should have defined semantics.