llvmllvm-irssa

LLVM IR position of predecessor block labels in phi node instruction


When using a phi node in a basic block is there a suggested order in which I should place the labels if there is a higher probability that the predecessor is a certain block. For example take the simple factorial function listed below.

define private i64 @fact(i64 %start) {
entry:
  %0 = icmp sle i64 1, %start
  br i1 %0, label %loop, label %endcond

loop:                                              ; preds = %loop, %entry
  %1 = phi i64 [ %res, %loop ], [ 1, %entry ]      ; if %start > 2 predecessor
  %2 = phi i64 [ %3, %loop ], [ %start, %entry ]   ; is likely %loop
  %res = mul i64 %1, %2
  %3 = sub i64 %2, 1
  %cond = icmp sle i64 1, %3
  br i1 %cond, label %loop, label %endcond

endcond:                                           ; preds = %loop, %entry
  %fin = phi i64 [ %res, %loop ], [ 1, %entry ]    ; highly unlikely
  ret i64 %fin                                     ; predecessor is %entry
}

While it is possible that the user will input @fact(1) it is unlikely, so I expect in most cases the predecessor block for the phi node in endcond to be post.loop. So is my assumption that in this case

%fin = phi i64 [ %res, %post.loop ], [ 1, %entry ]

is better than

%fin = phi i64 [ 1, %entry ], [ %res, %post.loop ]

correct? And if so, why or why not?


Solution

  • Doesn't make a difference. LLVM will do an analysis on your code to estimate the branch probabilities, and it uses that to order the resulting block.

    You can influence this by using branch weight metadata: http://llvm.org/docs/BlockFrequencyTerminology.html