繁体   English   中英

RISC-V汇编中的递归程序

[英]Recursive program in RISC-V assembly

我正在尝试在RISC-V中创建递归程序,但无法获得正确的结果。 看起来它自己最多只能调用两次,但是我尝试在纸上运行它,并且一切似乎正确:

addi x31, x0, 4
addi x30, x0, 2

addi x2, x0, 1600               //initialize the stack to 1600, x2= stackpointer
ecall x5, x0, 5                 //read the input to x5
jal x1, rec_func
ecall x0, x10, 2                //print the result
beq x0, x0, end

rec_func:
addi x2, x2, -16               //make room in stack
sd x1, 0(x2)                   //store pointer and result in stack
sd x10, 8(x2)
bge x5, x31, true             // if i > 3, then go to true branch
addi x10, x0, 1              // if i <= 3, then return 1
addi x2, x2, 16              // reset stack point
jalr x0, 0(x1)

true:
addi x5, x5, -2                // compute i-2
jal x1, rec_func                // call recursive func for i-2
ld x1, 0(x2)                    // load the return address
ld x10, 8(x2)                  // load result from last function call
addi x2, x2, 16                // reset stack point
mul x10, x10, x30               // multiply by 2
addi x10, x10, 1               // add 1
jalr x0, 0(x1)                 // return

end:

这是原始程序逻辑:

if i<= 3 return 1
else return 2 * rec_func(i-2) +1

我没有足够的声誉来添加评论,但是您是否尝试过使用调试器 (GDB?)而不是在纸上运行它? 那应该显示寄存器中实际的内容,以及为什么它不像您期望的那样分支。 我对这些说明(学习x86程序集)还不太熟悉,以至于无法确定源代码。

我现在开始工作了。 我所做的更改如下:

  • 在返回1的部分中,我没有加载return调用的堆栈指针
  • 我将x10的存储移到内存中,因为@Michael指出我正在返回它,不需要它。

最终代码如下所示:

addi x31, x0, 4
addi x30, x0, 2

addi x2, x0, 1600               // initialize the stack to 1600, x2= stackpointer
ecall x5, x0, 5                 // read the input to x5
jal x1, rec_func
ecall x0, x10, 2                // print the result
beq x0, x0, end

rec_func:
    addi x2, x2, -8                 // make room in stack
    sd x1, 0(x2)                    // store pointer and result in stack
    bge x5, x31, true               // if i > 3, then go to true branch
    ld x1, 0(x2)
    addi x10, x0, 1                 // if i <= 3, then return 1
    addi x2, x2, 8                  // reset stack point
    jalr x0, 0(x1)

true:
    addi x5, x5, -2                 // compute i-2
    jal x1, rec_func                // call recursive func for i-2
    ld x1, 0(x2)                    // load the return address
    addi x2, x2, 8                  // reset stack point
    mul x10, x10, x30               // multiply by 2
    addi x10, x10, 1                // add 1
    jalr x0, 0(x1)                  // return

end:

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM