Determining Return Location
The Link Register (LR) can be used to hold the address of the instruction to return to once the function terminates.
ADR LR, return_location
B start_location
return_location STR R0, return_value
; ...
start_location ; ...
MOV PC, LRBranch and Link Instruction
The Branch and Link instruction (BL) can be used to automate some of this process:
BL start_location
STR R0, return_value
start_location ;...
; ...
MOV PC, LRAs such, BL start_location is roughly equivalent to:
ADR LR, [PC, #16]
B start_locationThe Stack
There are a lot of problems that cannot be solved using registers only to store values. For example:
- More function parameters than available registers.
- Greater recursion depth than number of available registers.
- Unknown recursion depth.
- Overwriting of registers by called functions.
These can all be solved using the stack. The Stack Pointer (SP) is R13 (Registers). On most computers, the stack pointer is initially a large address, which is decreased as the stack grows.
The stack pointer contains the address of the top word on the stack.
Simple push and pop operations could be implemented as such:
STR R0, [SP, #-4]! ; push
LDR R0, [SP], #4 ; popPush and Pop Operations
The assembler provides two pseudo-instructions for stack manipulation, PUSH and POP:
Argument Format - {Ra, Rb, Rx-Ry}
- Multiple registers can be specified (
{Ra, Rb}). - Ranges of registers can be specified (
{Rx-Ry}). - Regardless of the order specified in the instruction, the registers will be pushed/popped in increasing order (ie. starting with the lowest numbered register).