Skip to content

[LoopInterchange] Incorrect handling of reductions #148228

Closed
@kasuga-fj

Description

@kasuga-fj

Consider the following code:

#include <limits.h>

int A[2][2] = {
  { INT_MAX, INT_MAX },
  { INT_MIN, INT_MIN },
};

int f(void) {
  int sum = 0;
  for (int i = 0; i < 2; i++)
    for (int j = 0; j < 2; j++)
      sum += A[j][i];
  return sum;
}

In the original code, sum is calculated as follows:

(i, j) | sum
-------|--------------------
(0, 0) | INT_MAX
(0, 1) | -1
(1, 0) | INT_MAX - 1 
(1, 1) | -2

On the other hand, if they are interchanged, the calculation proceeds as shown below, resulting in signed integer overflow:

(i, j) | sum
-------|--------------------
(0, 0) | INT_MAX
(1, 0) | INT_MAX + INT_MAX
...

Currently, such an interchange can be applied in some cases.
godbolt: https://godbolt.org/z/oqYs14va9

Metadata

Metadata

Assignees

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions