[llvm] [InstCombine] Support ptrtoint of gep folds for chain of geps (PR #137323)

Nikita Popov via llvm-commits llvm-commits at lists.llvm.org
Sat Apr 26 07:45:37 PDT 2025


================
@@ -2067,6 +2067,42 @@ Instruction *InstCombinerImpl::visitIntToPtr(IntToPtrInst &CI) {
   return nullptr;
 }
 
+Value *InstCombinerImpl::foldPtrToIntOfGEP(Type *IntTy, Value *Ptr) {
+  // Look through chain of one-use GEPs.
+  Type *PtrTy = Ptr->getType();
+  SmallVector<GEPOperator *> GEPs;
+  while (true) {
+    auto *GEP = dyn_cast<GEPOperator>(Ptr);
+    if (!GEP || !GEP->hasOneUse())
+      break;
+    GEPs.push_back(GEP);
+    Ptr = GEP->getPointerOperand();
+  }
+
+  // Don't handle case where GEP converts from pointer to vector.
+  if (GEPs.empty() || PtrTy != Ptr->getType())
+    return nullptr;
+
+  // Check whether we know the integer value of the base pointer.
+  Value *Res;
+  Type *IdxTy = DL.getIndexType(PtrTy);
+  if (match(Ptr, m_OneUse(m_IntToPtr(m_Value(Res)))) &&
----------------
nikic wrote:

This is pre-existing code tested here: https://github.com/llvm/llvm-project/blob/cd7497be6da6a3921dd1148d0590324a625e40e8/llvm/test/Transforms/InstCombine/cast_ptr.ll#L406-L419

I agree that this one-use requirement is unnecessary.

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


More information about the llvm-commits mailing list