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

            Bug ID: 128868
           Summary: [arm] copysignf returns the sign operand when the
                    result shares a register with the magnitude
                    (-mfloat-abi=soft)
           Product: gcc
           Version: 12.5.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: target
          Assignee: unassigned at gcc dot gnu.org
          Reporter: azoff at gcc dot gnu.org
  Target Milestone: ---

With -mfloat-abi=soft on a Thumb-2-capable architecture, the copysignsf3
expander in arm.md emits:

  op0 = op2;                 // sign
  insv op0[0:30] = op1;      // magnitude bits

If op0 and op1 are the same pseudo, the magnitude is overwritten before it
is read, and the result is the sign operand.  This happens after out-of-SSA
coalescing, for example when the result feeds a PHI together with the
magnitude.

Testcase:

float
f (float x, float y, int c)
{
  if (c)
    x = __builtin_copysignf (x, y);
  return x;
}

$ arm-none-eabi-gcc -O2 -mcpu=cortex-m3 -mthumb -mfloat-abi=soft -S t.c

f:
        cbz     r2, .L2
        mov     r0, r1          @ returns y; the magnitude in r0 is lost
.L2:
        bx      lr

The bug shows at -O1 and above; -O0 is correct.  ARM state
(-march=armv7-a -marm) gives "cmp r2, #0; movne r0, r1".

Plain C code is affected too, not just __builtin_copysignf.  copysignf
from <math.h> gives the same wrong result.  So does x = -fabsf (x) in
the same situation, because GCC rewrites it to copysignf (x, -1.0f); it
then returns -1.0 instead of -|x|.

Affected: -mfloat-abi=soft on v6t2, v7-a/r/m, v7e-m, v8-a/r (AArch32),
v8-m.main and v8.1-m.main, in both ARM and Thumb state.

Not affected: softfp/hard, v6-m, v8-m.base and architectures before v6t2,
and copysigndf3, which reads its inputs into scratch registers first.

Introduced by r5-5433-g3403c4c78e001d (2014-11-28), so all releases since
GCC 5 are probably affected.  Verified on trunk only.

Found by the Sashiko AI review of the v2 hard-float copysign series:
https://gcc.sashiko.dev/#/patchset/bmm.hnq95ivlkm.gcc.gcc.azoff.262.2.0%40forge-stage.sourceware.org

This description was generated with the help of an LLM and reviewed
before posting.

Reply via email to