MIPS中l.s指令出现Fetch address未对齐字边界错误求助
问题分析与解决方案
核心错误原因
触发“Fetch address not being aligned with word boundary”错误的直接原因是数组元素地址计算错误:MIPS中float类型占4字节,要求访问地址必须是4的倍数(字对齐),但你直接将索引值(如1、2)当作字节偏移量加到基地址上,导致最终地址不是4的倍数,违反了l.s指令的对齐要求。
具体问题与修正点
地址偏移计算错误
- 错误写法:
add $s0, $s0, $a1 - 修正逻辑:将索引转换为字节偏移(索引 × 4),可以用
sll指令(逻辑左移2位等价于乘4),比如sll $t2, $a1, 2,再用add $s0, $s0, $t2得到正确的元素地址。
- 错误写法:
分支指令语法错误
- 错误写法:
beq $t0, 1 skip2、beq $t0, 2 skip3 - 修正写法:
beq $t0, 1, skip2、beq $t0, 2, skip3(分支指令的操作数之间必须用逗号分隔)
- 错误写法:
条件判断逻辑失效
- 错误写法:三次重复赋值
$t1,覆盖了之前的判断结果 - 修正逻辑:直接用
beq指令判断$t0的值,跳转到对应分支设置a1和a2,避免重复赋值覆盖。
- 错误写法:三次重复赋值
结果存储逻辑错误
- 错误写法:
s.s $f15, result(每次都覆盖result第一个元素) - 修正写法:
s.s $f15, 0($s2)(使用初始化的$s2指针存储当前结果)
- 错误写法:
循环计数器未自增
- 缺失代码:循环结束前没有递增
$t0,导致无限循环 - 补充代码:在循环末尾添加
addi $t0, $t0, 1,并跳回loop标签。
- 缺失代码:循环结束前没有递增
修正后的完整代码
.data vector_A: .float 5.2, 7.1, 2.0 vector_B: .float 15.4, 3.5, 11.5 result: .float 0.0, 0.0, 0.0 .text li $t0, 0 #initialize i la $s2, result #equivalent to *s0=&result[0]; in C ################################################################################## #write code to load each element from array vector_B, scale by Co-factor= 0.8, # # and then store back at the corresponding original memory adresses of vector_B # ################################################################################## ########################################################################## loop: ################################################### la $s0, vector_A #load starting address of array vector_A into s0 # la $s1, vector_B #load starting address of array vector_B into s1 # ################################################### bge $t0, 3, exit_loop # 替换未定义的print标签,跳转至循环退出逻辑 #STEP 1: #implement if statements beq $t0, 0, set_jk_0 beq $t0, 1, set_jk_1 beq $t0, 2, set_jk_2 set_jk_0: li $a1, 1 li $a2, 2 j continue_cond set_jk_1: li $a1, 0 li $a2, 2 j continue_cond set_jk_2: li $a1, 0 li $a2, 1 j continue_cond continue_cond: ################################################################ #Similarly set the if, else conditions for the other two # #conditions of j, k as in the C code using different labels # ################################################################ #STEP 2: #load the two numbers from arrays vector_A and vector_B into coprocessors (i.e. floating point registers) sub $a3, $a1, $a2 #use this as k index # 修正地址计算:索引转字节偏移(左移2位=×4) sll $t2, $a1, 2 add $s0, $s0, $t2 l.s $f0, 0($s0) sll $t3, $a3, 2 add $s0, $s0, $t3 l.s $f1, 0($s0) #do previous 4 instructions again but for $s1 (array_B) sll $t4, $a1, 2 add $s1, $s1, $t4 l.s $f2, 0($s1) sll $t5, $a3, 2 add $s1, $s1, $t5 l.s $f3, 0($s1) #STEP 3: #perform the math mul.s $f10, $f0, $f3 mul.s $f11, $f1, $f2 sub.s $f15, $f10, $f11 #FINAL STEP: #store the results into the results array s.s $f15, 0($s2) # 用$s2指针存储当前结果 addi $s2, $s2, 4 #increment results register to the next index # 循环计数器自增,继续循环 addi $t0, $t0, 1 j loop exit_loop: # 程序退出指令 li $v0, 10 syscall
内容的提问来源于stack exchange,提问作者JimHalpert
相关产品推荐
相关产品推荐

