[llvm] [ValueTracking] Allow getUnderlyingPointer to look through inttoptr/ptrtoint round trip casts (PR #146432)

via llvm-commits llvm-commits at lists.llvm.org
Mon Jun 30 16:05:06 PDT 2025


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-llvm-analysis

Author: Drew Kersnar (dakersnar)

<details>
<summary>Changes</summary>

It has been established in past discussions that optimizing away a round trip ptrtoint -> inttoptr cast in something like InstCombine is not correct (https://www.ralfj.de/blog/2020/12/14/provenance.html, https://github.com/llvm/llvm-project/issues/33896). However, is it possibly correct to strip this round trip when recursing through `getUnderlyingObject`? This would improve alias analysis.

---
Full diff: https://github.com/llvm/llvm-project/pull/146432.diff


2 Files Affected:

- (modified) llvm/lib/Analysis/ValueTracking.cpp (+4) 
- (modified) llvm/unittests/Analysis/ValueTrackingTest.cpp (+12) 


``````````diff
diff --git a/llvm/lib/Analysis/ValueTracking.cpp b/llvm/lib/Analysis/ValueTracking.cpp
index e576f4899810a..837c6a6caa4b2 100644
--- a/llvm/lib/Analysis/ValueTracking.cpp
+++ b/llvm/lib/Analysis/ValueTracking.cpp
@@ -6661,6 +6661,10 @@ const Value *llvm::getUnderlyingObject(const Value *V, unsigned MaxLookup) {
       if (!NewV->getType()->isPointerTy())
         return V;
       V = NewV;
+    } else if (Operator::getOpcode(V) == Instruction::IntToPtr &&
+               Operator::getOpcode(cast<Operator>(V)->getOperand(0)) ==
+                   Instruction::PtrToInt) {
+      V = cast<Operator>(cast<Operator>(V)->getOperand(0))->getOperand(0);
     } else if (auto *GA = dyn_cast<GlobalAlias>(V)) {
       if (GA->isInterposable())
         return V;
diff --git a/llvm/unittests/Analysis/ValueTrackingTest.cpp b/llvm/unittests/Analysis/ValueTrackingTest.cpp
index 129052fbe08b8..b40f38d464ed9 100644
--- a/llvm/unittests/Analysis/ValueTrackingTest.cpp
+++ b/llvm/unittests/Analysis/ValueTrackingTest.cpp
@@ -3350,6 +3350,18 @@ TEST_F(ValueTrackingTest, ComputeConstantRange) {
   }
 }
 
+TEST_F(ValueTrackingTest, GetUnderlyingObject) {
+  parseAssembly(R"(
+    @globalmem = external global i8
+    define void @test() {
+      %A = getelementptr i8, ptr @globalmem, i64 0
+      %A2 = getelementptr i8, ptr inttoptr (i32 ptrtoint (ptr @globalmem to i32) to ptr), i64 0
+      ret void
+    }
+  )");
+  EXPECT_EQ(getUnderlyingObject(A), getUnderlyingObject(A2));
+}
+
 struct FindAllocaForValueTestParams {
   const char *IR;
   bool AnyOffsetResult;

``````````

</details>


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


More information about the llvm-commits mailing list