Skip to content

Commit

Permalink
[InstCombine] More precise nuw preservation in ptrtoint of gep fold
Browse files Browse the repository at this point in the history
We can transfer a nuw flag from the gep to the add. Additionally,
the inbounds + nneg case can be relaxed to nusw + nneg. Finally,
don't forget to pass the correct context instruction to
SimplifyQuery.
  • Loading branch information
nikic committed Jul 11, 2024
1 parent c66e1d6 commit 4502ea8
Show file tree
Hide file tree
Showing 2 changed files with 40 additions and 1 deletion.
4 changes: 3 additions & 1 deletion llvm/lib/Transforms/InstCombine/InstCombineCasts.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -2070,7 +2070,9 @@ Instruction *InstCombinerImpl::visitPtrToInt(PtrToIntInst &CI) {
Base->getType() == Ty) {
Value *Offset = EmitGEPOffset(GEP);
auto *NewOp = BinaryOperator::CreateAdd(Base, Offset);
if (GEP->isInBounds() && isKnownNonNegative(Offset, SQ))
if (GEP->hasNoUnsignedWrap() ||
(GEP->hasNoUnsignedSignedWrap() &&
isKnownNonNegative(Offset, SQ.getWithInstruction(&CI))))
NewOp->setHasNoUnsignedWrap(true);
return NewOp;
}
Expand Down
37 changes: 37 additions & 0 deletions llvm/test/Transforms/InstCombine/cast_ptr.ll
Original file line number Diff line number Diff line change
Expand Up @@ -342,6 +342,43 @@ define i32 @ptr_add_in_int_not_inbounds(i32 %x, i32 %y) {
ret i32 %r
}

define i32 @ptr_add_in_int_nuw(i32 %x, i32 %y) {
; CHECK-LABEL: @ptr_add_in_int_nuw(
; CHECK-NEXT: [[R:%.*]] = add nuw i32 [[X:%.*]], [[Y:%.*]]
; CHECK-NEXT: ret i32 [[R]]
;
%ptr = inttoptr i32 %x to ptr
%p2 = getelementptr nuw i8, ptr %ptr, i32 %y
%r = ptrtoint ptr %p2 to i32
ret i32 %r
}

define i32 @ptr_add_in_int_nusw(i32 %x, i32 %y) {
; CHECK-LABEL: @ptr_add_in_int_nusw(
; CHECK-NEXT: [[R:%.*]] = add i32 [[X:%.*]], [[Y:%.*]]
; CHECK-NEXT: ret i32 [[R]]
;
%ptr = inttoptr i32 %x to ptr
%p2 = getelementptr nusw i8, ptr %ptr, i32 %y
%r = ptrtoint ptr %p2 to i32
ret i32 %r
}

define i32 @ptr_add_in_int_nusw_nneg(i32 %x, i32 %y) {
; CHECK-LABEL: @ptr_add_in_int_nusw_nneg(
; CHECK-NEXT: [[NNEG:%.*]] = icmp sgt i32 [[Y:%.*]], -1
; CHECK-NEXT: call void @llvm.assume(i1 [[NNEG]])
; CHECK-NEXT: [[R:%.*]] = add nuw i32 [[X:%.*]], [[Y]]
; CHECK-NEXT: ret i32 [[R]]
;
%nneg = icmp sge i32 %y, 0
call void @llvm.assume(i1 %nneg)
%ptr = inttoptr i32 %x to ptr
%p2 = getelementptr nusw i8, ptr %ptr, i32 %y
%r = ptrtoint ptr %p2 to i32
ret i32 %r
}

define i32 @ptr_add_in_int_const(i32 %x) {
; CHECK-LABEL: @ptr_add_in_int_const(
; CHECK-NEXT: [[R:%.*]] = add nuw i32 [[X:%.*]], 4096
Expand Down

0 comments on commit 4502ea8

Please sign in to comment.