NASM - The Netwide Assembler

NASM Forum => Programming with NASM => Topic started by: Mixolydian on June 03, 2014, 07:09:28 PM

Title: Local variables - stack alignment
Post by: Mixolydian on June 03, 2014, 07:09:28 PM
Hi, I'm just wondering about local variables.

I've written the following code:

Code: [Select]
displayMessage:
push ebp
mov ebp, esp
and esp, -16
sub esp, 4

mov dword [esp], 3

push dword dword [esp]
push message
call _printf

add esp, 4
mov esp, ebp
pop ebp
ret

And it works. But when I've looked at the output from C compilers, it seems to align the stack to 16 bytes.

So the above would be:

Code: [Select]
displayMessage:
push ebp
mov ebp, esp
and esp, -16
sub esp, 16

mov dword [esp+12], 3

push dword dword [esp+12]
push message
call _printf

add esp, 16
mov esp, ebp
pop ebp
ret

Should I be aligning the stack to 16 bytes like this or is it just something C does? Will my code run faster when my stack pointer is aligned to 16 bytes?
Title: Re: Local variables - stack alignment
Post by: encryptor256 on June 03, 2014, 07:44:30 PM
Hmm... Interesting.

Maybe your cpu is 64 bit.

On 64 bit you need to align stack on 16 byte boundaries, who knows, maybe then there is need for 32 bit too.

Yes, it might run faster if stack is aligned on 16 byte boundaries.

Well, you have to investigate this alignment issue on 32 bit further.

I suggest using like C compiler does.
Title: Re: Local variables - stack alignment
Post by: Mixolydian on June 03, 2014, 07:49:57 PM
I think I will do what C does and align the stack pointer to 16 byte boundaries; I was just looking for a definitive reason as to why C does this.
Title: Re: Local variables - stack alignment
Post by: Frank Kotler on June 03, 2014, 08:02:47 PM
I "think" C does this "in case" you need a local variable aligned for SSE. Won't hurt to have "better" alignment than we need, not enough is a problem. We aren't likely to run out of stack space.

Best,
Frank