2

In the book CSAPP, 3.7.5 Local Storage in Registers, there is a calling function:

long P(long x, long y)
{
     long u = Q(y);
     long v = Q(x);
     return u + v;
}

and the Generated assembly code for the calling function is:

P:
  pushq    %rbp
  pushq    %rbx
  subq     $8, %rsp       Align stack frame
  movq     %rdi, %rbp
  movq     %rsi, %rdi
  call     Q
  movq     %rax, %rbx
  movq     %rbp, %rdi
  call     Q
  addq     %rbx, %rax
  addq     $8, %rsp
  popq     %rbx
  popq     %rbp
  ret

I can't understand Line 3 subq $8, %rsp. The book says it is used to align stack frame. Why the machine align stack frame here?

Michael Petch
  • 46,082
  • 8
  • 107
  • 198
Manhooo
  • 115
  • 2
  • 6
  • 3
    The 64-bit System V ABI requires 16-byte alignment just before you call a function. After the _CALL_ instruction you are in your function but the return address has been pushed on the stack. The stack is now misaligned by 8 bytes (return address is 8 bytes). Pushing _RBP_ subtract 8 more bytes so the stack is aligned again. pushing _RBX_ misaligns it by 8 again. The `subq $8, %rsp` happens to subtract another 8 realigning the stack once again. Now when you do `call Q` the stack will be aligned on a 16-byte boundary (stack pointer will be evenly divisible by 16) – Michael Petch Mar 25 '18 at 17:44
  • SIMD Instructions, which can perform parallel operations on multiple words in memory require those words to be a block starting at an address that is a multiple of 16 bytes. There is a good explanation of this [here](https://stackoverflow.com/questions/4175281/what-does-it-mean-to-align-the-stack) – Icemanind Mar 25 '18 at 18:37

0 Answers0