The following code from /llvm/lib/Transforms/Utils/LoopUnrollAndJam.cpp can be used by other transformations:
while (!MergeBlocks.empty()) { BasicBlock *BB = *MergeBlocks.begin(); BranchInst *Term = dyn_cast<BranchInst>(BB->getTerminator()); if (Term && Term->isUnconditional() && L->contains(Term->getSuccessor(0))) { BasicBlock *Dest = Term->getSuccessor(0); BasicBlock *Fold = Dest->getUniquePredecessor(); if (MergeBlockIntoPredecessor(Dest, &DTU, LI)) { // Don't remove BB and add Fold as they are the same BB assert(Fold == BB); (void)Fold; MergeBlocks.erase(Dest); } else MergeBlocks.erase(BB); } else MergeBlocks.erase(BB); }
Hence it should be separated into its own utility function.
Nit: s/branch and if L/branch. If L/