6.4.2 How a Called Function Responds
A called function (child function) must perform the following tasks:
- If the function is declared with an ellipsis, it can be called with a variable number of arguments. The called function pushes these arguments on the stack if they meet both of these criteria:
- The argument includes or follows the last explicitly declared argument.
- The argument is passed in a register.
- The called function pushes register values of all the registers that are modified by the function and that must be preserved upon exit of the function onto the stack. Normally, these registers are the save-on-entry registers (R4-R11 and R14 (alternate names are V1 to V8 and LR)) and the link register (R14) if the function contains calls. If the function is an interrupt, additional registers may need to be preserved. For more information, see Section 6.7.
- The called function allocates memory for the local variables and argument block by subtracting a constant from the SP. This constant is computed with the following formula:
size of all local variables + max = constant
The max argument specifies the size of all parameters placed in the argument block for each call.
- The called function executes the code for the function.
- If the called function returns a value, it places the value in R0 (or R0 and R1 values).
- If the called function returns a structure, it copies the structure to the memory block that the first argument, R0, points to. If the caller does not use the return value, R0 is set to 0. This directs the called function not to copy the return structure.
In this way, the caller can be smart about telling the called function where to return the structure. For example, in the statement s = f(x), where s is a structure and f is a function that returns a structure, the caller can simply pass the address of s as the first argument and call f. The function f then copies the return structure directly into s, performing the assignment automatically.
You must be careful to properly declare functions that return structures, both at the point where they are called (so the caller properly sets up the first argument) and at the point where they are declared (so the function knows to copy the result).
- The called function deallocates the frame and argument block by adding the constant computed in Step 3.
- The called function restores all registers that were saved in Step 2.
- The called function ( _f) loads the program counter (PC) with the return address.
The following example is typical of how a called function responds to a call:
; called function entry point
STMFD SP!, {V1, V2, V3, LR} ; save V1, V2, V3, and LR
SUB SP, SP, #16 ; allocate frame
... ; body of the function
ADD SP, SP, #16 ; deallocate frame
LDMFD SP!, {V1, V2, V3, PC} ; restore V1, V2, V3, and store LR
; in the PC, causing a return