@@ -77,14 +77,36 @@ LivenessAnalysis::LivenessAnalysis(Function *Func) {
77
77
78
78
// Record what this instruction uses.
79
79
//
80
- // Note that Phi nodes are special and must be skipped. If we consider
81
- // their operands as uses, then Phi nodes in loops may use variables
82
- // before they are defined, and this messes with the algorithm.
80
+ // In order to track the operands of PHI nodes we need to be a bit crafty
81
+ // as otherwise we end up with live values in blocks where they actually
82
+ // don't exist. To avoid this, we need to mark as live any PHI operand
83
+ // from one block at the end of all other blocks. This leads to those
84
+ // values being killed immediately after entering the block in the
85
+ // backwards pass and thus the value never being live there.
83
86
//
84
87
// The book doesn't cover this quirk, as it explains liveness for
85
88
// non-SSA form, and thus doesn't need to worry about Phi nodes.
86
- if (isa<PHINode>(I))
89
+ if (isa<PHINode>(I)) {
90
+ PHINode *P = cast<PHINode>(&I);
91
+ for (unsigned IVC = 0 ; IVC < P->getNumIncomingValues (); IVC++) {
92
+ BasicBlock *IBB = P->getIncomingBlock (IVC);
93
+ Value *IV = P->getIncomingValue (IVC);
94
+ if (isa<Constant>(IV)) {
95
+ continue ;
96
+ }
97
+ // For each block that isn't the incoming block create a Def for this
98
+ // value. This means when we do the backwards liveness pass this
99
+ // value is immediately killed in the block.
100
+ for (auto *BBB = P->block_begin (); BBB != P->block_end (); BBB++) {
101
+ if (*BBB != IBB) {
102
+ Instruction *Last = &((*BBB)->back ());
103
+ Defs[Last].insert (IV);
104
+ }
105
+ }
106
+ Uses[&I].insert (IV);
107
+ }
87
108
continue ;
109
+ }
88
110
89
111
for (auto *U = I.op_begin (); U < I.op_end (); U++)
90
112
if ((!isa<Constant>(U)) && (!isa<BasicBlock>(U)) &&
0 commit comments