How a Called Function Responds

A called function (child function) must perform the following tasks:

  1. 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.
  2. 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-R10) 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.
  3. 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:
  4. size of all local variables + max = constant

    The max argument specifies the size of all parameters placed in the argument block for each call.

  5. The called function executes the code for the function.
  6. If the called function returns a value, it places the value in R12, R12 and R13, or R12 through R15, depending on the size of the return type.
  7. If the called function returns a structure, it copies the structure to the memory block that the first argument, R12, points to. If the caller does not use the return value, R12 is set to 0. This directs the called function not to copy the return structure.
  8. Structures and unions with size 32 bits or less are passed by value, either in registers or on the stack. Structures and unions larger than 32 bits are passed by reference.

    In this way, the caller can be smart about telling the called function where to return the structure. For example, in the statement s = func(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).

  9. The called function deallocates the frame and argument block by adding the constant computed in Step 3.
  10. The called function restores all registers saved in Step 2.
  11. The called function (func) returns.

The following example is typical of how a called function responds to a call:

func: ; Called function entry point PUSH.W r10 PUSH.W r9 ; Save SOE registers SUB.W #2,SP ; Allocate the frame : : ; Body of function : ADD.W #2,SP ; Deallocate the frame POP r9 ; Restore SOE registers POP r10 RET ; Return