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

            Bug ID: 128882
           Summary: [15/16/17 Regression] wrong code at -O2: subtraction
                    in a narrower type recognized as .SAT_SUB of the wider
                    operands
           Product: gcc
           Version: 17.0
            Status: UNCONFIRMED
          Keywords: wrong-code
          Severity: normal
          Priority: P3
         Component: tree-optimization
          Assignee: unassigned at gcc dot gnu.org
          Reporter: liuhongt at gcc dot gnu.org
  Target Milestone: ---
            Target: x86_64-pc-linux-gnu

$ cat t.c
[[gnu::noipa]] unsigned
f (unsigned a, unsigned b)
{
  unsigned short d = (unsigned short) a - (unsigned short) b;
  return a >= b ? d : 0;
}

int
main ()
{
  if (f (0x10005, 3) != 2)
    __builtin_abort ();
  return 0;
}

$ gcc -O2 t.c && ./a.out
Aborted

GCC 14 is fine at all optimization levels.  GCC 15, 16 and trunk fail at
-O2 and -O3 (-O0, -O1 and -Os are fine).  The optimized dump has

  prephitmp_10 = .SAT_SUB (a_4(D), b_5(D));

The difference is computed in unsigned short, so it wraps at 16 bits and
is not a saturating subtraction of a and b: f (0x10005, 3) must be 2,
but .SAT_SUB gives 0x10002.

r15-1671 changed the X >= Y ? X - Y : 0 pattern (now in match-sat-alu.pd)
to (convert? (minus (convert1? @0) (convert1? @1))) so that a truncated
.SAT_SUB is recognized.  Nothing stops convert1 from narrowing @0 and @1.
The matcher is shared by widening_mul and the vectorizer.  The
X <= Y ? 0 : X - Y form added in r17-4219 has the same hole, though I
couldn't get the reproducer above into that shape.

This is separate from PR128872, where the match is valid but widening_mul
drops the conversion to the type of the lhs.

Reply via email to