80 likes | 99 Views
Learn how to effectively use subroutines in MIPS architecture, including subroutine calls, returns, and stack operations such as PUSH and POP. Discover programming tricks for optimizing stack operations and explore example programs like Factorial and Sort.
E N D
MIPS Subroutines Subroutine Call – jal subname Saves RA in $31 and jumps to subroutine entry label subname Subroutine Return – jr $31 Loads PC with return address in $31 Note: If subroutine calls are nested $31 must be saved on the stack and restored by the user.
Example Subroutine Call & Return #calling program #subroutine A . subroutineA: . #call subroutineA . jal subroutineA . . #return . jr $31 . .
MIPS Stack Operations All stack (LIFO) operations must be hand coded by using other MIPS instructions $29 points to the top of the Stack memory ($29 is also called the Stack Pointer, SP) The Stack starts at a high memory address and grows to a lower memory address The Stack grows by adding –4 and shrinks by adding +4 to Stack Pointer Putting data on the stack is called a “PUSH” and removing data from the Stack is called a “POP”
MIPS Stack PUSH # $SP = $SP – 4 # adjust stack pointer with addi addi $sp,$sp,-4 # memory($sp) = register value # save data on stack with sw sw $reg,0($sp)
MIPS Stack POP # register value = memory($sp) # get data from stack with lw lw $reg,0($sp) # $SP = $SP + 4 # adjust stack pointer with addi addi $sp,$sp,4
Programming trick when multiple Stack Ops needed Use only one addi instruction! Example: addi $sp,$sp,-8 #PUSH sw $reg1,4($sp) sw $reg2,0($sp) . . . lw $reg1,4($sp) lw $reg2,0($sp) addi $sp,$sp,8 #POP Saves both execution time and memory!
Subroutine & Stack Ops Complex subroutines will need to PUSH several registers and the return address (if it has a jal) upon entry Next, the subroutine performs all of it’s operations. These will destroy or modify the registers that were saved on stack Prior to returning, it will POP saved registers and the return address (net $sp change must be 0! – thiswill cause major problems if it is not correct!!!!) Finally, it returns to the calling program with a jr $31
Example MIPS Subroutines with Stack Operations Factorial & Sort example programs found in Chapter 3 Factorial example program in Appendix A