递归C++代码转RISC-V R64I汇编及参数传递错误排查
RISC-V汇编递归子集和函数参数传递错误排查与修正
我需要将一段计算子集和的递归C++代码转换为RISC-V R64I汇编代码,目标支持两个测试用例:
- 测试用例1:数组
{5,4,3},预期输出12 9 8 5 7 4 3 0 - 测试用例2:数组
{2,3},预期输出5 2 3 0
目前已完成字符串与数字打印的部分,但递归函数subsetSums的参数传递存在错误,无法得到正确输出,请求协助排查并修正。
参考C++代码
#include <iostream> using namespace std; //==============testcase1============== int arr[] = { 5, 4, 3 }; int n = 3; //output: 12 9 8 5 7 4 3 0 //===================================== //==============testcase2============== //int arr[] = {2, 3}; //int n = 2; //output: 5 2 3 0 //===================================== // Prints sums of all subsets of arr[l..r] void subsetSums(int arr[], int l, int r, int sum) { // Print current subset if (l > r) { cout << sum << " "; return; } // Subset including arr[l] subsetSums(arr, l + 1, r, sum + arr[l]); // Subset excluding arr[l] subsetSums(arr, l + 1, r, sum); } // Driver code int main() { cout << "output: "; subsetSums(arr, 0, n - 1,0); return 0; }
我编写的RISC-V汇编代码(含错误)
# Reference: https://www.geeksforgeeks.org/print-sums-subsets-given-set/ .data .align 4 # =========testcase1=========== arr: .word 5, 4, 3 n: .word 3 str: .string "output: " space: .string " " # output: 12 9 8 5 7 4 3 0 # ============================== # =========testcase2=========== #arr: .word 2, 3 #n: .word 2 #str: .string "output: " #space: .string " " # output: 5 2 3 0 # ============================== .text .global _start # Start your coding below, don't change anything upper except testing different testcase _start: li a7, 4 la a0, str ecall #load arr, 0, n, 0 la a0, arr la a1, 0 la a2, n la a3, 0 jal subsetSums j end # Jump to end of program subsetSums: mv t0, a0 mv t1, a1 mv t2, a3 # if l > r print sum blt a2, a1, sum add t3, a1, 0 slli t3, t3, 2 addi t3, a0, t3 lw t4, 0(t3) add a3, t2, t3 addi a1, t1, 1 jal subsetSums addi a1, t1, 1 add a3, t2, 0 jal subsetSums sum: mv t0, a3 # Print sum li a7, 1 addi a0, t0, 0 ecall #Print li a7, 4 la a0, space ecall lw ra, 0(sp) # Reload return address from stack addi sp, sp, 4 # Restore stack pointer jr x1 end:nop
错误代码段
subsetSums: mv t0, a0 mv t1, a1 mv t2, a3 # if l > r print sum blt a2, a1, sum #BUG add t3, a1, 0 slli t3, t3, 2 addi t3, a0, t3 lw t4, 0(t3) add a3, t2, t3 addi a1, t1, 1 jal subsetSums addi a1, t1, 1 add a3, t2, 0 jal subsetSums #BUG
我此前仅学习过基础的Hello World代码,从未接触过汇编语言,对当前问题无从下手。
内容的提问来源于stack exchange,提问作者Thitiwat Thongprasertsang
相关产品推荐
相关产品推荐

