"goto"语句如何影响CPU的"分支预测"?

wef*_*fa3 2 c cpu optimization goto branch-prediction

要了解有关CPU和代码优化的更多信息,我已经开始研究汇编编程.我还阅读了一些聪明的优化,比如"分支预测",CPU可以加速自身.

我的问题可能看起来很愚蠢,因为我还不太清楚这个问题.

我有一个非常模糊的记忆,我在某处(在互联网上)读过这些goto语句会降低程序的性能,因为它不能很好地处理CPU中的分支预测.然而,这可能只是我编造的内容并没有真正阅读过.

我认为这可能是真的.

我希望这个例子(在伪C中)将澄清为什么我认为是这样的:

int function(...) {
    VARIABLES DECLARED HERE

    if (HERE IS A TEST) {
        CODE HERE ...
    } else if (ANOTHER TEST) {
        CODE HERE ...
    } else {
        /*
        Let us assume that the CPU was smart and predicted this path.
        What about the jump to `label`?

        Is it possible for the CPU to "pre-fetch" the instructions over there?
        */
        goto label;
    }

    CODE HERE...

label:
    CODE HERE...
}
Run Code Online (Sandbox Code Playgroud)

对我来说,这似乎是一项非常复杂的任务.那是因为那时CPU需要查找goto跳转的位置,以便能够在那里预取指令.

你对此有所了解吗?

Sne*_*tel 6

无条件分支对于分支预测器不是问题,因为分支预测器不必预测它们.

它们为推测性指令获取单元增加了一点复杂性,因为分支(以及改变指令指针的其他指令)的存在意味着指令并不总是以线性顺序获取.当然,这也适用于条件分支.

请记住,分支预测和推测执行是不同的事情.您不需要对推测执行进行分支预测:您可以假设从不采用分支来推测性地执行代码,如果您确实采用了分支,则取消该分支之外的所有操作.在无条件分支的情况下,这将是一个特别愚蠢的事情,但它将保持逻辑简洁.(IIRC,这是第一个流水线处理器的工作方式.)

(I guess you could have branch prediction without speculative execution, but there wouldn't really be a point to it, since the branch predictor wouldn't have anybody to tell its predictions to.)

So yes, branches -- both conditional and unconditional -- increase the complexity of instruction fetch units. That's okay. CPU architects are some pretty smart people.

EDIT: Back in the bad old days, it was observed that the use of goto statements could adversely affect the ability of the compilers of the day to optimize code. This might be what you were thinking of. Modern compilers are much smarter, and in general are not taken too much aback by goto.