Skip to content

Commit c45f939

Browse files
committed
[InstCombine] Generalize ptrtoint(gep) fold (NFC)
We're currently handling a special case of ptrtoint gep -> add ptrtoint. Reframe the code to make it easier to add more patterns for this transform.
1 parent 09b1cfc commit c45f939

File tree

1 file changed

+21
-4
lines changed

1 file changed

+21
-4
lines changed

llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp

Lines changed: 21 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2025,6 +2025,25 @@ Instruction *InstCombinerImpl::visitIntToPtr(IntToPtrInst &CI) {
20252025
return nullptr;
20262026
}
20272027

2028+
// Whether we should convert ptrtoint(gep P, X) to ptrtoint(P) + X
2029+
static bool shouldPushPtrToIntThroughGEP(GEPOperator *GEP, Type *IntTy,
2030+
const DataLayout &DL) {
2031+
if (!GEP->hasOneUse())
2032+
return false;
2033+
2034+
// Skip cases whether there is a mismatch between the pointer integer type
2035+
// and the index type, or the GEP performs an implicit splat operation.
2036+
if (DL.getIndexType(GEP->getType()) != IntTy ||
2037+
GEP->getType() != GEP->getPointerOperand()->getType())
2038+
return false;
2039+
2040+
// (ptrtoint (gep (inttoptr Base), Offset)) -> Base + Offset
2041+
if (match(GEP->getPointerOperand(), m_OneUse(m_IntToPtr(m_Value()))))
2042+
return true;
2043+
2044+
return false;
2045+
}
2046+
20282047
Instruction *InstCombinerImpl::visitPtrToInt(PtrToIntInst &CI) {
20292048
// If the destination integer type is not the intptr_t type for this target,
20302049
// do a ptrtoint to intptr_t then do a trunc or zext. This allows the cast
@@ -2064,10 +2083,8 @@ Instruction *InstCombinerImpl::visitPtrToInt(PtrToIntInst &CI) {
20642083
}
20652084

20662085
// (ptrtoint (gep (inttoptr Base), ...)) -> Base + Offset
2067-
Value *Base;
2068-
if (GEP->hasOneUse() &&
2069-
match(GEP->getPointerOperand(), m_OneUse(m_IntToPtr(m_Value(Base)))) &&
2070-
Base->getType() == Ty) {
2086+
if (shouldPushPtrToIntThroughGEP(GEP, Ty, DL)) {
2087+
Value *Base = Builder.CreatePtrToInt(GEP->getPointerOperand(), Ty);
20712088
Value *Offset = EmitGEPOffset(GEP);
20722089
auto *NewOp = BinaryOperator::CreateAdd(Base, Offset);
20732090
if (GEP->hasNoUnsignedWrap() ||

0 commit comments

Comments
 (0)