Search code examples
assemblyarmstack-framestack-pointer

What's the Difference Between Stack Pointer and Frame Pointer in Assembly ARM


I was wondering if someone could please explain to me what's the difference between the Stack Pointer and the Frame Pointer in Assembly ARM


Solution

  • The way I understand it, the SP always points to the next available stack address(may need to be pre-decremented or pre-incremented first), which will be used for either pushing data or storing a return address.

    The SP can change while the called function is executing, if for example the function dynamically allocates a block of storage on the stack. Thus data in the stack frame such as passed parameters and local variables cannot reliably be referenced through offsets from the SP, since the SP is not guaranteed to have the same value throughout the execution of the function.

    The FP, OTOH, is guaranteed to have the same value throughout the execution of the function, so all local data can be accessed via hard-coded offsets from the FP. The FP is set to a fixed value within the stack frame, often just past the last passed argument.

    Here is an image I found that may be useful. You can see that offsets from FP will always be correct, but offsets from SP will depend on the size of the dynamic area and thus cannot be hard-coded, in functions that allocate runtime-variable amounts of space in their stack frame (like C99 VLA / alloca). https://www.cs.purdue.edu/homes/hosking/502/spim/node23.html. Functions that don't do that can optimize away a frame pointer (optimizing compilers will do that for you when making asm from a higher-level source language like C).