What is the purpose of the RBP register in x86_64 assembler?

user6827707 picture user6827707 · Jan 28, 2017 · Viewed 70.7k times · Source

So I'm trying to learn a little bit of assembly, because I need it for Computer Architecture class. I wrote a few programs, like printing the Fibonacci sequence.

I recognized that whenever I write a function I use those 3 lines (as I learned from comparing assembly code generated from gcc to its C equivalent):

pushq   %rbp
movq    %rsp, %rbp
subq    $16, %rsp

I have 2 questions about it:

  1. First of all, why do I need to use %rbp? Isn't it simpler to use %rsp, as its contents are moved to %rbp on the 2nd line?
  2. Why do I have to subtract anything from %rsp? I mean it's not always 16, when I was printfing like 7 or 8 variables, then I would subtract 24 or 28.

I use Manjaro 64 bit on a Virtual Machine (4 GB RAM), Intel 64 bit processor

Answer

Govind Parmar picture Govind Parmar · Jan 28, 2017

rbp is the frame pointer on x86_64. In your generated code, it gets a snapshot of the stack pointer (rsp) so that when adjustments are made to rsp (i.e. reserving space for local variables or pushing values on to the stack), local variables and function parameters are still accessible from a constant offset from rbp.

A lot of compilers offer frame pointer omission as an optimization option; this will make the generated assembly code access variables relative to rsp instead and free up rbp as another general purpose register for use in functions.

In the case of GCC, which I'm guessing you're using from the AT&T assembler syntax, that switch is -fomit-frame-pointer. Try compiling your code with that switch and see what assembly code you get. You will probably notice that when accessing values relative to rsp instead of rbp, the offset from the pointer varies throughout the function.