I'm trying to learn RISC-V and wrote a factorial function, but it's running into a simulator error, hinting at a possible infinite loop. I'm not really sure how to debug my code at the moment, and was wondering if people could drop hints on what I might be doing wrong.
Thank you!
.globl factorial
.data
n: .word 8
.text
main:
la t0, n #t0 corresponds to n
lw a0, 0(t0)
jal ra, factorial
addi a1, a0, 0
addi a0, x0, 1
ecall # Print Result
addi a1, x0, '\n'
addi a0, x0, 11
ecall # Print newline
addi a0, x0, 10
ecall # Exit
factorial:
addi sp sp -16
sw s0 0(sp) #s0 corresponds to i, initialised to n
sw s1 4(sp) #s1 corresponds to factorial that will be constantly updated; also initialised to 1
sw s2 8(sp) #s2 corresponds to n, or t0
sw s3 12(sp)
add s2 x0 t0
addi s1 x0 1
add s0 x0 t0
addi s3 x0 4 #this is what we use to decrement s0 (i) by 1 each time
loop:
beq s0 x0 exit
mul s1 s1 s0
sub s0 s0 s3
j loop
exit:
lw s0 0(sp)
lw s1 4(sp)
lw s2 8(sp)
lw s3 12(sp)
addi sp sp 16
ret