GCC turning on O2 causes bug when 128-bit integer is subscripted

Viewed 130
#include <cstdio>

__int128 idx;

int main() {
    int a[2] = {1, 2};
    idx++;
    a[idx] = 0;
    printf("%d %d", a[0], a[1]);
}

After turning on O2 a[idx] = 0 not executed. I guess it shouldn't be undefined behavior. Is this a bug in the compiler?

https://godbolt.org/z/qqccd9oEj

1 Answers

Looking at the compiler output for gcc-12.1 -std=c++20 -O2 -W -Wall

.LC0:
        .string "%d %d"
main:
        sub     rsp, 8
        mov     edx, 2
        add     QWORD PTR idx[rip], 1
        mov     esi, 1
        adc     QWORD PTR idx[rip+8], 0
        mov     edi, OFFSET FLAT:.LC0
        xor     eax, eax
        call    printf
        xor     eax, eax
        add     rsp, 8
        ret
idx:
        .zero   16

The problem is mov edx, 2. That is just wrong, it should read a[1] and optimize that to 0 not 2.

clang gets it right but still generates horrible code. idx should get optimized out.

You should file that as compiler bug.

Related