UMBC CMSC 211 |
A stack is a data structure like a queue, but data can only be added or removed at one end, so it is Last-In, First-Out (LIFO) There are special instructions built into the CPU to work with the stack. The sp register points to the newest 16-bit value that is on the stack, which is the next item to be removed.
The instruction is push and pop. Either a memory location (word only) or a register can be specified. If we have set up the code segment as:
X | DW | 1111 |
Y | DW | 2222 |
Z | DW | ? |
? | |
? | |
? |
push | X |
1111 | <- SP |
? | |
? |
push | Y |
1111 | |
2222 | <- SP |
? |
pop | Z |
1111 | <- SP |
2222 | |
? |
The hardware stack is implemented as a normal block of memory of the size you specified in the .STACK pseudo-op.
If you do push X followed by pop X, nothing is changed.
Saving and restoring registers is particularly important when using subprograms. You have the responsibility to save and restore important data in the registers before you call a subprogram and then you are responsible for restoring those registers afterwards.
Subprograms should save and restore any registers that they use, unless they are returning values in certain registers! This means you have to write the instructions to do it!