[llvm] b933c84 - [ValueTracking] Add support for `trunc nuw/nsw` in isKnowNonZero

Noah Goldstein via llvm-commits llvm-commits at lists.llvm.org
Wed Apr 24 00:53:29 PDT 2024


Author: Noah Goldstein
Date: 2024-04-24T02:53:11-05:00
New Revision: b933c8447b2a8797a882d3506460f49fb6f7bf34

URL: https://github.com/llvm/llvm-project/commit/b933c8447b2a8797a882d3506460f49fb6f7bf34
DIFF: https://github.com/llvm/llvm-project/commit/b933c8447b2a8797a882d3506460f49fb6f7bf34.diff

LOG: [ValueTracking] Add support for `trunc nuw/nsw` in isKnowNonZero

With `nsw`/`nuw`, the `trunc` is non-zero if its operand is non-zero.

Proofs: https://alive2.llvm.org/ce/z/iujmk6

Closes #89643

Added: 
    

Modified: 
    llvm/lib/Analysis/ValueTracking.cpp
    llvm/test/Analysis/ValueTracking/known-non-zero.ll

Removed: 
    


################################################################################
diff  --git a/llvm/lib/Analysis/ValueTracking.cpp b/llvm/lib/Analysis/ValueTracking.cpp
index 7501f78ca23b7b..de38eddaa98fef 100644
--- a/llvm/lib/Analysis/ValueTracking.cpp
+++ b/llvm/lib/Analysis/ValueTracking.cpp
@@ -2632,6 +2632,13 @@ static bool isKnownNonZeroFromOperator(const Operator *I,
             Q.DL.getTypeSizeInBits(I->getType()).getFixedValue())
       return isKnownNonZero(I->getOperand(0), Q, Depth);
     break;
+  case Instruction::Trunc:
+    // nuw/nsw trunc preserves zero/non-zero status of input.
+    if (auto *TI = dyn_cast<TruncInst>(I))
+      if (TI->hasNoSignedWrap() || TI->hasNoUnsignedWrap())
+        return isKnownNonZero(TI->getOperand(0), Q, Depth);
+    break;
+
   case Instruction::Sub:
     return isNonZeroSub(DemandedElts, Depth, Q, BitWidth, I->getOperand(0),
                         I->getOperand(1));

diff  --git a/llvm/test/Analysis/ValueTracking/known-non-zero.ll b/llvm/test/Analysis/ValueTracking/known-non-zero.ll
index 4d70f013c9a1a2..c00e47fba8c727 100644
--- a/llvm/test/Analysis/ValueTracking/known-non-zero.ll
+++ b/llvm/test/Analysis/ValueTracking/known-non-zero.ll
@@ -1452,9 +1452,7 @@ define i1 @trunc_nsw_non_zero(i8 %x) {
 ; CHECK-LABEL: @trunc_nsw_non_zero(
 ; CHECK-NEXT:    [[X_NE_Z:%.*]] = icmp ne i8 [[X:%.*]], 0
 ; CHECK-NEXT:    call void @llvm.assume(i1 [[X_NE_Z]])
-; CHECK-NEXT:    [[V:%.*]] = trunc nsw i8 [[X]] to i4
-; CHECK-NEXT:    [[R:%.*]] = icmp ne i4 [[V]], 0
-; CHECK-NEXT:    ret i1 [[R]]
+; CHECK-NEXT:    ret i1 true
 ;
   %x_ne_z = icmp ne i8 %x, 0
   call void @llvm.assume(i1 %x_ne_z)
@@ -1465,10 +1463,7 @@ define i1 @trunc_nsw_non_zero(i8 %x) {
 
 define i1 @trunc_nuw_non_zero(i8 %xx) {
 ; CHECK-LABEL: @trunc_nuw_non_zero(
-; CHECK-NEXT:    [[X:%.*]] = add nuw i8 [[XX:%.*]], 1
-; CHECK-NEXT:    [[V:%.*]] = trunc nuw i8 [[X]] to i4
-; CHECK-NEXT:    [[R:%.*]] = icmp eq i4 [[V]], 0
-; CHECK-NEXT:    ret i1 [[R]]
+; CHECK-NEXT:    ret i1 false
 ;
   %x = add nuw i8 %xx, 1
   %v = trunc nuw i8 %x to i4


        


More information about the llvm-commits mailing list