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

            Bug ID: 127336
           Summary: wrong code with __atomic_add_fetch() at -O1 and above
                    on x86
           Product: gcc
           Version: 17.0
            Status: UNCONFIRMED
          Keywords: wrong-code
          Severity: normal
          Priority: P3
         Component: target
          Assignee: unassigned at gcc dot gnu.org
          Reporter: zsojka at seznam dot cz
  Target Milestone: ---
              Host: x86_64-pc-linux-gnu
            Target: x86_64-pc-linux-gnu

Created attachment 65564
  --> https://gcc.gnu.org/bugzilla/attachment.cgi?id=65564&action=edit
reduced testcase

Output:
$ x86_64-pc-linux-gnu-gcc -O testcase.c
$ ./a.out
Aborted                    ./a.out

$ x86_64-pc-linux-gnu-gcc -O testcase.c -S -masm=intel -fverbose-asm -o-
...
# testcase.c:8:   u /= __atomic_add_fetch (&s, s, 0);
        mov     ecx, DWORD PTR "s"[rip] # s, s
        lock xadd       DWORD PTR "s"[rip], ecx #,, _9
        add     ecx, DWORD PTR "s"[rip] # tmp109, s
# testcase.c:8:   u /= __atomic_add_fetch (&s, s, 0);
        mov     eax, DWORD PTR "u"[rip] # u, u
        mov     edx, 0  # tmp112,
        div     ecx     # tmp109
        mov     DWORD PTR "u"[rip], eax # u, _5
...

The instruction:
...
        lock xadd       DWORD PTR "s"[rip], ecx #,, _9
loads the old value of "s" to ecx, and
        add     ecx, DWORD PTR "s"[rip] # tmp109, s
adds the sum to the addend, so we have 3*9 instead of 2*9

$ x86_64-pc-linux-gnu-gcc -v
Using built-in specs.
COLLECT_GCC=/repo/gcc-trunk/binary-latest-amd64/bin/x86_64-pc-linux-gnu-gcc
COLLECT_LTO_WRAPPER=/repo/gcc-trunk/binary-trunk-20260911053823-g2af7be77bc6-checking-yes-rtl-df-extra-nobootstrap-amd64/bin/../libexec/gcc/x86_64-pc-linux-gnu/17.0.0/lto-wrapper
Target: x86_64-pc-linux-gnu
Configured with: /repo/gcc-trunk//configure --enable-languages=c,c++
--enable-valgrind-annotations --disable-nls --enable-checking=yes,rtl,df,extra
--disable-bootstrap --build=x86_64-pc-linux-gnu --host=x86_64-pc-linux-gnu
--target=x86_64-pc-linux-gnu --with-ld=/usr/bin/x86_64-pc-linux-gnu-ld
--with-as=/usr/bin/x86_64-pc-linux-gnu-as --enable-libsanitizer
--disable-libstdcxx-pch
--prefix=/repo/gcc-trunk//binary-trunk-20260911053823-g2af7be77bc6-checking-yes-rtl-df-extra-nobootstrap-amd64
Thread model: posix
Supported LTO compression algorithms: zlib zstd
gcc version 17.0.0 20260910 (experimental) (GCC)

Reply via email to