[llvm] 50ece4c - [ValueTracking] Add better support for ConstantRange(And)

Noah Goldstein via llvm-commits llvm-commits at lists.llvm.org
Thu Oct 12 12:12:42 PDT 2023


Author: Noah Goldstein
Date: 2023-10-12T14:12:26-05:00
New Revision: 50ece4cba949787241b5fbfc94be6cfdc66e90ee

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

LOG: [ValueTracking] Add better support for ConstantRange(And)

The fairly common power of two pattern `X & -X` can be capped at the
highest power of 2 (signbit set).

Added: 
    

Modified: 
    llvm/lib/Analysis/ValueTracking.cpp
    llvm/test/Analysis/ValueTracking/constant-ranges.ll

Removed: 
    


################################################################################
diff  --git a/llvm/lib/Analysis/ValueTracking.cpp b/llvm/lib/Analysis/ValueTracking.cpp
index 9b29d64c97f797b..11b39751b542f15 100644
--- a/llvm/lib/Analysis/ValueTracking.cpp
+++ b/llvm/lib/Analysis/ValueTracking.cpp
@@ -8492,6 +8492,11 @@ static void setLimitsForBinOp(const BinaryOperator &BO, APInt &Lower,
     if (match(BO.getOperand(1), m_APInt(C)))
       // 'and x, C' produces [0, C].
       Upper = *C + 1;
+    // X & -X is a power of two or zero. So we can cap the value at max power of
+    // two.
+    if (match(BO.getOperand(0), m_Neg(m_Specific(BO.getOperand(1)))) ||
+        match(BO.getOperand(1), m_Neg(m_Specific(BO.getOperand(0)))))
+      Upper = APInt::getSignedMinValue(Width) + 1;
     break;
 
   case Instruction::Or:

diff  --git a/llvm/test/Analysis/ValueTracking/constant-ranges.ll b/llvm/test/Analysis/ValueTracking/constant-ranges.ll
index 14331c251ff5239..26e01efedd3dfc7 100644
--- a/llvm/test/Analysis/ValueTracking/constant-ranges.ll
+++ b/llvm/test/Analysis/ValueTracking/constant-ranges.ll
@@ -96,11 +96,7 @@ define i1 @shl_X_C_ugt_fail2(i8 %x) {
 
 define i1 @and_ugt(i8 %xx) {
 ; CHECK-LABEL: @and_ugt(
-; CHECK-NEXT:    [[X:%.*]] = mul i8 [[XX:%.*]], [[XX]]
-; CHECK-NEXT:    [[NEGX:%.*]] = sub i8 0, [[X]]
-; CHECK-NEXT:    [[X_P2:%.*]] = and i8 [[NEGX]], [[X]]
-; CHECK-NEXT:    [[R:%.*]] = icmp ugt i8 [[X_P2]], -128
-; CHECK-NEXT:    ret i1 [[R]]
+; CHECK-NEXT:    ret i1 false
 ;
   %x = mul i8 %xx, %xx  ; thwart complexity-based canonicalization
   %negx = sub i8 0, %x
@@ -111,11 +107,7 @@ define i1 @and_ugt(i8 %xx) {
 
 define i1 @and_ugt2(i8 %xx) {
 ; CHECK-LABEL: @and_ugt2(
-; CHECK-NEXT:    [[X:%.*]] = mul i8 [[XX:%.*]], [[XX]]
-; CHECK-NEXT:    [[NEGX:%.*]] = sub i8 0, [[X]]
-; CHECK-NEXT:    [[X_P2:%.*]] = and i8 [[X]], [[NEGX]]
-; CHECK-NEXT:    [[R:%.*]] = icmp ugt i8 [[X_P2]], -128
-; CHECK-NEXT:    ret i1 [[R]]
+; CHECK-NEXT:    ret i1 false
 ;
   %x = mul i8 %xx, %xx  ; thwart complexity-based canonicalization
   %negx = sub i8 0, %x


        


More information about the llvm-commits mailing list