17

GCC's man page states that -funsafe-math-optimizations allows for optimizations that "(a) assume that arguments and results are valid and (b) may violate IEEE or ANSI standards", but that's not very precise, is it?

What could an "invalid" argument be in this case? NaNs? Infinites? Subnormals? Negative numbers to sqrt()?

How far are results allowed to deviate from IEEE or ANSI standards? Is it "merely" stuff like operation associativity and ordering, or might it include eg. true comparisons with NaNs or incorrect comparisons with infinites? Could a stored variable be re-rounded after already being used (such that, for variables x and y, (x == y) + (x == y) could evaluate to 1)? Could isinf()/isnan() stop working?

Do the GCC devs follow any particular system or discipline with regards to such questions, or could the answer differ wildly from version to version?

Community
  • 1
  • 1
Dolda2000
  • 25,216
  • 4
  • 51
  • 92
  • As far as I know, it doesn't mess with that. `-ffinite-math-only` and `-ffast-math` do though. – harold Jan 25 '15 at 07:38

1 Answers1

3

According to gcc.gnu.org (my bold):

This mode enables optimizations that allow arbitrary reassociations and transformations with no accuracy guarantees. It also does not try to preserve the sign of zeros.

That includes your mention of associative reordering, as well as "Built-in functions [which] have names such as __builtin_sqrt" being applied when they "may have less precision or be restricted to a smaller domain"

Community
  • 1
  • 1
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
  • Perhaps this is simply a bug in the implementation and/or documentation, but reality does not seem to match what you describe, because I observe GCC only optimizing a `floor()` call to a `roundsd` instruction when `-funsafe-math-optimization` is enabled, even though this instruction cannot reasonably violate the constraints you describe, seeing as how that single instruction is also the implementation of the `floor()` function in glibc for SSE4.1+ processors. I'll have to investigate. – Dolda2000 Jan 26 '15 at 08:46
  • Apparently, that `roundsd` optimization is only enabled with `-fno-trapping-math` which is part of `-funsafe-math-optimizations`. According to the people on the GCC mailing list, that limitation seems to be overly cautious anyway, however, so there seems to be no reason to think that that implies less safety than this answer indicates. With that cleared up, I'm marking it as accepted. – Dolda2000 Feb 11 '15 at 06:50
  • 1
    According to https://en.wikipedia.org/wiki/ARM_architecture#Advanced_SIMD_(Neon) this flag is required to use ARM's NEON engine with its restriction on subnormals: _A quirk of Neon in ARMv7 devices is that it flushes all subnormal numbers to zero, and as a result the GCC compiler will not use it unless `-funsafe-math-optimizations`, which allows losing denormals, is turned on._ – nqtronix Jul 24 '22 at 13:35