can someone help me convert this C code to MIPS assembly? I keep getting an infinte loop.
C code:
uint32_t reverse_sum(uint32_t *arr) {
uint32_t r;
if(*arr == -1) return 0;
r = reverse_sum(arr 1) (uint32_t)*arr;
*arr = r;
return(r);
}
This is what I tried, I see why I am getting an infinite loop, but I can't think of another approach to this without getting an infinite loop. (Assume $a0 holds the arr, and $v0 is the return register).
reverse_prefix_sum:
# PROLOGUE
subu $sp, $sp, 8 # expand stack by 8 bytes
sw $ra, 8($sp) # push $ra (ret addr, 4 bytes)
sw $fp, 4($sp) # push $fp (4 bytes)
addu $fp, $sp, 8 # set $fp to saved $ra
lw $t0, 0($a0) # t0 now stores first array element
bne $t0, -1, rec
li $v0, 0
j ret
rec:
subu $sp, $sp, 4 # expand stack by 1 spot
sw $t0, 4($sp) # store t0 (first element in array) on the stack
lw $a0, 4($a0) # load arr 1 element in a0
jal reverse_prefix_sum
lw $a0, 4($sp)
add $t1, $v0, $a0
sw $t1, 0($t0)
move $v0, $t1
ret:
# EPILOGUE
move $sp, $fp # restore $sp
lw $ra, ($fp) # restore saved $ra
lw $fp, -4($sp) # restore saved $fp
jr $ra # return to kernel
CodePudding user response:
That has this instruction:
lw $a0, 4($a0) # load arr 1 element in a0
to pass a pointer parameter to the recursive function
But the C code wants a pointer to the element, not an array element value. To pass arr 1 you merely need an add instruction, not a load.
In C, arr 1 is a pointer arithmetic expression, not a dereference.