Index: llvm/lib/Transforms/Utils/BasicBlockUtils.cpp =================================================================== --- llvm/lib/Transforms/Utils/BasicBlockUtils.cpp +++ llvm/lib/Transforms/Utils/BasicBlockUtils.cpp @@ -1158,11 +1158,16 @@ } if (OldLatch) { - BasicBlock *NewLatch = L->getLoopLatch(); - if (NewLatch != OldLatch) { - MDNode *MD = OldLatch->getTerminator()->getMetadata("llvm.loop"); - NewLatch->getTerminator()->setMetadata("llvm.loop", MD); - OldLatch->getTerminator()->setMetadata("llvm.loop", nullptr); + Loop *IL = LI->getLoopFor(OldLatch); + // It's still possible that OldLatch is the latch of another inner loop, in + // which case we do not move the metadata. + if (IL && IL->getLoopLatch() != OldLatch) { + BasicBlock *NewLatch = L->getLoopLatch(); + if (NewLatch != OldLatch) { + MDNode *MD = OldLatch->getTerminator()->getMetadata("llvm.loop"); + NewLatch->getTerminator()->setMetadata("llvm.loop", MD); + OldLatch->getTerminator()->setMetadata("llvm.loop", nullptr); + } } } Index: llvm/test/Transforms/LoopSimplify/update_latch_md2.ll =================================================================== --- /dev/null +++ llvm/test/Transforms/LoopSimplify/update_latch_md2.ll @@ -0,0 +1,34 @@ +; Tests loop-simplify does not move the loop metadata, because +; the loopexit block is not the latch of the loop _bb6. + +; RUN: opt < %s -loop-simplify -S | FileCheck %s +; CHECK-LABEL: _bb7.loopexit: +; CHECK-NOT: br label %_bb7, !llvm.loop !0 +; CHECK-LABEL: _bb6: +; CHECK: br i1 %p, label %_bb6, label %_bb7.loopexit, !llvm.loop !0 + +define void @func(i1 %p) { +_bb1: + br label %_bb7 + +_bb7: + br i1 %p, label %_bb4, label %_bb2 + +_bb4: + br i1 %p, label %_bb5, label %_bb3 + +_bb5: + br label %_bb3 + +_bb3: + br label %_bb6 + +_bb6: + br i1 %p, label %_bb6, label %_bb7, !llvm.loop !0 + +_bb2: + ret void +} + +!0 = distinct !{!0, !1} +!1 = !{!"llvm.loop.mustprogress"}