[PATCH] D122299: [InstCombine] Fix missing nsw flag when fold -(x-y) to y-x

chenglin.bi via Phabricator via llvm-commits llvm-commits at lists.llvm.org
Wed Mar 23 02:05:50 PDT 2022


bcl5980 created this revision.
bcl5980 added reviewers: spatel, RKSimon, nikic, craig.topper.
Herald added subscribers: StephenFan, lebedev.ri, hiraditya.
Herald added a reviewer: lebedev.ri.
Herald added a project: All.
bcl5980 requested review of this revision.
Herald added a project: LLVM.
Herald added a subscriber: llvm-commits.

Use CreateNSWSub instead of CreateSub when original sub has nsw flag


https://reviews.llvm.org/D122299

Files:
  llvm/lib/Transforms/InstCombine/InstCombineNegator.cpp
  llvm/test/Transforms/InstCombine/nsw.ll


Index: llvm/test/Transforms/InstCombine/nsw.ll
===================================================================
--- llvm/test/Transforms/InstCombine/nsw.ll
+++ llvm/test/Transforms/InstCombine/nsw.ll
@@ -140,3 +140,23 @@
   %t3 = mul <vscale x 2 x i64> %shuf, %xx
   ret <vscale x 2 x i64> %t3
 }
+
+define i32 @neg_sub_nsw(i32 %a, i32 %b) {
+; CHECK-LABEL: @neg_sub_nsw(
+; CHECK-NEXT:    [[C_NEG:%.*]] = sub nsw i32 [[B:%.*]], [[A:%.*]]
+; CHECK-NEXT:    ret i32 [[C_NEG]]
+;
+  %c = sub nsw i32 %a, %b
+  %d = sub i32 0, %c
+  ret i32 %d
+}
+
+define i32 @neg_sub(i32 %a, i32 %b) {
+; CHECK-LABEL: @neg_sub(
+; CHECK-NEXT:    [[C_NEG:%.*]] = sub i32 [[B:%.*]], [[A:%.*]]
+; CHECK-NEXT:    ret i32 [[C_NEG]]
+;
+  %c = sub i32 %a, %b
+  %d = sub i32 0, %c
+  ret i32 %d
+}
Index: llvm/lib/Transforms/InstCombine/InstCombineNegator.cpp
===================================================================
--- llvm/lib/Transforms/InstCombine/InstCombineNegator.cpp
+++ llvm/lib/Transforms/InstCombine/InstCombineNegator.cpp
@@ -238,6 +238,9 @@
     // `sub` is always negatible.
     // However, only do this either if the old `sub` doesn't stick around, or
     // it was subtracting from a constant. Otherwise, this isn't profitable.
+    if (I->hasNoSignedWrap())
+      return Builder.CreateNSWSub(I->getOperand(1), I->getOperand(0),
+                                  I->getName() + ".neg");
     return Builder.CreateSub(I->getOperand(1), I->getOperand(0),
                              I->getName() + ".neg");
   }


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D122299.417526.patch
Type: text/x-patch
Size: 1524 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/llvm-commits/attachments/20220323/6a032d0e/attachment.bin>


More information about the llvm-commits mailing list