Why does gcc push %rbx at the beginning of main?

前端 未结 2 411
萌比男神i
萌比男神i 2021-02-03 14:20

The latest version of gcc is producing assembly that doesn\'t make sense to me. I compiled the code using no optimization; but, some parts of this code don\'t make sense, even

相关标签:
2条回答
  • 2021-02-03 14:50
    GCC dictates how the stack is used. Contract between caller and callee on x86:
    
        * after call instruction:
              o %eip points at first instruction of function
              o %esp+4 points at first argument
              o %esp points at return address 
        * after ret instruction:
              o %eip contains return address
              o %esp points at arguments pushed by caller
              o called function may have trashed arguments
              o %eax contains return value (or trash if function is void)
              o %ecx, %edx may be trashed
              o %ebp, %ebx, %esi, %edi must contain contents from time of call 
        * Terminology:
              o %eax, %ecx, %edx are "caller save" registers
              o %ebp, %ebx, %esi, %edi are "callee save" registers
    

    The main function is like any other function in this context. gcc decided to use ebx for intermediate calculations, so it preserves its value.

    0 讨论(0)
  • 2021-02-03 14:54

    By default gcc compiles with optimization disabled, which is the case here, apparently.

    You need to enable it with one of the optimization switches (e.g. -O2 or -O3).

    Then you will not see redundant and seemingly meaningless things.

    As for rbx, it has to be preserved because that's what the calling conventions require. Your function modifies it (movl -32(%rbp), %ebx), so it has to be saved and restored explicitly.

    0 讨论(0)
提交回复
热议问题