MIPS Subroutines

Mark Smotherman. Last updated September 2002.

(under construction)

Introduction

32-bit RISC ... later extended to 64-bit programming model ...

Register conventions

        r0      ($zero)    - constant 0 (hardware)
        r1      ($at)      - reserved for assembler
        r2-r3   ($v0-$v1)  - expression evaluation and function return value
        r4-r7   ($a0-$a3)  - four arguments
        r8-r15  ($t0-$t7)  - eight temporaries (not preserved across calls)
        r16-r23 ($s0-$s7)  - eight saved temporaries (preserved across calls)
        r24-r25 ($t8-$t9)  - two temporaries (not preserved across calls)
        r26-r27 ($k0-$k1)  - reserved for OS kernel
        r28     ($gp)      - pointer to global area
        r29     ($sp)      - stack pointer
        r30     ($fp)      - frame pointer
        r31     ($ra)      - return address (hardware)
[from gcc - check others]

Subroutine instructions

        jal  displ     r31 <- return address;
                       pc <- target address
        jalr rs,rd     rd <- return address (rd defaults to r31);
                       pc <- contents of register rs
        jr   rs        pc <- contents of register rs

Parameter passing

... first four parameters in registers, other in memory stack ...

Calling program structure

           ...
           lw    $a0,parameter   ! first parameter placed in $a0
           jal   subr            ! save return address in r31
           ...

Subroutine structure (non-leaf)

        subr:
                               ! prolog:
           subu  $sp,$sp,32    !   adjust stack frame
           sw    $ra,20($sp)   !   save return address
           sw    $fp,16($sp)   !   save caller's fp
           addu  $fp,$sp,28    !   set up new fp

           sw    $a0,0($fp)    !   save first parameter in stack

           ... body of subroutine ...

                               ! epilog:
           lw    $ra,20($sp)   !   restore return address
           lw    $fp,16($sp)   !   restore caller's fp
           addu  $sp,$sp,32    !   restore caller's sp
           jr    $ra           ! return


[History of subroutines page] [Mark's homepage] [CPSC homepage] [Clemson Univ. homepage]

mark@cs.clemson.edu