diff --git a/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp b/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp --- a/llvm/lib/Transforms/Utils/BasicBlockUtils.cpp +++ b/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); + } } } diff --git a/llvm/test/Transforms/LoopSimplify/update_latch_md2.ll b/llvm/test/Transforms/LoopSimplify/update_latch_md2.ll --- a/llvm/test/Transforms/LoopSimplify/update_latch_md2.ll +++ b/llvm/test/Transforms/LoopSimplify/update_latch_md2.ll @@ -1,13 +1,11 @@ ; Tests loop-simplify does not move the loop metadata, because ; the loopexit block is not the latch of the loop _bb6. -; FIXME(#55416): The metadata should not move. - ; RUN: opt < %s -passes=loop-simplify -S | FileCheck %s ; CHECK-LABEL: loop.header.loopexit: -; CHECK: br label %loop.header, !llvm.loop !0 +; CHECK-NOT: br label %loop.header, !llvm.loop !0 ; CHECK-LABEL: loop.latch: -; CHECK-NOT: br i1 %p, label %loop.latch, label %loop.header.loopexit, !llvm.loop !0 +; CHECK: br i1 %p, label %loop.latch, label %loop.header.loopexit, !llvm.loop !0 define void @func(i1 %p) { bb1: