如何解决如何在 asembly riscv 中使用 short int 对堆栈的元素求和
已经有一个使用数组的代码,但我想使用短整数。 我如何使用短整数?
sum:
lw x1,0x0(x10)
lw x2,0x4(x10)
add x3,x0,x0
loop:
lw x4,0x0(x1)
add x3,x3,x4
addi x1,x1,4
addi x2,x2,-1
bnex x2,loop
sw x3,0x8(x10)
解决方法
Risc-V 没有任何类型。因此,编译器可以使用短整数为您的示例编译相同的代码。
但由于短整数在大多数情况下是 16 位长,也称为半字,您可以使用 lh(加载半字)和 sh(存储半字)而不是 lw 和 sw 来重写代码。
此外,您还需要注意使用的寄存器,否则代码将无法正确运行。还有你正在加载的东西。在您的示例中,您使用 x10(a0 - 参数寄存器 1)作为指向数组指针的指针以及指向大小的指针。这通常不会完成,也不可能用 C 来描述(也许用结构体)。
回到寄存器。您正在使用 x1(ra - 返回地址)、x2(sp - 堆栈指针)、x3(gp - 全局指针)和 x4(tp - 线程指针)。所有这些都是您不想接触的基本通用操作的寄存器。通常用于此类操作的寄存器是 x5-x7 和 x28-x31 临时寄存器。但出于可读性目的,最好使用 t0-t6 代替。
这是短整数的正确版本:
sum: # C-style: short int sum(short int* array,short int size)
# a0 holds the array pointer and a1 holds the size
addi t0,zero,0 # t0 will hold the result of the summation
loop:
lh t1,0(a0) # load the first element of the array
add t0,t0,t1 # sum the array element to t0
addi a1,a1,-1 # decrement the size to not overflow the array
addi a0,a0,2 # increment the array address to point to the next array element
# its 2 because of short ints (16 bits -> 2 bytes)
bnez a1,loop # check if the summation is done
add a0,zero # move the result to a0 (also return value register)
ret # return using the ra register (so don't overwrite the ra register)
我希望这会有所帮助。
如需进一步帮助,我强烈建议您阅读“Risc-V 用户规范”。它还描述了寄存器的使用以及如何很好地映射函数。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。