Q14Microprocessor and Microcontroller
Question
What is Subroutine? Explain the use of stack in CALL and RETURN Instructions in detail.
Answer
A deep architectural explanation of Subroutines, detailing how the CALL instruction mathematically pushes the return address onto the Stack, and how RETURN sequentially pops it back into the Program Counter.
In assembly language programming, a Subroutine (analogous to a "function" or "method" in higher-level languages) is a highly specialized, isolated block of code engineered to perform a specific, frequently repeated task (e.g., generating a time delay or multiplying two numbers). Instead of rewriting this massive block of code everywhere it is needed, the programmer simply writes it once in memory, and the main program violently jumps to it when required. This requires flawless management of the Program Counter (PC) using the Stack.
The Anatomy of a CALL Instruction
When the microprocessor encounters a CALL 2050H instruction, a highly complex sequence of internal hardware operations is triggered:
- 1. Address Preservation: The microprocessor is about to jump to
2050H. However, it absolutely MUST remember where it came from so it can return later. The memory address of the next instruction in the main program is currently residing in the 16-bit Program Counter (PC). - 2. The Stack Push: The microprocessor forces the Stack Pointer (SP) to decrement by 1. It then takes the upper 8 bits (high byte) of the PC and permanently writes them into that Stack memory location. It decrements the SP again by 1. It then writes the lower 8 bits (low byte) of the PC into that new Stack location. The return address is now safely preserved in LIFO memory.
- 3. The Jump: Finally, the microprocessor overwrites the Program Counter with the target address provided in the instruction (
2050H). On the next clock cycle, execution radically shifts to the subroutine.
The Anatomy of a RETURN Instruction
The absolute last instruction of any valid subroutine must be RET (Return). When executed:
- 1. The Stack Pop: The microprocessor goes to the exact memory location currently pointed to by the Stack Pointer (SP). It reads the 8-bit value (the preserved low byte) and mathematically inserts it into the lower half of the Program Counter. It increments the SP by 1.
- 2. The Second Pop: It reads the next 8-bit value (the preserved high byte) from the Stack and inserts it into the upper half of the Program Counter. It increments the SP again.
- 3. Resuming Execution: The Program Counter now perfectly contains the original return address. On the next clock cycle, execution flawlessly resumes in the main program exactly where it left off, as if the subroutine jump had never occurred.