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

            Bug ID: 105198
           Summary: Wrong code for C loop (GCC 12 -O2, GCC 11 -O3)
           Product: gcc
           Version: 12.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: middle-end
          Assignee: unassigned at gcc dot gnu.org
          Reporter: tomas.kalibera at gmail dot com
  Target Milestone: ---

Created attachment 52770
  --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=52770&action=edit
Reproducible example to compile and execute (see comment in file)

It seems that GCC produces wrong code for function next_set found in R package
MASS (traced down by Brian Ripley):

static void next_set(int *x, int n, int k)
{
    int i, j, tmp;

    j = k - 1;
    tmp = x[j]++;
    while(j > 0 && x[j] >= n - (k - 1 -j)) tmp = ++x[--j];
    for(i = j+1; i < k; i++)  x[i] =  ++tmp;
}

The attached standalone example reproduces the problem on a slightly modified
and instrumented variant of the function, for one specific input, see comments
in the code. 

Correct output (GCC 12 -O1, and can be seen from the C code):

n == 5, k == 3, x == 0 1 4
tmp == 2, j == 1, x == 0 2 5

Incorrect but seen on x86_64/Linux (GCC 12 -O2, GCC 11 -O3):

n == 5, k == 3, x == 0 1 4
tmp == 4, j == 2, x == 0 1 5

One can modify the example to get slightly simpler native code via writing to
the array in "main" via volatile variables.

It works with GCC 10 -O3.

Reply via email to