[CVP] Simplify SRem when constantrange abs(lhs) < abs(rhs)
authorluxufan <luxufan@iscas.ac.cn>
Tue, 20 Dec 2022 15:03:04 +0000 (23:03 +0800)
committerluxufan <luxufan@iscas.ac.cn>
Tue, 3 Jan 2023 14:51:12 +0000 (22:51 +0800)
For `srem x, y`, if abs(constant range of x) less than abs(constant
range of y), we can simplify it as:
`srem x, y => x` if y is guaranteed to be positive.
'srem x, y => -x' if y is guaranteed to be negative.

Differential Revision: https://reviews.llvm.org/D140405

llvm/lib/Transforms/Scalar/CorrelatedValuePropagation.cpp
llvm/test/Transforms/CorrelatedValuePropagation/srem.ll

index fdebd6f..c50ba30 100644 (file)
@@ -905,6 +905,15 @@ static bool processSRem(BinaryOperator *SDI, LazyValueInfo *LVI) {
   if (SDI->getType()->isVectorTy())
     return false;
 
+  ConstantRange LCR = LVI->getConstantRange(SDI->getOperand(0), SDI);
+  ConstantRange RCR = LVI->getConstantRange(SDI->getOperand(1), SDI);
+
+  if (LCR.abs().icmp(CmpInst::ICMP_ULT, RCR.abs())) {
+    SDI->replaceAllUsesWith(SDI->getOperand(0));
+    SDI->eraseFromParent();
+    return true;
+  }
+
   struct Operand {
     Value *V;
     Domain D;
index 5c21756..5f6facd 100644 (file)
@@ -523,8 +523,7 @@ define dso_local i8 @abs_x_lt_abs_y_positive(i8 %x, i8 %y) {
 ; CHECK-NEXT:    [[AND_COND:%.*]] = and i1 [[AND_X]], [[Y_CMP]]
 ; CHECK-NEXT:    br i1 [[AND_COND]], label [[IF_ELSE:%.*]], label [[IF_THEN:%.*]]
 ; CHECK:       if.else:
-; CHECK-NEXT:    [[REM:%.*]] = srem i8 [[X]], [[Y]]
-; CHECK-NEXT:    ret i8 [[REM]]
+; CHECK-NEXT:    ret i8 [[X]]
 ; CHECK:       if.then:
 ; CHECK-NEXT:    ret i8 0
 ;
@@ -556,8 +555,7 @@ define dso_local i8 @abs_x_lt_abs_y_positive_unsigned_cmp(i8 %x, i8 %y) {
 ; CHECK-NEXT:    [[AND_COND:%.*]] = and i1 [[AND_X]], [[AND_Y]]
 ; CHECK-NEXT:    br i1 [[AND_COND]], label [[IF_ELSE:%.*]], label [[IF_THEN:%.*]]
 ; CHECK:       if.else:
-; CHECK-NEXT:    [[REM:%.*]] = srem i8 [[X]], [[Y]]
-; CHECK-NEXT:    ret i8 [[REM]]
+; CHECK-NEXT:    ret i8 [[X]]
 ; CHECK:       if.then:
 ; CHECK-NEXT:    ret i8 0
 ;
@@ -591,8 +589,7 @@ define dso_local i8 @abs_x_lt_abs_y_negative(i8 %x, i8 %y) {
 ; CHECK-NEXT:    [[AND_COND:%.*]] = and i1 [[AND_X]], [[AND_Y]]
 ; CHECK-NEXT:    br i1 [[AND_COND]], label [[IF_ELSE:%.*]], label [[IF_THEN:%.*]]
 ; CHECK:       if.else:
-; CHECK-NEXT:    [[REM:%.*]] = srem i8 [[X]], [[Y]]
-; CHECK-NEXT:    ret i8 [[REM]]
+; CHECK-NEXT:    ret i8 [[X]]
 ; CHECK:       if.then:
 ; CHECK-NEXT:    ret i8 0
 ;