Index: llvm/lib/Transforms/Utils/LoopUnroll.cpp =================================================================== --- llvm/lib/Transforms/Utils/LoopUnroll.cpp +++ llvm/lib/Transforms/Utils/LoopUnroll.cpp @@ -763,13 +763,6 @@ } } - // When completely unrolling, the last latch becomes unreachable. - if (!LatchIsExiting && CompletelyUnroll) { - BranchInst *Term = cast(Latches.back()->getTerminator()); - new UnreachableInst(Term->getContext(), Term); - Term->eraseFromParent(); - } - // Update dominators of blocks we might reach through exits. // Immediate dominator of such block might change, because we add more // routes which can lead to the exit: we can now reach it from the copied @@ -819,6 +812,12 @@ DT->verify(DominatorTree::VerificationLevel::Fast)); DomTreeUpdater DTU(DT, DomTreeUpdater::UpdateStrategy::Lazy); + + // When completely unrolling, the last latch becomes unreachable. + if (!LatchIsExiting && CompletelyUnroll) + changeToUnreachable(&Latches.back()->front(), /* UseTrap */ false, + PreserveLCSSA, &DTU); + // Merge adjacent basic blocks, if possible. for (BasicBlock *Latch : Latches) { BranchInst *Term = dyn_cast(Latch->getTerminator()); Index: llvm/test/Transforms/LoopUnroll/unroll-unconditional-latch.ll =================================================================== --- llvm/test/Transforms/LoopUnroll/unroll-unconditional-latch.ll +++ llvm/test/Transforms/LoopUnroll/unroll-unconditional-latch.ll @@ -28,7 +28,6 @@ ; CHECK-NEXT: store i32 0, i32* [[PTR_3]], align 4 ; CHECK-NEXT: br i1 true, label [[IF_END_LOOPEXIT:%.*]], label [[FOR_LATCH_3:%.*]] ; CHECK: for.latch.3: -; CHECK-NEXT: store volatile i64 3, i64* [[OUT]], align 4 ; CHECK-NEXT: unreachable ;