LLVM has phi instruction with quite weird explanation:
The 'phi' instruction is used to implement the φ node in the SSA graph representing the function.
Typically it is used to implement branching. If I understood correctly, it is needed to make dependency analysis possible and in some cases it could help to avoid unnecessary loading. However it's still hard to understand what it does exactly.
Kaleidoscope example explains it fairly nicely for if
case. However it's not that clear how to implement logical operations like &&
and ||
. If I type the following to online llvm compiler:
void main1(bool r, bool y) {
bool l = y || r;
}
Last several lines completely confuse me:
; <label>:10 ; preds = %7, %0
%11 = phi i1 [ true, %0 ], [ %9, %7 ]
%12 = zext i1 %11 to i8
Looks like phi node produces a result which can be used. And I was under impression that phi node just defines from which paths values coming.
Could someone explain what is a Phi node, and how to implement ||
with it?
A phi node is an instruction used to select a value depending on the predecessor of the current block (Look here to see the full hierarchy - it's also used as a value, which is one of the classes which it inherits from).
Phi nodes are necessary due to the structure of the SSA (static single assignment) style of the LLVM code - for example, the following C++ function
gets translated into the following IR: (created through
clang -c -emit-llvm file.c -o out.bc
- and then viewed throughllvm-dis
)So what happens here? Unlike the C++ code, where the variable
bool l
could be either 0 or 1, in the LLVM IR it has to be defined once. So we check if%tobool
is true, and then jump tolor.end
orlor.rhs
.In
lor.end
we finally have the value of the || operator. If we arrived from the entry block - then it's just true. Otherwise, it is equal to the value of%tobool2
- and that's exactly what we get from the following IR line:The
phi
node is a solution of the problem in compilers to convert the IR into "Static single assignment" form. To understand better understand the solution I would suggest better understand the problem.So I will one up you "Why is
phi
node".You don't need to use phi at all. Just create bunch of temporary variables. LLVM optimization passes will take care of optimizing temporary variables away and will use phi node for that automatically.
For example, if you want to do this:
You can use phi node for that (in pseudocode):
But you can do without phi node (in pseudocode):
By running optimization passes with llvm this second code will get optimized to first code.