Why decrement %rsp when everything can be done via registers?

Viewed 161

Below is my code:

C code

// this function might look weird, just for demo purpose
void func4(int x, int y, int z) {
    int t = z - y;
    int k = t >> 31;
    t = (t + k) >> 1;
    k = t + y;
    if(k <= x) {
        t = 0;
        if(k >= 1) {
            return;
        }else {
            y = k + 1;
            func4(x, y, z);
        }
    }else {
        z = k - 1;
        func4(x, y, z);
    }
}

asssembly code:

// only show relevant code
func4:
   subq $8, %rsp     //  decrement %rsp by 8, but why?
   movl %edx, %eax
   subl %esi, %eax
   ...               //  all operations on registers
   addq $8, %rsp
   ret

So since every operation can be done via registers, nothing is pushed to the stack, no pointer involved, so why the %rsp is decremented by 8 in the first place? Is it for alignment/offset?

1 Answers

func4 makes an outgoing function call (to itself no less) and thus must honor the ABI for function calls, that requires %rsp to be aligned mod 16 at the time of call (and thus misaligned by 8 on entry due to the return address being pushed).

Related