Course: Computer Architectures
Source lesson: ARM Subroutines and Procedure Calls
Defining and calling a subroutine
A subroutine has a label and a return instruction:
MyAdd:
ADD r0, r0, r1
BX LRThe caller uses BL:
BL MyAddBL does two jobs:
- It places the address of the next instruction in
LR(r14). - It jumps to
MyAddby updatingPC(r15).
BX LR branches to the saved return address. BLX Rn performs the same kind of call when the destination is held in a register.
Nested calls
Suppose main calls sub1, and sub1 calls sub2:
main --BL--> sub1 --BL--> sub2The first call puts the address back to main in LR. The second call overwrites LR with the address back to sub1. If sub1 did not save its original LR, it loses its way back to main.
A safe non-leaf subroutine saves LR and restores it into PC:
sub1:
PUSH {LR}
BL sub2
POP {PC}If other registers are changed, preserve them too:
sub1:
PUSH {r4, r5, LR}
; use r4 and r5; call other routines if needed
POP {r4, r5, PC}Common confusion
LR is a register holding a return address; it is not the return itself. PC is the register that controls which instruction executes next. POP {PC} returns because it loads the saved address into PC.
Retrieval questions
Q: What is lost if sub1 executes BL sub2 without saving LR?
A: The return address to sub1’s caller, such as main, because the nested call overwrites LR.
Q: Why is POP {r4, PC} useful?
A: It restores r4 and loads the saved return address into PC in one stack transfer.