【问题标题】:What is the difference between `select` and `phi` in LLVM IR?LLVM IR中的`select`和`phi`有什么区别?
【发布时间】:2020-07-23 06:42:02
【问题描述】:

例如,我有一个 C 代码:

void foo(int x) {
    int y;
    if (x > 0) {
        y = 1;
    } else {
        y = 2;
    }
    // do something with y
}

为了简化 LLVM IR 级别的代码(y 可以放入寄存器而不是堆栈),我可以使用 select

define void @foo(i32 %x) {
    %result = icmp sgt i32 %x, 0
    %y = select i1 %result, i32 1, i32 2
    ; do something with %y
}

但是,如果我使用phi,代码会变得更长:

define void @foo(i32 %x) {
    %result = icmp sgt i32 %x, 0
    br i1 %result, label %btrue, label %bfalse
btrue:
    br label %end
bfalse:
    br label %end
end:
    %y = phi i32 [1, %btrue], [2, %bfalse]
    ; do something with %y
    ret void
}

据我所知,phi 相对于select 的唯一优势是phi 支持2 个以上的分支,而select 仅支持2 个分支。除了这种情况,还有其他情况phi优于select吗?

【问题讨论】:

    标签: llvm llvm-ir ssa


    【解决方案1】:

    select 的操作数仅为Values,而phi 的操作数是ValueBasicBlock 的对。

    另一个区别是phi 可以转动函数的控制流,而select 只允许根据布尔值在两个值之间进行选择。粗略地说,select对应?:三元运算符,phi对应Cswitch语句,很多情况。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-05
      • 2010-11-01
      • 1970-01-01
      相关资源
      最近更新 更多