[llvm] [Loads] Allow replacement of null with ptr in `canReplacePointersIfEqual` (PR #184348)

Antonio Frighetto via llvm-commits llvm-commits at lists.llvm.org
Tue Mar 3 06:34:52 PST 2026


https://github.com/antoniofrighetto created https://github.com/llvm/llvm-project/pull/184348

It should always be valid to allow the replacement of null with the destination pointer, as moving from nullary provenance to a non-nullary one preserves provenance monotonicity.

>From 704ca1d4122e39f6f00ff356107c29665b3d5853 Mon Sep 17 00:00:00 2001
From: Antonio Frighetto <me at antoniofrighetto.com>
Date: Tue, 3 Mar 2026 15:23:11 +0100
Subject: [PATCH] [Loads] Allow replacement of null with ptr in
 `canReplacePointersIfEqual`

It should always be valid to allow the replacement of null with the
destination pointer, as moving from nullary provenance to a non-nullary
one preserves provenance monotonicity.
---
 llvm/lib/Analysis/Loads.cpp           | 8 ++++++--
 llvm/unittests/Analysis/LoadsTest.cpp | 1 +
 2 files changed, 7 insertions(+), 2 deletions(-)

diff --git a/llvm/lib/Analysis/Loads.cpp b/llvm/lib/Analysis/Loads.cpp
index 2e855f918c913..23a38eddaab88 100644
--- a/llvm/lib/Analysis/Loads.cpp
+++ b/llvm/lib/Analysis/Loads.cpp
@@ -827,14 +827,18 @@ static bool isPointerUseReplacable(const Use &U, bool HasNonAddressBits) {
   return Limit != 0;
 }
 
-// Returns true if `To` is a null pointer, constant dereferenceable pointer or
-// both pointers have the same underlying objects.
+// Returns true if `From` is a null pointer, `To` is a null pointer, or `To` is
+// a constant dereferenceable pointer, or both pointers have the same underlying
+// objects.
 static bool isPointerAlwaysReplaceable(const Value *From, const Value *To,
                                        const DataLayout &DL) {
   // This is not strictly correct, but we do it for now to retain important
   // optimizations.
   if (isa<ConstantPointerNull>(To))
     return true;
+  // Conversely, replacing null with destination pointer is always valid.
+  if (isa<ConstantPointerNull>(From))
+    return true;
   if (isa<Constant>(To) && To->getType()->isPointerTy() &&
       isDereferenceablePointer(To, Type::getInt8Ty(To->getContext()), DL))
     return true;
diff --git a/llvm/unittests/Analysis/LoadsTest.cpp b/llvm/unittests/Analysis/LoadsTest.cpp
index 2433abe9f918e..f48ad69d16089 100644
--- a/llvm/unittests/Analysis/LoadsTest.cpp
+++ b/llvm/unittests/Analysis/LoadsTest.cpp
@@ -105,6 +105,7 @@ define void @f(ptr %p1, ptr %p2, i64 %i) {
   EXPECT_FALSE(canReplacePointersIfEqual(P1, P2, DL));
   EXPECT_TRUE(canReplacePointersIfEqual(P1, ConstDerefPtr, DL));
   EXPECT_TRUE(canReplacePointersIfEqual(P1, NullPtr, DL));
+  EXPECT_TRUE(canReplacePointersIfEqual(NullPtr, P1, DL));
 
   GetElementPtrInst *BasedOnP1 = cast<GetElementPtrInst>(&*++InstIter);
   EXPECT_TRUE(canReplacePointersIfEqual(BasedOnP1, P1, DL));



More information about the llvm-commits mailing list