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

            Bug ID: 129012
           Summary: UBSan: signed overflow negating ratio == INT64_MIN in
                    get_computation_cost (tree-ssa-loop-ivopts.cc)
           Product: gcc
           Version: 17.0
            Status: UNCONFIRMED
          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-small.c

struct S { int a; __int128 b; } c[8];

void f(void) {
  for (int i = 0; i < 8; i++)
    c[i].a = c[i].b = i * 0x8000000000000000ull;
}

With a compiler built with `-fsanitize=undefined` (bootstrap-ubsan), `gcc -O1
-c repro-small.c` (also -O2, -Os) reports:

```
gcc/tree-ssa-loop-ivopts.cc:4942:12: runtime error: negation of
-9223372036854775808 cannot be represented in type 'long int'; cast to an
unsigned type to negate this value to itself
    #0 get_computation_cost gcc/tree-ssa-loop-ivopts.cc:4942
    #1 determine_group_iv_cost_generic gcc/tree-ssa-loop-ivopts.cc:4988
    #2 determine_group_iv_cost gcc/tree-ssa-loop-ivopts.cc:5726
    #3 determine_group_iv_costs gcc/tree-ssa-loop-ivopts.cc:5998
    #4 tree_ssa_iv_optimize_loop gcc/tree-ssa-loop-ivopts.cc:8303
```

The step of the address IV for `c[i].b` relative to the `i *
0x8000000000000000` IV gives a ratio of `HOST_WIDE_INT_MIN`, and
get_computation_cost negates it (current trunk, tree-ssa-loop-ivopts.cc:4958):

```c
  /* Turn a + i * (-c) into a - i * c.  */
  if (ratio < 0 && comp_inv && !integer_zerop (comp_inv))
    aratio = -ratio;
  else
    aratio = ratio;
```

`aratio` is only used for cost estimates (mult_by_coeff_cost etc.), so the
generated code is not affected; the negation should be done in an unsigned type
or the INT64_MIN case excluded.


## Checked versions
- gcc trunk 113f18c2309 (2026-10-17), built with -fsanitize=address,undefined:
reported at -O1, -O2, -Os
- The code is unchanged in trunk 1ed04a18ef6 (2026-11-23) so it should
reproduce in the trunk as well.

Thanks.

Reply via email to