.text . . Call: b Proc # call procedure Return: . # return address . done Proc: # procedure code begins here . . b Return # return to calling program
In the preceding example, the procedure always returns to the same location. The code is modular, but not reuseable. A general procedure call mechanism must allow a procedure to be called from various locations in a program and to return to the instruction following each procedure call.
To reuse a procedure, the return address must be saved before the procedure is called. The steps in the transfer of control to execute a procedure are:
In MAL, register $31 (also called $ra) is used to save the return address for a procedure call. The jr (jump register) instruction is used to return from a procedure. It moves the contents of the specified register to the PC, causing an unconditional branch to the address contained in the register. For example:
.text . . la $ra, Return # save return address Call: b Proc # call procedure Return: . # return address . done Proc: # procedure code begins here . . jr $ra # return to calling program
The MAL jal (jump and link) instruction simplifies a procedure call by saving the return address and branching to the procedure with a single instruction. The jal instruction always saves the return address in $ra.
.text . . Call: jal Proc # call procedure . . done Proc: # procedure code begins here . . jr $ra # return to calling program
Using the jal and jr instructions together allows implementation of the procedure call mechanism without creating additional labels for return addresses.
To fit the address operand of the jal instruction into 32 bits, the address is limited to 28 bits and combined with the 4 most significant bits of the PC to form the jump destination address.
When a 28 bit address is insufficient, the jalr (jump and link register) instruction allows both the jump address and the return address to be stored in arbitrary registers.
The MAL jump instructions for calling procedures are shown below:
Notes:
When a procedure calls another procedure, the linkage techniques described in the Nested Procedures section must be employed.