Course contentsShow
← Embedded Systems & Computer Architecture
Lesson 49 of 9361. Foundations of Digital Logic and Computer ArchitectureFree lesson

Handling Procedure Calls and Stack Frames

You will trace the hardware-software interaction required to manage return addresses and local variables during nested function call execution.

In this lesson, you will learn how the hardware and software coordinate to keep track of where a program was before it jumped into a new function, ensuring it can always find its way back.

The Problem of Nesting

When your program calls a function (like Function_A calling Function_B), the processor needs to remember where to return once Function_B is done. If we only had one "Return Address" register, calling a second function would overwrite the address needed to return to the main program, causing a crash. To solve this, we use the Stack, a portion of RAM managed as a last-in, first-out (LIFO) structure.

The Stack Frame

Every time a procedure is called, the system carves out a block of memory called a Stack Frame. This frame holds:

  1. The Return Address: Where the CPU should jump after the function finishes.
  2. Local Variables: Any temporary data that doesn't fit in your limited register file.
  3. Saved Registers: Data that was in the registers before the call, which the new function might overwrite.

The Hardware-Software Handshake

When a call instruction occurs, the hardware automatically updates the Stack Pointer (SP)—a special register holding the memory address of the "top" of the stack.

Consider this sequence:

  1. Call: The CPU pushes the current PC (Program Counter) value onto the stack and jumps to the new address.
  2. Setup: The procedure "pushes" register values onto the stack to save them for later.
  3. Execution: The procedure uses registers freely for calculations.
  4. Teardown: The procedure "pops" the saved values back into the registers and restores the original return address.
  5. Return: The CPU jumps back to the address retrieved from the stack.

By nesting these frames, the processor can handle infinitely deep function calls, provided there is enough RAM. Each frame acts as a "snapshot" of the state of the machine at the moment that specific function was invoked.

Key Takeaway: The stack allows the processor to manage nested function calls by storing the return address and local state in RAM, effectively giving each function its own private workspace that is created upon entry and destroyed upon exit.