On 11/11/26 3:16 AM, Merlin Warner-Huish wrote:
fma (x, 1.0, y) can be folded to x + y, because multiplying by 1.0 is
exact, so the fma rounds the same way as the addition.  For the same
reason fma (x, -1.0, y) can be folded to y - x.

fma (x, y, 0.0) can be folded to x * y when adding that zero can be
dropped, which fold_real_zero_addition_p decides: -0.0 by default, and
either zero with -fno-signed-zeros.  It is not folded with
-frounding-math, because +0.0 + -0.0 is -0.0 when rounding towards
-inf, while x * y would be +0.0.
FWIW, I worked on a design one which planned to do this under the hood in the FPU hardware -- we were trying to save space by not having distinct fadd/fmul units and just reuse the fmacs.   It wasn't clear if it was going to be strictly complaint or not and I left years ago, so I don't know if they proceeded with that design decision or not.



In each case this saves the fma and loading the constant.

        PR tree-optimization/126696

gcc/ChangeLog:

        * match.pd (fma (x, 1.0, y) -> x + y): New simplification.
        (fma (x, -1.0, y) -> y - x): Likewise.
        (fma (x, y, 0.0) -> x * y): Likewise.

gcc/testsuite/ChangeLog:

        * gcc.dg/pr126696-2.c: New test.
        * gcc.dg/pr126696.c: New test.
        * gcc.dg/tree-ssa/pr126696.c: New test.
---
Changes since v1:
- Use fold_real_zero_addition_p for the zero addend, so it is not
   folded with -frounding-math, and +0.0 is folded with
   -fno-signed-zeros.
- Add gcc.dg/pr126696-2.c, an FE_DOWNWARD run test.

Bootstrapped and regression tested on x86_64-pc-linux-gnu with no new
failures.  I also checked the aarch64 compile-only tests with a cross
compiler.

I didn't add a HONOR_SNANS check to the +-1.0 folds: unlike
x * 1.0 -> x, they keep an arithmetic operation, so a signalling NaN is
still quieted and still raises invalid, as with the fma.  The zero case
uses fold_real_zero_addition_p, so it is also not done with
-fsignaling-nans, which is slightly more conservative than needed.
Andrea had a comment on how she thought this could easily solved. Your change is more complex than she suggested.  It seems like it'd be best if Andrea chimes in again.

jeff

Reply via email to