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

            Bug ID: 114052
           Summary: Wrong code at -O2 for well-defined infinite loop
           Product: gcc
           Version: 14.0
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c
          Assignee: unassigned at gcc dot gnu.org
          Reporter: maxdamantus at gmail dot com
  Target Milestone: ---

int foo(void) {
        int counter = 0;
        while (1) {
                if(counter >= 2)
                        continue;
                printf("%i\n", counter++);
        }
        return 0;
}

This is actually from a reddit post I came across:
https://www.reddit.com/r/C_Programming/comments/yugk1y/gcc_optimization_behavior/

There are theories in the comments above about UB due to integer overflow or
non-terminating loops, but I'm pretty sure they don't apply (correct me if I'm
wrong).

The controlling expression of the loop is a constant expression, so it can't be
assumed to terminate, and the loop should repeat infinitely with `counter ==
2`, so no overflow should occur. Instead, part of the loop is presumably DCEd,
so control continues outside of the function.

Versions before gcc-13 had slightly different incorrect behaviours occur when
replacing `2` in the condition with `3`, `4`, `5`, etc. These larger numbers
appear to behave correctly now.

godbolt link:
https://godbolt.org/#z:OYLghAFBqd5QCxAYwPYBMCmBRdBLAF1QCcAaPECAMzwBtMA7AQwFtMQByARg9KtQYEAysib0QXACx8BBAKoBnTAAUAHpwAMvAFYTStJg1AB9U8lJL6yAngGVG6AMKpaAVxYMQAJlIOAMngMmABy7gBGmMQSAJykAA6oCoS2DM5uHnoJSTYCAUGhLBFRXFwWmFY5DEIETMQEae6ePpaY1inVtQR5IeGRMRY1dQ0ZpQqDXYE9hX0lAJQWqK7EyOwcAKReAMyByG5YANRrm45j%2BKgAdAhH2GsaAIIb2wy7rgdHJwTotHhhl9e3D3ugQI%2B34qAgADdUHh0LMjgAhAEA4H7FhMQKQ6Gww4AdkR932hKJhKUBAhYVcVAgp0WBFI%2B2Ccj8fnpxgAkgB5YLwgBi9I0cM2%2BLuxOJxEwBCWDFBqHBguFaxxABEkUDBDLwVCYbNccLRUSUWhXIJIodNkr9hoEQD9YSAO4IOiYfYQLg6xV621evBUo0m4hmm7m/ZeOEEr0R/VoQSBVyYa3hyPEuLEYFUjZeDYAVjwayzjgYGfpfoIkQ2iK88PlNttipVidF4slxGlVqFSOVqruKKCEMixlEtHo6Ex2t1Nf1cVcBAUEAzeBYWSSYXoYDAGerDbFEql%2B0kmfb9zrAI481onCzvE8HC0pFQnEc%2BwUi2WzsePFIBE0p/mAGsQJsmznIBIGgWBABs%2BicJIV7fnenC8AoIAaJ%2B37zHAsBIGgi5OmQFAQNhcS4SgwBcJsPg0LQpbEEhEBhHBYSBLUACenAfoxzDEMxHJhNorRftwvDYWwggcgwtCsTevBYBSwCOGItBIYJpBYGiRjiFJKl4OKbR9kpt6YKorTTqst7AuUcHfGExAsc4WBwQQqYsGxp58AYwAKAAangmB2hycSMC5MiCCIYjsFIwXyEoahwbopQGEYICmAO%2Bg/EhkDzKgcSVEpAC0HJeLwqB9sQqZYOlEDzC0bR2BADjDJ4pT%2BJMBRFJkiTJAIDXtdkKTdK1MxlBU7TjN1ozlPxI2dP1vTFAMnRjfNdQzdMxRVS%2BKwSGeF6wZp94cPsqgABzgbl4GSPswDIMg%2BxkecXgurghAkIcWxurwAlaLMf4AUBYH/SBkHnhwMGkNet77YhyGoVJ6EwIgIC0lOdL4YRuHBKwqzHad52Xddt1AYVvj4EQZV6PwIWDuF0gU1FKjqJpcWkHaNlxC520cJeYNwftHLTsj%2ByoFQh0nWdF1XTdd0PRAzg4fQAbvrMH1oT9gHAQD/1QSDu0QwhFjQ59P5a0T4NFXrhvfaQJVJHYkhAA

Seems to have started happening in gcc 8.1, still reproducible from git
version, `basepoints/gcc-14-9077-g52490278466`.

Reply via email to