Why does std atomic insert 5 to the stack

Viewed 679

I wanted to see how std::atomic is translated to assembly. To do that I wrote the following code but there is something I do not understand.

The following code:

int main(void)
{
    std::atomic<int> a;
    a.fetch_add(0);
    return 0;
}

Is compiled by GCC to:

1 |  push    rbp
2 |  mov     rbp, rsp
3 |  mov     DWORD PTR [rbp-4], 0
4 |  mov     DWORD PTR [rbp-8], 5
5 |  mov     edx, DWORD PTR [rbp-4]
6 |  lea     rax, [rbp-12]
7 |  lock xadd       DWORD PTR [rax], edx
8 |  mov     eax, 0
9 |  pop     rbp
10|  ret

Why does GCC push "5" (on line 4) onto the stack?

1 Answers

If you take the godbolt link Richard Critten very helpfully posted in a comment, and change the GCC command line to use -O0, the literal 5 reappears. Tellingly, it also shows up in

std::__atomic_base<int>::operator int() const:
        push    rbp
        mov     rbp, rsp
        sub     rsp, 32
        ...
        mov     DWORD PTR [rbp-12], 5
        mov     eax, DWORD PTR [rbp-12]
        mov     esi, 65535
        mov     edi, eax
        call    std::operator&(std::memory_order, std::__memory_order_modifier)

so the literal 5 is eventually passed as an argument to that call, in %edi.

Since the argument is std::memory_order, we can look at the documentation and see

typedef enum memory_order {
    memory_order_relaxed,
    memory_order_consume,
    memory_order_acquire,
    memory_order_release,
    memory_order_acq_rel,
    memory_order_seq_cst
} memory_order;

which, literally implemented, will give memory_order_seq_cst = 5.

Note that memory_order_seq_cst is the default for fetch_add's ordering parameter, so you'd expect to see it passed as an argument.

Related