2

For this simple C program,

int test(int a,int b)
{
    int k=89;
    return a+b;
}
int main()
{
    test(5,3);
}

gcc 10 produces the following assembly code (using https://godbolt.org/ and verified on my machine):

test:
        push    rbp
        mov     rbp, rsp
        mov     DWORD PTR [rbp-20], edi
        mov     DWORD PTR [rbp-24], esi
        mov     DWORD PTR [rbp-4], 89
        mov     edx, DWORD PTR [rbp-20]
        mov     eax, DWORD PTR [rbp-24]
        add     eax, edx
        pop     rbp
        ret
main:
        push    rbp
        mov     rbp, rsp
        mov     esi, 3
        mov     edi, 5
        call    test
        mov     eax, 0
        pop     rbp
        ret

As you can see, gcc is using stack area without decrementing stack pointer. Is this normal? Isn't gcc supposed to decrement esp before using stack area?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
Mah35h
  • 1,127
  • 1
  • 7
  • 18
  • It is changing the *base* pointer `rbp`. – user207421 May 10 '20 at 08:22
  • `esp` yes, `rsp` no. The 32-bit ABI doesn't have a red-zone. – Peter Cordes May 10 '20 at 09:59
  • 1
    @user207421: It's also changing RSP by using push/pop on RBP, but that's not what this question is asking about. It's accessing space below the current RSP, via addressing modes like `[rbp-24]` while RBP = RSP. (`-fomit-frame-pointer` is only enabled with optimization on, not at `-O0`, otherwise GCC would store `volatile` locals or other stuff it couldn't avoid spilling using addressing modes like `[rsp - 8]` and not waste instructions making / destroying a frame pointer.) – Peter Cordes May 10 '20 at 10:05

0 Answers0