I am trying to have the function vbsme call another function called sad… is the following procedure correct about saving the registers and return address?? the caller is supposed to save register $t0-$t7, but where and how should I do that?
vbsme: li $v0, 0 # reset $v0
li $v1, 0 # reset $v1
li $t0, 1 # i(row) = 1
li $t1, 1 # j(col) = 1
lw $t2, 0($a0) # row size
lw $t3, 4($a0) # col size
mul $t4, $t2, $t3 # row * col
li $t5, 0 # element = 0
loop: bgeq $t5, $t4, exit # if element >= row * col then exit
addi $sp, $sp, -16 # create space on the stack pointer
sw $ra, -12($sp) # save return address
sw $s6, -8($sp) # save return address
sw $s7, -4($sp) # save return address
subi $s7, $t0, 1 # 1st parameter: i-1
subi $s6, $t1, 1 # 2nd parameter: j-1
jal sad # calculate the sum of absolute difference using the frame starting from row a0 and col a1
lw $ra, -12($sp) # restore return address
lw $s6, -8($sp)
lw $s7, -4($sp)
addi $sp, $sp, 16 # restore stack pointer
jr $ra
$sx registers are guaranteed to be unchanged accross function calls, so its the callee (sum function) the responsible of saving them, only if its going to change their value.
$tx registers, on the other hand, are not guaranteed to be unchanged over function calls, so its the responsability of the caller (vbsme) to save them.
You should save $sx in the callee stack.
So when you start coding the sum function, you should save space in the stack
If you want to save n registers, then save n*4.
Space in the stack is saved by subtracting on the $sp register, which points to the base of the stack. Before your function code, you should create the stack for that function, saving all caller-saved registers, return address and global pointer registers when neccesary
By the way, by convention, registers $a0, $a3 should keep the arguments to the function you are calling. Also, note that because you are using the $s0, $s7 registers, you have to do some extra work. Convention says that if you don’t use them, then you shouldn’t save them, so maybe you could use the $tx (temporary) registers instead.