https://gcc.gnu.org/bugzilla/show_bug.cgi?id=128795

            Bug ID: 128795
           Summary: combine: known_cond replaces a register by the other
                    operand under UNEQ for floating point, islessgreater
                    (a, b) ? b : a returns b for NaN and -0.0 (sparc64)
           Product: gcc
           Version: 17.0
            Status: UNCONFIRMED
          Keywords: wrong-code
          Severity: normal
          Priority: P3
         Component: rtl-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: lzy20000419 at outlook dot com
  Target Milestone: ---

Fails with a sparc64-linux-gnu cross trunk build (gcc 17.0.0 20261117,
9571dd0b7219) and with every tested release from 7.5.0 to 16.1.0. No working
release was found.
Target: sparc64-linux-gnu.

    /* { dg-do run } */
    /* { dg-options "-O2 -fno-trapping-math" } */
    __attribute__((noipa)) double
    f (double a, double b)
    {
      return __builtin_islessgreater (a, b) ? b : a;
    }

    int
    main (void)
    {
      volatile double nan = __builtin_nan (""), one = 1.0, nz = -0.0, pz = 0.0;
      if (!__builtin_isnan (f (nan, one)))
        __builtin_abort ();
      if (!__builtin_signbit (f (nz, pz)))
        __builtin_abort ();
      return 0;
    }

    sparc64-linux-gnu-gcc -O2 -fno-trapping-math t.c && qemu-sparc64 ./a.out

Observed: abort. Expected: exit 0. islessgreater (NaN, 1.0) and islessgreater
(-0.0, +0.0) are false, so f must return a. Trunk compiles f to

    f:
            save    %sp, -176, %sp
            return  %i7+8
             fmovd  %f2, %f0

so it always returns b. -O1 and -Os fail too; -O2 -fno-trapping-math
-fdisable-rtl-combine works. Before r17-5585 (PR122307), releases also fail
without -fno-trapping-math. On trunk that change hides the default-flags case.

Godbolt (16.1.0): https://godbolt.org/z/h5z1crbbh

In combine.cc, simplify_if_then_else gets (if_then_else (ltgt a b) b a). It
reverses the condition to UNEQ for the false arm and calls known_cond
(false_rtx, UNEQ, a, b). known_cond then does:

      if (cond == EQ && rtx_equal_p (x, reg) && ! FLOAT_MODE_P (GET_MODE (x))
          && ! FLOAT_MODE_P (GET_MODE (val)))
        return val;

      if (cond == UNEQ && rtx_equal_p (x, reg))
        return val;

The EQ case already excludes floating point. The UNEQ case has no such check,
but UNEQ (a, b) is also true when either operand is a NaN, and for -0.0 and
+0.0, so replacing a by b is wrong. Both arms become b. The bug shows on
targets whose conditional FP move takes the FP comparison result directly, such
as (ltgt (reg:CCFP %fcc0) (const_int 0)) on SPARC.

Possible fix: remove the UNEQ substitution, or require !HONOR_NANS and
!HONOR_SIGNED_ZEROS for it.

Disclaimer: This test case was found with LLM-assisted targeted testing, and
the report was written with LLM assistance.

Reply via email to