[llvm] ec2e5b8 - Fix iterator corruption in splitBasicBlockBefore

Max Kazantsev via llvm-commits llvm-commits at lists.llvm.org
Thu Oct 27 04:11:15 PDT 2022


Author: Max Kazantsev
Date: 2022-10-27T17:54:15+07:00
New Revision: ec2e5b8c92e6fc98fdb33ff1bd4fba5f92dc7194

URL: https://github.com/llvm/llvm-project/commit/ec2e5b8c92e6fc98fdb33ff1bd4fba5f92dc7194
DIFF: https://github.com/llvm/llvm-project/commit/ec2e5b8c92e6fc98fdb33ff1bd4fba5f92dc7194.diff

LOG: Fix iterator corruption in splitBasicBlockBefore

We should not delete block predecessors (via replacing successors
of terminators) while iterating them, otherwise we may skip some
of them. Instead, save predecessors to a separate vector and iterate
over it.

Added: 
    

Modified: 
    llvm/lib/IR/BasicBlock.cpp

Removed: 
    


################################################################################
diff  --git a/llvm/lib/IR/BasicBlock.cpp b/llvm/lib/IR/BasicBlock.cpp
index 687865d9a3b37..20101a96e8c4f 100644
--- a/llvm/lib/IR/BasicBlock.cpp
+++ b/llvm/lib/IR/BasicBlock.cpp
@@ -452,7 +452,11 @@ BasicBlock *BasicBlock::splitBasicBlockBefore(iterator I, const Twine &BBName) {
   // If there were PHI nodes in 'this' block, the PHI nodes are updated
   // to reflect that the incoming branches will be from the New block and not
   // from predecessors of the 'this' block.
-  for (BasicBlock *Pred : predecessors(this)) {
+  // Save predecessors to separate vector before modifying them.
+  SmallVector<BasicBlock *, 4> Predecessors;
+  for (BasicBlock *Pred : predecessors(this))
+    Predecessors.push_back(Pred);
+  for (BasicBlock *Pred : Predecessors) {
     Instruction *TI = Pred->getTerminator();
     TI->replaceSuccessorWith(this, New);
     this->replacePhiUsesWith(Pred, New);


        


More information about the llvm-commits mailing list