I'm trying to implement liveness analysis to remove dead instructions. I know that isInstructionTriviallyDead() exists, however, I want to learn how to remove code using def-use (or use-def) chains.
The way I am currently doing it is I am iterating through all the instructions in a block (using inst_iterator), and for each instruction, looping through all of its uses. Ultimately, if an instruction has no use, then I consider it dead, and can therefore remove it using eraseFromParent()
This looks something like:
for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
bool deadInst = true;
Instruction *inst = &*I;
for (User* pUser : inst->users()) {
// If we enter this loop, we have at least one use, so instruction isn't dead
deadInst = false;
}
// deadInst is true if we didn't enter the loop, so has no uses
if (deadInst) {
inst->eraseFromParent();
}
}
The problem is, a return instruction has no uses assosciated with it (and I'm sure there are other definitions with no uses). However a return instruction shouldn't be removed as it'll lead to semantically incorrect code.
Is my general approach to removing instructions via liveness analysis okay? What can I do to ensure instructions like return are not removed?
Any pointers are much appreciated :)
also check whether the instruction is a terminator instruction (
inst->isTerminator())