C到MIPS翻译

5
尝试将此C代码转换为MIPS并在SPIM中运行。
int A[100], B[100];
for(i=1; i<100; 1++){
A[i] = A[i-1] + B[i];
}

到目前为止,这就是我所拥有的。
    # comments are delimted by has marks

.data
A:   .word  0:100        # array of 12 integers
B:   .word  0:100        # array of 12 integers


.text
main:
    li $v0, 1       # load the value "1" into register $v0
    li $t0, 1       # load the value "1" into register $t0
    li $t1, 100     # load the value "100" into register $t1
    blt $t0, $t1, loop # branches to Loop if $t0 < 100
    la $t9, B
    la $t8, A

loop:
    sll $t0, $t0, 2
    add $t2, $t9, $t0 
    lw $s4, 0($t9)
    add $t3, $t0, -1
    add $t4, $t8, $t3
    lw $s5, 0($t4)
    add $t5, $t2, $s5
    add $t6, $s0, $t0
    sw $t7, 0($t5)
    addi $t0, $t0, 1
    li $v0, 1 # system call for print_int
    move $a0, $t0 # the sum to print
    syscall # print the sum

在SPIM中运行时,我遇到了以下错误:

PC=0x00400040处发生异常
  读取数据/堆栈时地址无效: 0x00000004
PC=0x0040004c处发生异常
  指令/数据获取时地址未对齐: 0x00000003
PC=0x00400058处发生异常
  读取数据/堆栈时地址无效: 0x00000000
试图在0x0040006c处执行非指令内容

希望能提供一些指导。谢谢。


2
为什么不先编译,然后优化结果呢? - Potatoswatter
什么是MIPS?在维基百科上找不到。 - Alon Gubkin
阿隆:http://zh.wikipedia.org/wiki/MIPS%E6%9E%B6%E6%A7%8B - Gabe
哎呀,我们是不是已经老了,现在我们中间有些程序员从没听说过MIPS? :) - Jim Buck
2个回答

2
你在初始化指向 AB 的指针之前就分支到了 loop (blt $t0, $t1, loop)。你需要将 blt $t0, $t1, loop 移动到代码的末尾而不是开头。
我很抱歉必须这样做,但存在太多问题无法列举。请尝试以下操作:
.data 
A:   .word  0:100        # array of 100 integers 
B:   .word  0:100        # array of 100 integers 


.text 
main: 
    li $t0, 4       # load the value "1" into register $t0 
    li $t1, 400     # load the value "100" into register $t1 
    la $t9, B 
    la $t8, A 

loop: 
    add $t2, $t9, $t0  # $t2 = B + i
    lw $s4, 0($t9)     # $s4 = B[i]
    add $t3, $t0, -4   # $t3 = i - 1
    add $t4, $t8, $t3  # $t4 = A + i - 1
    lw $s5, 0($t4)     # $s5 = A[i - 1]
    add $t5, $t8, $t0  # $t5 = A + i
    add $t6, $s4, $s5  # $t6 = B[i] + A[i - 1]
    sw $t6, 0($t5)     # A[i] = $t6
    addi $t0, $t0, 4   # i++

    li $v0, 1 # system call for print_int 
    move $a0, $t6 # the sum to print 
    syscall # print the sum

    blt $t0, $t1, loop # branches to Loop if $t0 < 100 

1

首先,s1和s2应该被初始化为你的数组基于栈(我假设)的地址。


我已经正确地初始化了数组(我想)。我仍然遇到相同的错误,看起来是执行load word命令时出了问题。 - user282964

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接