[llvm] 4a19e61 - [InstCombine] Fold abs(-x) -> abs(x)

Craig Topper via llvm-commits llvm-commits at lists.llvm.org
Sat Aug 1 13:25:10 PDT 2020


Author: Craig Topper
Date: 2020-08-01T13:25:00-07:00
New Revision: 4a19e6156ed5b6e87d708e6de29b675be69c574f

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

LOG: [InstCombine] Fold abs(-x) -> abs(x)

Negating the input doesn't matter. I left a FIXME to copy the nsw flag if its present on the neg but not on the abs.

Reviewed By: nikic

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

Added: 
    

Modified: 
    llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
    llvm/test/Transforms/InstCombine/abs-intrinsic.ll

Removed: 
    


################################################################################
diff  --git a/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp b/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
index ed93c33c1a59..4eb3e2e4434f 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineCalls.cpp
@@ -769,6 +769,16 @@ Instruction *InstCombinerImpl::visitCallInst(CallInst &CI) {
     if (Value *V = lowerObjectSizeCall(II, DL, &TLI, /*MustSucceed=*/false))
       return replaceInstUsesWith(CI, V);
     return nullptr;
+  case Intrinsic::abs: {
+    Value *IIOperand = II->getArgOperand(0);
+    // abs(-x) -> abs(x)
+    // TODO: Copy nsw if it was present on the neg?
+    Value *X;
+    if (match(IIOperand, m_Neg(m_Value(X))))
+      return replaceOperand(*II, 0, X);
+
+    break;
+  }
   case Intrinsic::bswap: {
     Value *IIOperand = II->getArgOperand(0);
     Value *X = nullptr;

diff  --git a/llvm/test/Transforms/InstCombine/abs-intrinsic.ll b/llvm/test/Transforms/InstCombine/abs-intrinsic.ll
index ed845cc84267..9e64aea9dabe 100644
--- a/llvm/test/Transforms/InstCombine/abs-intrinsic.ll
+++ b/llvm/test/Transforms/InstCombine/abs-intrinsic.ll
@@ -165,3 +165,23 @@ define <4 x i1> @abs_known_not_int_min_vec(<4 x i32> %x) {
   %c2 = icmp sge <4 x i32> %abs, zeroinitializer
   ret <4 x i1> %c2
 }
+
+define i32 @abs_of_neg(i32 %x) {
+; CHECK-LABEL: @abs_of_neg(
+; CHECK-NEXT:    [[B:%.*]] = call i32 @llvm.abs.i32(i32 [[X:%.*]], i1 false)
+; CHECK-NEXT:    ret i32 [[B]]
+;
+  %a = sub i32 0, %x
+  %b = call i32 @llvm.abs.i32(i32 %a, i1 false)
+  ret i32 %b
+}
+
+define <4 x i32> @abs_of_neg_vec(<4 x i32> %x) {
+; CHECK-LABEL: @abs_of_neg_vec(
+; CHECK-NEXT:    [[B:%.*]] = call <4 x i32> @llvm.abs.v4i32(<4 x i32> [[X:%.*]], i1 false)
+; CHECK-NEXT:    ret <4 x i32> [[B]]
+;
+  %a = sub nsw <4 x i32> zeroinitializer, %x
+  %b = call <4 x i32> @llvm.abs.v4i32(<4 x i32> %a, i1 false)
+  ret <4 x i32> %b
+}


        


More information about the llvm-commits mailing list