I am trying to write a compiler that converts a simple imperative language to SSA form, but I am having trouble with loops. As an example, I have some code that looks like:
fun count() {
i = 0;
while(i < 10) {
x = i + 1
i = x;
}
return i;
}
I then convert it to a control flow graph that looks like this:
0 ->
predecessors = []
successors = [1,2]
dominators = [0]
strict dominators = []
dominatees = [0,1,2]
dominance frontier = []
inverse dominance frontier = []
immediate dominator = none
immediate dominatees = [1,2]
instructions =
r := 0
i := 0
if i >= 10 goto 2 else goto 1
1 ->
predecessors = [0,1]
successors = [1,2]
dominators = [0,1]
strict dominators = [0]
dominatees = [1]
dominance frontier = [1,2]
inverse dominance frontier = [1]
immediate dominator = 0
immediate dominatees = []
instructions =
x := i + 1
i := x
if i < 10 goto 1 else goto 2
2 ->
predecessors = [0,1]
successors = []
dominators = [0,2]
strict dominators = [0]
dominatees = [2]
dominance frontier = []
inverse dominance frontier = [1]
immediate dominator = 0
immediate dominatees = []
instructions =
r := i
ret
The issue I'm running into is that when I use the algorithm for placing phi nodes described in section 5.1 of Efficiently Computing Static Single Assignment Form and the Control Dependence Graph, I get something like this:
0 ->
predecessors = []
successors = [1,2]
...
instructions =
r := 0
i := 0
if i >= 10 goto 2 else goto 1
1 ->
predecessors = [0,1]
successors = [1,2]
...
instructions =
x := phi(x, x)
i := phi(i, i)
x := i + 1
i := x
if i < 10 goto 1 else goto 2
2 ->
predecessors = [0,1]
successors = []
...
instructions =
x := phi(x, x)
i := phi(i, i)
r := i
ret
I understand why a phi is necessary for i
in basic block #1 and #2, but I don't understand why phis are necessary for x
, and in fact they seem to break the renaming algorithm that follows (specifically, at one point where the renaming algorithm tries to pop off the S("x")
stack, that stack is empty, because x
was not assigned to in basic block #0). Did I somehow incorrectly implement this algorithm, or is there some subtlety I'm not understanding?