Unaligned Stack Pointer

Hi all,

my question is maybe not directly related with LLVM but general with compilers.

The common approach is that compilers often don’t align stack pointer for leaf functions if the function utilizes stack just for keeping variables of small sizes.

I’m wondering what is the benefit of such behavior.

Is saving a few bytes of the stack just once worth of such approach?

Or maybe something else stands behind it? Is there any other potential benefit of unaligned Stack Pointer in Leaf Functions?

Thanks,

Przemek

Is this really “common”?

I would expect many architectures to require stack pointer alignment at all times, as a signal/interrupt/fault can happen at any time.

SPARC is a good example. If an interrupt occurs, the OS must flush all register windows out to the user stack. This requires that the stack pointer be aligned. Since you have no control over when an interrupt can occur. you must maintain alignment at all times.

Exactly, but for some architectures SP is not aligned for such case.
My questions is what for, apart of saving few bytes on stack just during execution od leaf function?

Przemek

czw., 17 wrz 2020, 17:17 użytkownik David Jones <david.jones@metrics.ca> napisał:

The answer may be architecture-specific. Typically such things are done to avoid some unnecessary cost, whether it is stack space, or extra instructions to ensure proper alignment. For example, on architectures/ABIs that have red zones on the stack, leaf functions may not bother allocating any space at all (i.e. leaving the stack pointer unmodified) if the local data fits in the red zone.

The kernel will realign the stack pointer as appropiate for signal
handlers, so that argument doesn't really work. Interrupt and exception
handlers normally have their own stacks, so the problem doesn't apply to
them.

Joerg

Thank you for all responses!

Read zone is in fact a very interesting solution.

But on architectures which don’t support red zones and in case leaf function eventually modifies stack pointer, why not modify it always according to alignment?

If for example SP is aligned to 8 bytes and the leaf function wants to store on stack just one ‘char’ (1-byte), what is the difference between decreasing SP by 1 instead of 8?

In such case we know that the stack will not grow-down any more (except interrupt/exception handlers), so in fact we are saving just 7-bytes, which eventually will not be used.

Is it really worth not aligning the stack pointer just for such case? … additionally having to manage with unaligned stack pointer in interrupts handlers…

Or maybe there are other scenarios where unaligned pointers might be used and brings benefits?

Przemek