Bug 121652 - [15 Regression] round builtin does not raise FE_INVALID for signaling NaN
Summary: [15 Regression] round builtin does not raise FE_INVALID for signaling NaN
Status: RESOLVED FIXED
Alias: None
Product: gcc
Classification: Unclassified
Component: target (show other bugs)
Version: 15.2.1
: P2 normal
Target Milestone: 15.3
Assignee: Vineet Gupta
URL:
Keywords: wrong-code
Depends on:
Blocks:
 
Reported: 2025-08-24 11:40 UTC by Levi Zim
Modified: 2025-10-08 21:55 UTC (History)
6 users (show)

See Also:
Host: riscv64-linux-gnu
Target: riscv64-linux-gnu
Build: riscv64-linux-gnu
Known to work:
Known to fail:
Last reconfirmed: 2025-08-24 00:00:00


Attachments
Preprocessed source code of test-nearbyint-except (41.86 KB, text/plain)
2025-08-26 04:25 UTC, Levi Zim
Details
Patch / Proof of concept (956 bytes, patch)
2025-09-07 21:26 UTC, Aurelien Jarno
Details | Diff

Note You need to log in before you can comment on or make changes to this bug.
Description Levi Zim 2025-08-24 11:40:25 UTC
The fix for 121534 causes another glibc test to fail:

    $ math/test-nearbyint-except
    PASS: float
    FAIL: float sNaN
    PASS: double
    FAIL: double sNaN
    PASS: long double
    PASS: long double sNaN


