循序渐进,学习开发一个RISC-V 上的操作系统 练习5.8 参考答案

练习 5-8

  • 要求:阅读 code/asm/cc_leaf 和 code/asm/cc_nested 的例⼦代码,理解 RISC-V 的函数调⽤约定。在此基础上编写汇编程序实现以下功能,等价的 c 语⾔的⽰例代码如下,供参考:

ch5.8 test

Format:

要求:阅读 code/asm/cc_leaf 和 code/asm/cc_nested 的例⼦代码,理解 RISC-V 的函数调⽤约定。在此基

础上编写汇编程序实现以下功能,等价的 c 语⾔的⽰例代码如下,供参考:

/*
unsigned int square(unsigned int i)
{
return i * i;
}
unsigned int sum_squares(unsigned int i)
{
unsigned int sum = 0;
for (int j = 1; j <= i; j++) {
sum += square(j);
}
return sum;
}
void _start()
{
sum_squares(3);
}
*/

汇编源码

        .text                   # Define beginning of text section
        .global _start          # Define entry _start

_start:
    la sp, stack_start
    li a0, 3
    call sum_squares

stop:
        j stop                  # Infinite loop to stop execution
sum_squares:
    addi sp, sp, -16
    sw s0, 0(sp)
    sw s1, 4(sp)
    sw s2, 8(sp)
    sw ra, 12(sp)
    mv s0, a0
    li s1, 1
    li s2, 0
loop:
    BGT s1, s0, loop_end
    mv a0, s1
    jal square
    add s2,s2,a0
    addi s1,s1, 1
    j   loop
loop_end:
    mv a0, s2     # return sum to a0
    lw s0, 0(sp)
    lw s1, 4(sp)
    lw s2, 8(sp)
    lw ra, 12(sp)
    addi sp, sp, 16
    ret                 # return sum_square

square:
    addi sp, sp, -4
    sw s0, 0(sp)
    mv s0, a0
    mul a0, s0,s0
    lw s0, 0(sp)
    addi sp, sp, 4
    ret
    nop             #
stack_end:
    .rep 20
    .long 0
    .endr
stack_start:
        .end                    # End of file

https://gitee.com/unicornx/riscv-operating-system-mooc

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值