# add5.s -- Add 5 numbers in a procedure. # This program illustrates the use of passing parameters through registers # and the system stack, and also using the system stack to "save" s # registers that will be used as local variables. .data output: .asciiz "The sum is " nl: .asciiz "\n" .text main: li $a0, 2 # initialize parameters to function li $a1, 9 li $a2, 6 li $a3, 1 li $s0, 3 sw $s0, 0($sp) # put 5th parameter on the stack addi $sp, $sp, -4 jal add5 # call procedure move $s1, $v0 # copy return value to $s1 addi $sp, $sp, 4 # reset the stack pointer to what it was # before we needed to call the function li $v0, 4 # introduce output la $a0, output syscall li $v0, 1 # print answer move $a0, $s1 # specify that we print the value in $s1 syscall li $v0, 4 # print newline la $a0, nl syscall li $v0, 10 # end of program syscall #---------------------------------------------------------------------- # add5 - procedure that adds five numbers -- 4 of the parameters are # passed in registers a0-a3, and the 5th is on the stack. We'll use # s0 to hold the sum, and we'll return the sum in v0. add5: sw $ra, 0($sp) # save return address sw $s0, -4($sp) # save space for local variable addi $sp, $sp, -8 move $t1, $a0 # copy parameters to local variables move $t2, $a1 move $t3, $a2 move $t4, $a3 lw $t5, 12($sp) # location of 5th parameter is 3rd number # from the top of the stack add $s0, $t1, $t2 # add them up add $s0, $s0, $t3 add $s0, $s0, $t4 add $s0, $s0, $t5 move $v0, $s0 # set the return value addi $sp, $sp, 8 # restore the saved registers lw $s0, -4($sp) # (This is the inverse of what we did lw $ra, 0($sp) # at the beginning) jr $ra # return