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, t0, 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 用户规范”。它还描述了寄存器的使用以及如何很好地映射函数。