Search code examples
llvmllvm-ir

eraseFromParent() vs removeFromParent() in llvm


I Understand the difference between eraseFromParent() and removeFromParent() is that former unlinks and deletes instruction from the BasicBlock, while later just unlinks but not delete it.

When should I use one over the other?. Looking for some example scenarios.


Solution

  • I'll use instructions in basic blocks as the example. The other kinds of lists are similar.

    Delete: If you want to drop an instruction completely, eraseFromParent() does that with one line of code.

    Delete slightly later: If you want to drop an instruction, but use it to create something else, then it may make sense to remove it from its basic block, compute the replacement based on the instruction, and only then delete the instruction. For example, if you have a pass that replaces some computations with reads from global variables this approach can make sense. It depends on how you compute the replacement.

    Don't delete: If you want to move an instruction elsewhere, then it may make sense to remove it from its basic block, do whatever else is necessary, and then insert it into its new home. For example, if you need to consider and perhaps move each instruction in a function once, then it's simple to write one loop that removes the instruction followed by one that inserts the instructions in their new home. That way you don't risk matching newly moved instructions.