Stack register

From Infogalactic: the planetary knowledge core
Jump to: navigation, search

A stack register is a computer central processor register whose purpose is to keep track of a call stack. On an accumulator-based architecture machine, this may be a dedicated register such as SP on an Intel x86 machine. On a general register machine, it may be a register which is reserved by convention, such as on the PDP-11 or RISC machines. Some designs such as the Data General Eclipse had no dedicated register, but used a reserved hardware memory address for this function.

Machines before the late 1960s—such as the PDP-8 and HP 2100—did not have compilers which supported recursion. Their subroutine instructions typically would save the current location in the jump address, and then set the program counter to the next address.[1] While this is simpler than maintaining a stack, since there is only one return location per subroutine code section, there cannot be recursion without considerable effort on the part of the programmer.

A stack machine has 2 or more stack registers — one of them keeps track of a call stack, the other(s) keep track of other stack(s).

Stack registers in x86

In 8086, the main stack register is called stack pointer - SP. The stack segment register (SS) is usually used to store information about the memory segment that stores the call stack of currently executed program. SP points to current stack top. By default, the stack grows up down. To push a value to the stack, the PUSH instruction is used. To pop a value from the stack, The POP instruction is used.

Example: Assuming that SS = 0x10000 and SP = 0xF820. This means that current stack top is the physical address 0x1F820. The next two machine instructions of the program are:

PUSH AX
PUSH BX
  • These first instruction shall push the value stored in AX (16-bit register) to the stack. This is done by subtracting a value of 2 (2 bytes) from SP.
  • The new value of SP becomes 0xF81E. The CPU then copies the value of AX at the memory word whose physical address is 0x1F81E.
  • When "PUSH BX" is executed, SP is set to 0xF81C and BX is copied to 0x1F81C.[2]

This illustrates how PUSH works. Usually, the running program pushes registers to the stack to make use of the registers for other purposes, like to call a routine that may change the current values of registers. To restore the values stored at the stack, the program shall contain machine instructions like this:

POP BX
POP AX
  • POP BX copies the word at 0x1F81C (which is the old value of BX) to BX, then increases SP by 2. SP now is 0xF81E.
  • POP AX copies the word at 0x1F81E to AX, then sets SP to 0xF820.

NOTE: The program above pops BX first, that's because it was pushed last.

NOTE: In 8086, PUSH & POP instructions can only work with 16-bit elements.

References

  1. Lua error in package.lua at line 80: module 'strict' not found.
  2. Lua error in package.lua at line 80: module 'strict' not found.