Iterator Invalidation in LLVM

If I use an iterator to loop through all the instructions in a Function like this:

for (inst_iterator I = inst_begin(F), E = inst_end(F); I != E; ++I) {
// Code inserting instructions or deleting instructions

Will the iterator get invalidated if changes are made to the IR by inserting or deleting instructions?
If yes, will doing I = inst_begin(F) at the end of the loop make the iterator valid again?



It will become valid, but there are better ways: for inserting instructions, consider using llvm::IRBuilder; for deleting instructions, please collect llvm::Instruction* you want to remove in a list first before removing them in a separate phase.

Thanks for the reply. What advantage does using llvm::IRBuilder have. Does it also validate the iterator?

The primary advantage of IRBuilder is its ease of use: once specified with an insertion point you can continuedly insert new instructions by calling IRBuilder’s APIs without worrying about details like whether the iterator is valid or not. Speaking of its IRBuilder’s APIs, they’re sometimes more ergonomics. For instance, to create an arithmetic add instruction, IRBuilder::CreateAdd is more straightforward than using BinaryOperator::Create.

1 Like