The test that fails is

  /* But it mustn't lose exceptions from sNaN arguments.  */		\
  if (SNAN_TESTS (FLOAT))						\
    {									\
      static volatile FLOAT snan = __builtin_nans ## SUFFIX ("");	\
      volatile FLOAT c __attribute__ ((unused));			\
      feclearexcept (FE_ALL_EXCEPT);					\
      c = nearbyint ## SUFFIX (snan);					\
      if (fetestexcept (FE_INVALID) == FE_INVALID)			\
	puts ("PASS: " #FLOAT " sNaN");					\
      else								\
	{								\
	  puts ("FAIL: " #FLOAT " sNaN");				\
	  result = 1;							\
	}								\
    }									\


It appears that gcc's round built-in is used in the place of nearbyint in the test.

The test expects nearbyint to raise an exception for signaling NaN but previous fix(r16-3220-gf5696e9b1113b0a8e464cabb8cc26c871b1d9289) unconditionally saves and restores the fflags thus losing the FE_INVALID exception for sNaN input.

That being said, I am not sure what's the expectation of round built-in.
If it should always save/restore fflags, then the built-in should not be applied here.
If not, we need a special case for signaling NaN.
Comment 1 Xi Ruoyao 2025-08-24 13:57:39 UTC
Per previous Glibc discussion about nearbyint on x86:

if frndint raises an "invalid" exception for a sNaN operand, that *should* be added into the restored environment.

Thus we indeed should keep the exception here.
Comment 2 Xi Ruoyao 2025-08-24 14:04:11 UTC
The easiest way would be a feq.[sd] with the operand as both inputs, and r0 as the output:

"FEQ.S performs a quiet comparison: it only sets the invalid operation exception flag if either input is a signaling NaN."
Comment 3 Vineet Gupta 2025-08-25 08:55:14 UTC
Can you provide the exact flags used to build the test. Also will be handy the fragment of preprocessed test specifically around SNAN_TESTS. Thx.
Comment 4 Vineet Gupta 2025-08-25 16:50:36 UTC
Also I'm thinking to model this based on existing libc implementation which has been around for a while and should hopefully be correct.

What glibc does is early check for nan and return x + x if so. See [1]

This implicitly
  - doesn't restore flags for nan case (this PR/121652)
  - restores flag otherwise (retains fix for PR/121534)

https://github.com/bminor/glibc/blob/master/sysdeps/riscv/rv64/rvd/s_round.c

This requires the gcc builtin to call equivalent of __builtin_isnan().

However looks like there's a different problem lurking under the hood so let me run it by this group who care about these subtleties.

Consider following test: -O2 -march=rv64gc -mabi=lp64d

`
int myisnan(double __x)
{
   return __builtin_isnan(__x);
}
`

generates

`
myisnan:
	feq.d	a0,fa0,fa0
	xori	a0,a0,1
	ret
`

FEQ.D is a quite comparison meaning it *can* set the invalid operation exception flag if either input is a signaling NaN.

For the purpose of this PR I can implement isnan using fclass insn, but the general question stands (I'll open a seperate PR for that, since its an independent issue of its own).
Comment 5 Andrew Waterman 2025-08-25 23:57:42 UTC
My recollection is that Annex F leaves signaling NaN behavior implementation-defined, and so setting the invalid flag on signaling NaN is permitted but not required.  For __builtin_isnan, I see that the ARMv8 and x86 backends use instructions that set the invalid flag on signaling NaNs, so it's probably best that we do the same.

Furthermore, it's more efficient to use feq than fclass, because when the result controls an if-statement, the xori can be omitted (whereas fclass still needs an andi or a constant load).
Comment 6 Xi Ruoyao 2025-08-26 01:10:54 UTC
(In reply to Andrew Waterman from comment #5)
> My recollection is that Annex F leaves signaling NaN behavior
> implementation-defined, and so setting the invalid flag on signaling NaN is
> permitted but not required.

It is required by Glibc manual:

 -- Macro: int FE_SNANS_ALWAYS_SIGNAL

     This macro, defined by TS 18661-1:2014, is defined to ‘1’ in
     ‘fenv.h’ to indicate that functions and operations with signaling
     NaN inputs and floating-point results always raise the invalid
     exception and return a quiet NaN, even in cases (such as ‘fmax’,
     ‘hypot’ and ‘pow’) where a quiet NaN input can produce a non-NaN
     result.  Because some compiler optimizations may not handle
     signaling NaNs correctly, this macro is only defined if compiler
     support for signaling NaNs is enabled.  That support can be enabled
     with the GCC option ‘-fsignaling-nans’.

Thus the RISC-V implementation needs to raise it unless you announce -fsignaling-nans completely unsupported on RISC-V.
Comment 7 Andrew Waterman 2025-08-26 01:17:30 UTC
Ah, thanks.  Regardless, it seems the `feq` scheme is the preferable one.
Comment 8 Levi Zim 2025-08-26 04:25:01 UTC
Created attachment 62200 [details]
Preprocessed source code of test-nearbyint-except
Comment 9 Levi Zim 2025-08-26 04:26:25 UTC
(In reply to Vineet Gupta from comment #3)
> Can you provide the exact flags used to build the test. Also will be handy
> the fragment of preprocessed test specifically around SNAN_TESTS. Thx.

The exact commands used are:
(extracted from build logs)

gcc test-nearbyint-except.c -c -std=gnu11 -fgnu89-inline  -march=rv64gc -mabi=lp64d -O2 -pipe -Wformat -Wformat-security -fstack-clash-protection -g -ffile-prefix-map=/build/glibc/src=/usr/src/debug/glibc -Wall -Wwrite-strings -Wundef -Wimplicit-fallthrough -fmerge-all-constants -frounding-math -fstack-protector-strong -fno-common -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=3 -Wstrict-prototypes -Wold-style-definition -Wfree-labels -Wmissing-parameter-name 
-fmath-errno   -fno-omit-frame-pointer -fPIE          -I../include -I/build/glibc/src/glibc-build/math  -I/build/glibc/src/glibc-build  -I../sysdeps/unix/sysv/linux/riscv/rv64  -I../sysdeps/unix/sysv/linux/riscv/include -I../sysdeps/unix/sysv/linux/riscv  -I../sysdeps/riscv/nptl  -I../sysdeps/unix/sysv/linux/wordsize-64  -I../sysdeps/unix/sysv/linux/riscv/multiarch  -I../sysdeps/unix/sysv/linux/include -I../sysdeps/unix/sysv/linux  -I../sysdeps/nptl  -I../sysdeps/pthread  -I../sysdeps/gnu  -I../sysdeps/unix/inet  -I../sysdeps/unix/sysv  -I../sysdeps/unix  -I../sysdeps/posix  -I../sysdeps/riscv/rv64/rvd  -I../sysdeps/riscv/rv64/rvf  -I../sysdeps/riscv/rvf  -I../sysdeps/riscv/rvd  -I../sysdeps/riscv/rv64  -I../sysdeps/riscv/multiarch  -I../sysdeps/riscv  -I../sysdeps/ieee754/ldbl-128  -I../sysdeps/ieee754/dbl-64  -I../sysdeps/ieee754/flt-32  -I../sysdeps/wordsize-64  -I../sysdeps/ieee754  -I../sysdeps/generic  -I.. -I../libio -I. -nostdinc -isystem /usr/lib/gcc/riscv64-unknown-linux-gnu/15.1.1/include -isystem /usr/lib/gcc/riscv64-unknown-linux-gnu/15.1.1/include-fixed -isystem /usr/include -D_LIBC_REENTRANT -include /build/glibc/src/glibc-build/libc-modules.h -DMODULE_NAME=testsuite -include ../include/libc-symbols.h  -DPIC     -DTOP_NAMESPACE=glibc -o /build/glibc/src/glibc-build/math/test-nearbyint-except.o -MD -MP -MF /build/glibc/src/glibc-build/math/test-nearbyint-except.o.dt -MT /build/glibc/src/glibc-build/math/test-nearbyint-except.o                                                                                                                                                                                            
gcc -o /build/glibc/src/glibc-build/math/test-nearbyint-except -pie  -Wl,-O1 -nostdlib -nostartfiles  -Wl,-O1 -Wl,--sort-common -Wl,--as-needed -Wl,-z,relro -Wl,-z,now  -Wl,-z,relro  /build/glibc/src/glibc-build/csu/Scrt1.o /build/glibc
/src/glibc-build/csu/crti.o `gcc  --print-file-name=crtbeginS.o` /build/glibc/src/glibc-build/math/test-nearbyint-except.o /build/glibc/src/glibc-build/support/libsupport_nonshared.a /build/glibc/src/glibc-build/math/libm.so.6  -Wl,-dynamic-linker=/usr/lib/ld-linux-riscv64-lp64d.so.1 -Wl,-rpath-link=/build/glibc/src/glibc-build:/build/glibc/src/glibc-build/math:/build/glibc/src/glibc-build/elf:/build/glibc/src/glibc-build/dlfcn:/build/glibc/src/glibc-build/nss:/build/
glibc/src/glibc-build/nis:/build/glibc/src/glibc-build/rt:/build/glibc/src/glibc-build/resolv:/build/glibc/src/glibc-build/mathvec:/build/glibc/src/glibc-build/support:/build/glibc/src/glibc-build/misc:/build/glibc/src/glibc-build/debug
:/build/glibc/src/glibc-build/nptl:/lib/ -lgcc -Wl,--as-needed -lgcc_s  -Wl,--no-as-needed /build/glibc/src/glibc-build/libc.so.6 /build/glibc/src/glibc-build/libc_nonshared.a -Wl,--as-needed /build/glibc/src/glibc-build/elf/ld.so -Wl,-
-no-as-needed -lgcc -Wl,--as-needed -lgcc_s  -Wl,--no-as-needed `gcc  --print-file-name=crtendS.o` /build/glibc/src/glibc-build/csu/crtn.o                   

Here are the flags for building preprocessed source

gcc  test-nearbyint-except.i  -c -std=gnu11 -fgnu89-inline  -march=rv64gc -mabi=lp64d -O2 -pipe -Wformat -Wformat-security -fstack-clash-protection -g -ffile-prefix-map=/build/glibc/src=/usr/src/debug/glibc -Wall -Wwrite-strings -Wundef -Wimplicit-fallthrough -fmerge-all-constants -frounding-math -fstack-protector-strong -fno-common -U_FORTIFY_SOURCE -D_FORTIFY_SOURCE=3 -Wstrict-prototypes -Wold-style-definition -Wfree-labels -Wmissing-parameter-name -fmath-errno   -fno-omit-frame-pointer -fPIE
Comment 10 Joseph S. Myers 2025-08-26 19:45:45 UTC
FE_SNANS_ALWAYS_SIGNAL is, as quoted, about operations *with floating-point results*. The classification macros are bound to IEEE operations that must not raise "invalid" for any inputs. isnan wrongly raising exceptions is bug 66462. (Comparison macros, however, unlike classification ones, should raise "invalid" for signaling NaNs.)
Comment 11 Aurelien Jarno 2025-09-05 08:38:21 UTC
(In reply to Vineet Gupta from comment #4)
> Also I'm thinking to model this based on existing libc implementation which
> has been around for a while and should hopefully be correct.
> 
> What glibc does is early check for nan and return x + x if so. See [1]
> 
> This implicitly
>   - doesn't restore flags for nan case (this PR/121652)
>   - restores flag otherwise (retains fix for PR/121534)

In addition the x+x addition converts a possible snan into a nan.

> https://github.com/bminor/glibc/blob/master/sysdeps/riscv/rv64/rvd/s_round.c
> 
> This requires the gcc builtin to call equivalent of __builtin_isnan().
> 
> However looks like there's a different problem lurking under the hood so let
> me run it by this group who care about these subtleties.
> 
> Consider following test: -O2 -march=rv64gc -mabi=lp64d
> 
> `
> int myisnan(double __x)
> {
>    return __builtin_isnan(__x);
> }
> `
> 
> generates
> 
> `
> myisnan:
> 	feq.d	a0,fa0,fa0
> 	xori	a0,a0,1
> 	ret
> `
> 
> FEQ.D is a quite comparison meaning it *can* set the invalid operation
> exception flag if either input is a signaling NaN.

I think it is what we want no? In addition this is what is currently used by the GLIBC code.

At the end it seems the GLIBC round code is correct and widely tested, so we just want to mimic it in the builtin.
Comment 12 Aurelien Jarno 2025-09-05 08:48:43 UTC
(In reply to Aurelien Jarno from comment #11)
> At the end it seems the GLIBC round code is correct and widely tested, so we
> just want to mimic it in the builtin.

The same way the comments in the GCC code mention saving and restoring flags due to the invalid flag. The reason why they are saved and restored in GLIBC is actually the inexact flag.
Comment 13 Aurelien Jarno 2025-09-05 12:44:20 UTC
I am starting to wonder if it is really worth inlining so much code compared to a call to round(), and if it is not better to not try to handle NaN and fflags, requiring both !flag_trapping_math and flag_trapping_math. I even wonder if that wasn't the intent in the original code, just the condition was wrong and should have been:
-    && (TARGET_ZFA || flag_fp_int_builtin_inexact || !flag_trapping_math)
+    && (TARGET_ZFA || (flag_fp_int_builtin_inexact && !flag_trapping_math))
Comment 14 Xi Ruoyao 2025-09-05 12:51:13 UTC
(In reply to Aurelien Jarno from comment #13)
> I am starting to wonder if it is really worth inlining so much code compared
> to a call to round(), and if it is not better to not try to handle NaN and
> fflags, requiring both !flag_trapping_math and flag_trapping_math. I even
> wonder if that wasn't the intent in the original code, just the condition
> was wrong and should have been:
> -    && (TARGET_ZFA || flag_fp_int_builtin_inexact || !flag_trapping_math)
> +    && (TARGET_ZFA || (flag_fp_int_builtin_inexact && !flag_trapping_math))

It's not wrong: the GCC documentation clearly says:

    The default is -ffp-int-builtin-inexact, allowing the exception to
    be raised, unless C23 or a later C standard is selected.  This
    option does nothing unless -ftrapping-math is in effect.

So if -fno-trapping-math, we should completely ignore flag_fp_int_builtin_exact.

(Also the word above seems a little outdated as now GCC defaults to -std=gnu23.)

If you'd make the expand only work for -fno-trapping-math you should just write TARGET_CFA || !flag_trapping_math instead.
Comment 15 Aurelien Jarno 2025-09-05 13:08:39 UTC
(In reply to Xi Ruoyao from comment #14)
> (In reply to Aurelien Jarno from comment #13)
> > I am starting to wonder if it is really worth inlining so much code compared
> > to a call to round(), and if it is not better to not try to handle NaN and
> > fflags, requiring both !flag_trapping_math and flag_trapping_math. I even
> > wonder if that wasn't the intent in the original code, just the condition
> > was wrong and should have been:
> > -    && (TARGET_ZFA || flag_fp_int_builtin_inexact || !flag_trapping_math)
> > +    && (TARGET_ZFA || (flag_fp_int_builtin_inexact && !flag_trapping_math))
> 
> It's not wrong: the GCC documentation clearly says:
> 
>     The default is -ffp-int-builtin-inexact, allowing the exception to
>     be raised, unless C23 or a later C standard is selected.  This
>     option does nothing unless -ftrapping-math is in effect.
> 
> So if -fno-trapping-math, we should completely ignore
> flag_fp_int_builtin_exact.
> 
> (Also the word above seems a little outdated as now GCC defaults to
> -std=gnu23.)
> 
> If you'd make the expand only work for -fno-trapping-math you should just
> write TARGET_CFA || !flag_trapping_math instead.

Indeed you are correct that there is no need to check for the two. That said my comment still stands, I believe the original code was not intended to handle all cases and that the way to fix that is just to fix the condition as you proposed. Otherwise I find strange that flag_fp_int_builtin_inexact is mentioned in the condition while not having the corresponding code to handle that.
Comment 16 Jeffrey A. Law 2025-09-05 13:59:47 UTC
WRT c#13, yes, it's worth it, the performance gains were huge.  Of course if we look out Zfa should become ubiquitious and that other path won't matter.  But we're not at that point yet IMHO.
Comment 17 Aurelien Jarno 2025-09-05 14:14:16 UTC
(In reply to Jeffrey A. Law from comment #16)
> WRT c#13, yes, it's worth it, the performance gains were huge.  Of course if
> we look out Zfa should become ubiquitious and that other path won't matter. 
> But we're not at that point yet IMHO.

Yep, but they were huge for the -ffast-math case used by SPEC2017. The code works fine for that case, and changing the condition of the pattern as suggested does not change the code generated with -ffast-math and thus the SPEC2017 performance.

My point is do we want to inline the case that handles both inexact and NaN? I guess we are talking about going from 7 to 13 instructions.
Comment 18 Aurelien Jarno 2025-09-07 21:26:59 UTC
Created attachment 62345 [details]
Patch / Proof of concept

In case we want to keep the condition unchanged, here is a patch to correctly handle the sNaN case. It checks for NaN using feq, and jump to a code adding the two arguments in case flag_trapping_math is active to convert the sNaN into a qNan. This is similar to what is done on the GLIVC side. This means there is no need to save and restore the fflags anymore, as this is allowed by -ffp-int-builtin-inexact.

Note that it is my first changes in that area of GCC, and I am not fully sure I have done things correctly with the jumps, and especially with the emit_barrier() call. That's why it's maybe only a proof of concept. That said I have however checked and tested the generated code for various combinaison of -f(no-)fp-int-builtin-inexact and -f(no-)signaling-nans. I also checked that the GLIBC testsuite fully passes with this change.
Comment 19 Vineet Gupta 2025-09-08 16:25:39 UTC
(In reply to Aurelien Jarno from comment #18)
> > 
> > However looks like there's a different problem lurking under the hood so let
> > me run it by this group who care about these subtleties.
> > 
> > Consider following test: -O2 -march=rv64gc -mabi=lp64d
> > 
> > `
> > int myisnan(double __x)
> > {
> >    return __builtin_isnan(__x);
> > }
> > `
> > 
> > generates
> > 
> > `
> > myisnan:
> > 	feq.d	a0,fa0,fa0
> > 	xori	a0,a0,1
> > 	ret
> > `
> > 
> > FEQ.D is a quite comparison meaning it *can* set the invalid operation
> > exception flag if either input is a signaling NaN.
> 
> I think it is what we want no? In addition this is what is currently used by
> the GLIBC code.

Yeah I was just pointing a different/orthogonal potential existing issue. That current __builtin_isnan() can potentially raising an FP exception (Invalid op). This could be fine for its intended usage in round builtin, but not sure if that is fine as a general API / implementation agreement etc.

> At the end it seems the GLIBC round code is correct and widely tested, so we
> just want to mimic it in the builtin.

Yes totally agree on that.
Comment 20 Vineet Gupta 2025-09-08 16:33:46 UTC
(In reply to Aurelien Jarno from comment #18)
> Created attachment 62345 [details]
> Patch / Proof of concept
> 
> In case we want to keep the condition unchanged, here is a patch to
> correctly handle the sNaN case. 

You mean the expander gate ? I don't see a strong argument to not change it if we can agree it is wrong. I still don't fully comprehend all the discussions above regarding this, but I won't mind changing that too (in addition to other changes u proposed). With review and enough testing I think that change should be fine too.


> It checks for NaN using feq, and jump to a
> code adding the two arguments in case flag_trapping_math is active to
> convert the sNaN into a qNan. This is similar to what is done on the GLIVC
> side. This means there is no need to save and restore the fflags anymore, as
> this is allowed by -ffp-int-builtin-inexact.

Cool.

 
> Note that it is my first changes in that area of GCC, and I am not fully
> sure I have done things correctly with the jumps, and especially with the
> emit_barrier() call. That's why it's maybe only a proof of concept. 

I think its worthwhile to pos tit as RFC to the list. That way we get more eyes to stare at the patch especially with the expertise of Joseph and others proficient in the area.

> That said I have however checked and tested the generated code for various
> combinaison of -f(no-)fp-int-builtin-inexact and -f(no-)signaling-nans. I
> also checked that the GLIBC testsuite fully passes with this change.

Nice.

You change for early Nan detection and removal of save/restore look sane to me.
Comment 21 Xi Ruoyao 2025-09-17 01:10:30 UTC
(In reply to Vineet Gupta from comment #19)

> Yeah I was just pointing a different/orthogonal potential existing issue.
> That current __builtin_isnan() can potentially raising an FP exception
> (Invalid op). This could be fine for its intended usage in round builtin,
> but not sure if that is fine as a general API / implementation agreement etc.

That is PR 66462.
Comment 22 Aurelien Jarno 2025-09-26 17:32:14 UTC
I have posted a patch to the gcc-patches mailing-list: https://gcc.gnu.org/pipermail/gcc-patches/2025-September/696217.html
Comment 23 GCC Commits 2025-10-02 15:15:21 UTC
The master branch has been updated by Jeff Law <law@gcc.gnu.org>:

https://gcc.gnu.org/g:60c6f92fb192352d784ab3153a9e11c19a3216a0

commit r16-4191-g60c6f92fb192352d784ab3153a9e11c19a3216a0
Author: Aurelien Jarno <aurelien@aurel32.net>
Date:   Thu Oct 2 09:05:34 2025 -0600

    [PATCH v2] RISC-V: fix __builtin_round NaN handling [PR target/121652]
    
    __builtin_round() fails to correctly generate invalid exceptions for NaN
    inputs when -ftrapping-math is used (which is the default). According to
    the specification, an invalid exception should be raised for sNaN, but
    not for qNaN.
    
    Commit f12a27216952 ("RISC-V: fix __builtin_round clobbering FP...")
    attempted to avoid raising an invalid exception for qNaN by saving and
    restoring the FP exception flags. However this inadvertently suppressed
    the invalid exception for sNaN as well.
    
    Instead of saving/restoring fflags, this patch uses the same approach
    than the well tested GLIBC round implementation. When flag_trapping_math
    is enabled, it first checks whether the input is a NaN using feq.s/d. In
    that case it adds the input value with itself to possibly convert sNaN
    into qNaN. With this change, the glibc testsuite passes again.
    
    The generated code with -ftrapping-math now looks like:
    
    convert_float_to_float_round
      feq.s       a5,fa0,fa0
      beqz        a5,.L6
      auipc       a5,0x0
      flw         fa4,42(a5)
      fabs.s      fa5,fa0
      flt.s       a5,fa5,fa4
      beqz        a5,.L5
      fcvt.w.s    a5,fa0,rmm
      fcvt.s.w    fa5,a5
      fsgnj.s     fa0,fa5,fa0
      ret
    .L6:
      fadd.s      fa0,fa0,fa0
    .L5:
      ret
    
    With -fno-trapping-math, the additional checks are omitted so the
    resulting code is unchanged.
    
    In addition this fixes the following failures:
    FAIL: gcc.target/riscv/rvv/autovec/vls/math-nearbyint-1.c -O3 -ftree-vectorize -mrvv-vector-bits=scalable  scan-assembler-times frflags\\s+[atx][0-9]+ 32
    FAIL: gcc.target/riscv/rvv/autovec/vls/math-nearbyint-1.c -O3 -ftree-vectorize -mrvv-vector-bits=scalable  scan-assembler-times fsflags\\s+[atx][0-9]+ 32
    
    Fixes: f652a35877e3 ("This is almost exclusively Jivan's work....")
    Fixes: f12a27216952 ("RISC-V: fix __builtin_round clobbering FP...")
    
            PR target/121652
    
    gcc/ChangeLog:
    
            * config/riscv/riscv.md (round_pattern): special case NaN input
            instead of saving/restoring fflags.
    
    gcc/testsuite/ChangeLog:
    
            * gcc.target/riscv/rvv/autovec/vls/math-nearbyint-1.c: Adjust
            scan pattern for fewer instances of frflags/fsrflags.
Comment 24 Jeffrey A. Law 2025-10-02 15:16:47 UTC
Update regression marker targets.  Expecting to backport in a week or so before closing.
Comment 25 GCC Commits 2025-10-08 13:45:04 UTC
The releases/gcc-15 branch has been updated by Jeff Law <law@gcc.gnu.org>:

https://gcc.gnu.org/g:ddf34234be385a4f2750e7da790ff9218067d881

commit r15-10399-gddf34234be385a4f2750e7da790ff9218067d881
Author: Aurelien Jarno <aurelien@aurel32.net>
Date:   Thu Oct 2 09:05:34 2025 -0600

    [PATCH v2] RISC-V: fix __builtin_round NaN handling [PR target/121652]
    
    __builtin_round() fails to correctly generate invalid exceptions for NaN
    inputs when -ftrapping-math is used (which is the default). According to
    the specification, an invalid exception should be raised for sNaN, but
    not for qNaN.
    
    Commit f12a27216952 ("RISC-V: fix __builtin_round clobbering FP...")
    attempted to avoid raising an invalid exception for qNaN by saving and
    restoring the FP exception flags. However this inadvertently suppressed
    the invalid exception for sNaN as well.
    
    Instead of saving/restoring fflags, this patch uses the same approach
    than the well tested GLIBC round implementation. When flag_trapping_math
    is enabled, it first checks whether the input is a NaN using feq.s/d. In
    that case it adds the input value with itself to possibly convert sNaN
    into qNaN. With this change, the glibc testsuite passes again.
    
    The generated code with -ftrapping-math now looks like:
    
    convert_float_to_float_round
      feq.s       a5,fa0,fa0
      beqz        a5,.L6
      auipc       a5,0x0
      flw         fa4,42(a5)
      fabs.s      fa5,fa0
      flt.s       a5,fa5,fa4
      beqz        a5,.L5
      fcvt.w.s    a5,fa0,rmm
      fcvt.s.w    fa5,a5
      fsgnj.s     fa0,fa5,fa0
      ret
    .L6:
      fadd.s      fa0,fa0,fa0
    .L5:
      ret
    
    With -fno-trapping-math, the additional checks are omitted so the
    resulting code is unchanged.
    
    In addition this fixes the following failures:
    FAIL: gcc.target/riscv/rvv/autovec/vls/math-nearbyint-1.c -O3 -ftree-vectorize -mrvv-vector-bits=scalable  scan-assembler-times frflags\\s+[atx][0-9]+ 32
    FAIL: gcc.target/riscv/rvv/autovec/vls/math-nearbyint-1.c -O3 -ftree-vectorize -mrvv-vector-bits=scalable  scan-assembler-times fsflags\\s+[atx][0-9]+ 32
    
    Fixes: f652a35877e3 ("This is almost exclusively Jivan's work....")
    Fixes: f12a27216952 ("RISC-V: fix __builtin_round clobbering FP...")
    
            PR target/121652
    
    gcc/ChangeLog:
    
            * config/riscv/riscv.md (round_pattern): special case NaN input
            instead of saving/restoring fflags.
    
    gcc/testsuite/ChangeLog:
    
            * gcc.target/riscv/rvv/autovec/vls/math-nearbyint-1.c: Adjust
            scan pattern for fewer instances of frflags/fsrflags.
    
    (cherry picked from commit 60c6f92fb192352d784ab3153a9e11c19a3216a0)
Comment 26 Jeffrey A. Law 2025-10-08 13:45:40 UTC
Cherry-picked to the gcc-15 branch.  Closing as fixed.
Comment 27 Aurelien Jarno 2025-10-08 21:55:23 UTC
(In reply to Jeffrey A. Law from comment #26)
> Cherry-picked to the gcc-15 branch.  Closing as fixed.

Thanks Jeff!