【问题标题】:Can't Understand the Code Order When MIPS is translated to C无法理解 MIPS 翻译成 C 时的代码顺序
【发布时间】:2016-01-15 17:50:00
【问题描述】:

我正在尝试将 MIPS 代码转换为 C。我得到了问题的答案,但我猜到的答案与答案略有不同。所以我想问你。这是问题和建议的答案:

问题:

sll $t0, $s0, 2 

add $t0, $s6, $t0 

sll $t1, $s1, 2 

add $t1, $s7, $t1 

lw $s0, 0($t0) 

addi $t2, $t0, 4 

lw $t0, 0($t2) 

add $t0, $t0, $s0 

sw $t0, 0($t1)

答案:

B[g] = A[f + 1] + A[f];
f = A[f];

我认为答案正好相反,因为 f = A[f] 首先是从上到下计算的。所以这是我的答案:

 f = A[f];
 B[g] = A[f + 1] + A[f];

我知道正确答案在问题中,但为什么呢?我只是卡在那里。

从现在开始,谢谢,

【问题讨论】:

    标签: c mips translate


    【解决方案1】:

    您的分析是正确的,但您的解释是错误的:

    ;These 2 compute the address of A[f], using pointer arithmetic
    ; s0 is f and s6 is A
    sll  $t0, $s0, 2     ; t0 = s0 << 2
    add  $t0, $s6, $t0   ; t0 = s6 + t0  -- t0 is now the address of A[f]
    
    ;These 2 compute the address of B[g], using pointer arithmetic
    ; s1 is g and s7 is B
    sll  $t1, $s1, 2     ; t1 = s1 << 2
    add  $t1, $s7, $t1   ; t1 = s7 + t1  -- t1 is now the address of B[g]
    
    ; load A[f] into s0. s0 used to be f so we can read this as f = A[f]
    lw   $s0, 0($t0)     ; s0 = A[f]
    
    ; Compute address of A[f+1]
    addi $t2, $t0, 4     ; t2 = t0 + 4 -- t2 is now the address of A[f+1]
    
    ; Load A[f+1]
    lw   $t0, 0($t2)     ; t0 = Mem[t2] -- which is t0 = A[f+1]
    
    ; Add A[f] + A[f+1]
    add  $t0, $t0, $s0   ; t0 = t0 + ts -- which is A[f] + A[f+1]
    ; Store  A[f] + A[f+1] into B[g]
    sw  $t0, 0($t1)      ; Mem[t1] = t0 -- which is B[g] = A[f] + A[f+1]
    

    如果你想用高级语言表达同样的意思,那确实是:

    B[g] = A[f + 1] + A[f];
    f = A[f];
    

    你的顺序执行结果不正确,使用简单替换来检查这些在执行时的含义顺序

    f = A[f];
    B[g] = A[f + 1] + A[f];
    

    相同
    B[g] = A[A[f] + 1] + A[A[f]];
    f = A[f];
    

    这不是代码的作用。

    【讨论】:

    • 我可以看到我所取得的成果与您的示例不符。但是,我仍然感到困惑。我的意思是,代码首先执行操作 f = A[f] 然后 B[g] = A[f + 1] + A[f];不是吗?我的意思是,首先编写的代码不是必须在顶部吗?
    • 不,只要您的代码与生成的代码具有相同的顺序语义,编译器就可以做任何事情。如果您运行机器代码和正确答案,它们会产生相同的结果,但如果您运行您的,它会产生不同的结果 (B[g]) 将具有不同的值。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-21
    • 1970-01-01
    • 2018-10-22
    • 2023-03-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多