简体   繁体   English

为什么std原子会向堆栈插入5

[英]Why does std atomic insert 5 to the stack

I wanted to see how std::atomic is translated to assembly. 我想看看std::atomic是如何转换为汇编的。 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: 由GCC汇编为:

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? 为什么GCC将“5”(第4行)推入堆栈?

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. 如果你采用godbolt链接Richard Critten非常有帮助地在评论中发布,并将GCC命令行更改为使用-O0 ,则文字5重新出现。 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 . 所以文字5最终作为参数传递给%edi

Since the argument is std::memory_order , we can look at the documentation and see 由于参数是std::memory_order ,我们可以查看文档并查看

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 . 字面上实现的将给出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. 请注意, memory_order_seq_cstfetch_add的排序参数的默认值,因此您希望将其视为参数传递。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM