Tricks of the stack

The stack is very flexible in what can be pushed and popped.  There are a few tricks that are very useful when using the stack, you can push a 32-bit value and then pop two 16-bit values.

' Push a 32 bit value onto the stack

! PUSH EDX

 

' Now pop two 16 bit values off the stack

! POP AX

! POP CX

Even though the pushed data size is different to the popped data size, four bytes have been pushed onto the stack and four bytes have been popped back off the stack so the stack is balanced.

The stack can be used for many different things, you can push a register and pop it later when you need it so that you do not need to allocate a memory variable to put it in.  You can use the stack to move a piece of data between memory operands and registers.

! PUSH ECX

! POP  memVar

…or:

! PUSH memVar

! POP  EDX

…or between two memory variables:

! PUSH memVar1

! POP  memVar2

…instead of using a register:

! MOV EDX, memvar1

! MOV memvar2, EDX

A collection of small tricks of this type free up the number of registers that you can use in your procedures, provided the stack is managed carefully.

Before the end of your routine, you should make sure that all the registers you have pushed onto the stack have also been popped from the stack.  It is easy to make a mistake in this area, especially if the routine conditionally PUSHes and POPs any registers.

 

See Also

The Inline Assembler

The stack

Balancing the stack

Stack Overhead Reduction