[llvm] [MemCpyOpt] allow more memcpy-to-memcpy optimization (PR #150792)

Nikita Popov via llvm-commits llvm-commits at lists.llvm.org
Wed Jan 14 13:42:36 PST 2026


================
@@ -1640,6 +1636,46 @@ bool MemCpyOptPass::performStackMoveOptzn(Instruction *Load, Instruction *Store,
   if (!CaptureTrackingWithModRef(DestAlloca, DestModRefCallback,
                                  DestAddressCaptured))
     return false;
+
+  // Check that copy is full with dest size, either because it wrote every byte,
+  // or it was fresh. The store itself was ignored earlier, but might be in a
+  // loop, so it could (in rare cases) observe that earlier store which needs to
+  // be checked for now. For example, a source language might emit code matching
+  // that pattern for a simple array reverse with a struct element type:
+  //   for (i = 0; i < size; i++) dest[size - i - 1] = src[i];
+  if (Size != *DestSize) {
+    // Similar analysis to overreadUndefContents
+    MemoryLocation Loc;
+    Value *Ptr;
+    if (auto SI = dyn_cast<StoreInst>(Store)) {
+      Loc = MemoryLocation::get(SI);
+      Ptr = SI->getPointerOperand();
+    } else if (auto MI = dyn_cast<MemCpyInst>(Store)) {
+      Loc = MemoryLocation::getForDest(MI);
+      Ptr = MI->getDest();
+    } else {
+      llvm_unreachable("performStackMoveOptzn must have a known store kind");
+    }
+    // If offset and size are constant, then this overwrote the same bytes every
+    // time anyways.
+    if (!Ptr->getPointerOffsetFrom(DestAlloca, DL)) {
----------------
nikic wrote:

Currently the store must always be to the start of DestAlloca, so we'll never reach this code path. So I think under the current limitation, we can just drop the size check entirely. I tried to come up with some case where a partial loop copy with zero offset would be problematic, but didn't find one.

https://github.com/llvm/llvm-project/pull/150792


More information about the llvm-commits mailing list