# sums.asm MIPS file -- example of function from lecture # # 3 February 1999, Lin Jensen # # Function sum to find the sum of an array, # print out the sum of each of 2 arrays, by calling twice # # Subroutine printsum: prints the calculated value nicely. # # The main program: # printsum (sum (arr1, count1)) # printsum (sum (arr2, count2)) # #========================== TEXT Segment =============================== .globl __start .text #---------------- function sum (*array, count) -------------------------- # * means a pointer is expected (C syntax) # ---- input arguments: # $a0 pointer to an array of words (address) # $a1 number of elements in the array (value) # ---- returns: # $v0 sum of all the words indicated # # ---- temporary registers used: # $t0 point to each array element # $t1 count down # $t2 each element value sum: move $t0, $a0 # use to point to successive array elements move $t1, $a1 # countdown in $t1 = count li $v0, 0 # sum = 0 sumloop: sub $t1, 1 # countdown decremented (-1) bltz $t1, sumend # EXIT loop when countdown becomes negative lw $t2, ($t0) add $v0, $v0,$t2 # sum = sum + array(element) add $t0, 4 # point to next array element (4 bytes = 1 word) j sumloop sumend: #final sum now in $v0 jr $ra # return from function call ($ra ---> PC) # -------- subroutine printsum, prints ("Sum is ", $a0) printsum: move $t0, $a0 # save it for printing ($t0 is working copy of argument) la $a0, str # print "Sum is " li $v0, 4 syscall move $a0, $t0 # print sum, we saved it in $t0 li $v0, 1 # as integer syscall la $a0, eoln #end the line li $v0, 4 syscall jr $ra # return from function call ($ra ---> PC) #---------------- main program, execution starts here ------------------ __start: # sum (&arr1, count1) # &arr1 means the address is passed (C syntax) # set up function arguments la $a0, arr1 lw $a1, count1 jal sum #call function sum (PC+4 ---> $ra) # result now in $v0 (RETurn to here) move $a0, $v0 # ... becomes argument to jal printsum # print ("sum is ", $a0) # -------------------------- Call it again --------- # sum (&arr2, count2) # &arr1 means the address is passed (C syntax) # set up function arguments la $a0, arr2 lw $a1, count2 jal sum #call function sum (PC+4 ---> $ra) # result now in $v0 move $a0, $v0 # ... becomes argument to jal printsum # subroutine to print the result li $v0, 10 syscall # end program #------------------DATA SEGMENT ----------------------- .data str: .asciiz "Sum is " eoln: .asciiz "\n" arr1: .word 1,2,3 count1: .word 3 arr2: .word 111, 222, 54321, -99, 365, 32767,0,0,87654 count2: .word 9 # # end of program