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

            Bug ID: 129218
           Summary: [14/15/16/17 Regression] wrong code at -O3: after loop
                    unswitching on a switch, `if (!(a / -3 & 128)) d = c;`
                    is dropped in the "no case taken" copy since r14-3982
           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: haoxintu at gmail dot com
  Target Milestone: ---

Hi,

$cat repro.c

char b;
int c, d = 3;
long g;

int
main (void)
{
  for (int j = 0; j < 8; j++)
    {
      char a = g;
      switch (a)
        {
        case 3:
          b = c;
          /* FALLTHRU */
        case -60 ... -58:
          b = 0;
        }
      _Bool f = !(a / -3 & 128);
      if (f)
        d = c;
    }
  if (d != 0)
    __builtin_abort ();
  return 0;
}

$ gcc -O2 repro.c && ./a.out                        # ok (also -O0, -O1, -Os)
$ gcc -O3 repro.c && ./a.out                        # Aborted
$ gcc -O2 -funswitch-loops repro.c && ./a.out       # Aborted
$ gcc -O3 -fno-unswitch-loops repro.c && ./a.out    # ok
$ gcc -O3 -fno-tree-forwprop repro.c && ./a.out     # ok
$ gcc -O3 -fno-thread-jumps repro.c && ./a.out      # ok

`g == 0`, so `a == 0` in every iteration; no case label matches, `0 / -3 & 128
== 0`, so `f == 1` and `d = c` (0) runs.
At -O3 the loop is unswitched on the switch ("unswitching loop 1 on 'switch'
with condition: (unsigned char) a_12 + 60 <= 2", then "unswitching loop 2 on
'switch' with condition: a_12 == 3"). In the resulting copy for "neither case"
(which contains `a == 0`), the store `d = c` is gone and `d` keeps 3.

## Cause

**Bisected to r14-3982** (9ea74d235c7, "tree-optimization/111294 - better DCE
after forwprop", Richard Biener, 2023-09-14):
https://gcc.gnu.org/git/?p=gcc.git;a=commit;h=9ea74d235c7e7816b996a17c61288f02ef767985

C-only builds of the two commits (`--enable-checking=release`), same testcase:

| Commit | repro.c -O3 |
|---|---|
| 0f1f6cf872a (parent of r14-3982) | ok |
| **9ea74d235c7 (r14-3982) "tree-optimization/111294 - better DCE after
forwprop"** | **aborts** |

The commit makes forwprop remove statements left dead after folding. Together
with loop unswitching on the switch and jump
threading (each of -fno-unswitch-loops, -fno-tree-forwprop, -fno-thread-jumps
avoids it), the `d = c` store of the default copy is
lost.

## Checked versions

- gcc trunk c10b819941b (2026-11-30): -O3 and -O2 -funswitch-loops abort; -O0,
-O1, -O2, -Os ok.
- gcc 16.0.1, 15.2, 14.3, 14.2, 14.1 (Compiler Explorer): -O3 aborts.
- gcc 13.4: ok.

Godbolt (gcc trunk, -O3 aborts, -O0 runs): https://godbolt.org/z/q4YG3h1GY

Thanks.

Reply via email to