Skip to content

[ValueTracking] Handle trunc nuw in computeKnownBitsFromICmpCond #125414

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Feb 3, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 4 additions & 1 deletion llvm/lib/Analysis/ValueTracking.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -776,7 +776,10 @@ static void computeKnownBitsFromICmpCond(const Value *V, ICmpInst *Cmp,
if (match(LHS, m_Trunc(m_Specific(V)))) {
KnownBits DstKnown(LHS->getType()->getScalarSizeInBits());
computeKnownBitsFromCmp(LHS, Pred, LHS, RHS, DstKnown, SQ);
Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
if (cast<TruncInst>(LHS)->hasNoUnsignedWrap())
Known = Known.unionWith(DstKnown.zext(Known.getBitWidth()));
else
Known = Known.unionWith(DstKnown.anyext(Known.getBitWidth()));
return;
}

Expand Down
49 changes: 49 additions & 0 deletions llvm/test/Transforms/InstCombine/known-bits.ll
Original file line number Diff line number Diff line change
Expand Up @@ -480,6 +480,55 @@ if.else:
ret i64 13
}

define i64 @test_icmp_trunc_nuw(i64 %a) {
; CHECK-LABEL: @test_icmp_trunc_nuw(
; CHECK-NEXT: entry:
; CHECK-NEXT: [[CAST:%.*]] = trunc nuw i64 [[A:%.*]] to i32
; CHECK-NEXT: [[CMP:%.*]] = icmp sgt i32 [[CAST]], 0
; CHECK-NEXT: br i1 [[CMP]], label [[IF_THEN:%.*]], label [[IF_ELSE:%.*]]
; CHECK: if.then:
; CHECK-NEXT: ret i64 [[A]]
; CHECK: if.else:
; CHECK-NEXT: ret i64 0
;
entry:
%cast = trunc nuw i64 %a to i32
%cmp = icmp sgt i32 %cast, 0
br i1 %cmp, label %if.then, label %if.else

if.then:
%b = and i64 %a, 2147483647
ret i64 %b

if.else:
ret i64 0
}

define i64 @test_icmp_trunc_no_nuw(i64 %a) {
; CHECK-LABEL: @test_icmp_trunc_no_nuw(
; CHECK-NEXT: entry:
; CHECK-NEXT: [[CAST:%.*]] = trunc i64 [[A:%.*]] to i32
; CHECK-NEXT: [[CMP:%.*]] = icmp sgt i32 [[CAST]], 0
; CHECK-NEXT: br i1 [[CMP]], label [[IF_THEN:%.*]], label [[IF_ELSE:%.*]]
; CHECK: if.then:
; CHECK-NEXT: [[B:%.*]] = and i64 [[A]], 2147483647
; CHECK-NEXT: ret i64 [[B]]
; CHECK: if.else:
; CHECK-NEXT: ret i64 0
;
entry:
%cast = trunc i64 %a to i32
%cmp = icmp sgt i32 %cast, 0
br i1 %cmp, label %if.then, label %if.else

if.then:
%b = and i64 %a, 2147483647
ret i64 %b

if.else:
ret i64 0
}

define i1 @test_icmp_or_distjoint(i8 %n, i1 %other) {
; CHECK-LABEL: @test_icmp_or_distjoint(
; CHECK-NEXT: entry:
Expand Down