assembly - MIPS bne beq 计算机组织与设计

标签 assembly branch conditional mips

所以,我会引用我的教科书(计算机组织与设计),然后我会问我的问题:

Compiling if-then-else into Conditional branches

In the following code segment, f, g, j, i and j are variables. If the five variables f through j correspond to the five registers $s0 through $s4, what is the compiled MIPS code for this C if statement?

if (i == j) f = g + h; else f = g - h;

Figure 2.9 is a flowchart of what the MIPS code should do. The first expression compares for equality, so it would seem that we would want the branch if registers are equal instruction (beq). In general, the code will be more efficient if we test for the opposite condition to branch over the code that performs the subsequent then part of the if (the label Else is defined below) and so we use the branch if registers are not equal instruction (bne):

bne $s3, $s4, Else # go to Else if i ≠ j


我已经搜索了一段时间,但我找不到为什么 bne 会比 beq 更有效。
(不过,我确实发现有时建议使用 bne,因为它使代码更容易理解,因为当条件成立时要执行的语句就在 bne 语句的正下方。)
因此,如果它在一般情况下不会更有效,它在这个特定练习中仍然可能更有效。我已经考虑过这一点,我认为跳转指令会花费时间,因此我们希望尽量减少所需的跳转次数。这意味着,当我们期望条件成立时,我们应该使用 bne,而当我们期望条件失败时,我们应该使用 beq。
现在,如果我们测试 $s3 是否等于 $s4,当我们没有关于这些寄存器内容的任何信息时,假设它们可能相等是不合理的;相反,它们更有可能不相等,这将导致使用 beq 而不是 bne。
所以,总结一下:教科书说bne比beq更有效,无论是一般情况还是只是在这个例子中都不清楚,但在任何一种情况下我都不明白为什么。

最佳答案

效率不是直接比较 bne 和 beq 的机器代码。文本描述了通过编码来优化整体性能以缩短最常见的代码路径。

如果您假设这些值更有可能不相等,那么在使用 bne 时只需要处理一条指令,如果您使用 beq,则必须在失败时执行额外的跳转。

最短的路径是通过比较,失败而不是跳跃。

来自 http://www.cs.gmu.edu/~setia/cs365-S02/class3.pdf :

分支罕见案例

18 美元,19 美元,L1

  • 其他处理
  • jmp

  • 取而代之

    bne $18, $19, L2
  • 成功处理
  • 结束

  • L2:

    快速处理常见案例 -
    大多数分支的一条指令


    重新阅读你的问题,我认为关键是这个假设:

    "Now if we test whether $s3 equals $s4, when we have no information whatsoever about the content of those registers, it's not reasonable to assume that they're likely to be equal; on the contrary, it's more likely that they're not equal, which should result in using beq instead of bne."



    这似乎是困惑,我们需要找到一些证据或理由来确定哪种可能性更有可能,记录相等或不相等。

    在这种情况下,我们正在检查 if-then-else。我断言我们希望 if 测试通过,这就是 twalberg 所描述的心理。寄存器不太可能包含随机值,因为它们包含程序员期望的数据 - 先前操作的结果。

    关于assembly - MIPS bne beq 计算机组织与设计,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14104183/

    相关文章:

    R,有条件地删除重复的行

    assembly - 分支预测如何与指令指针交互

    windows - PE文件操作码

    java - GitHub 在不同的分支上工作,但在同一个类上。我们如何 merge 这个?

    git - git : Branch, fork 中相同代码的两个变体,还是创建单独的存储库?

    python - 不明白这个SyntaxError : illegal target for annotation

    c - "Segmentation fault"同时执行动态 malloc 代码

    macos - 从 MSVC 裸函数转换总线错误 : Inline x86 assembly with GCC asm{} block on Mac OS X,

    不同版本框架的 Git 工作流程

    javascript - 如何有条件地添加属性以 react DOM 元素