[llvm] [InstCombine] Simplify `add nsw/nuw i1` to `or disjoint i1` (PR #118221)

Pedro Lobo via llvm-commits llvm-commits at lists.llvm.org
Sun Dec 1 09:22:49 PST 2024


https://github.com/pedroclobo created https://github.com/llvm/llvm-project/pull/118221

Optimize `add nsw i1`/`add nuw i1` to `or disjoint i1`.

Alive2: [nsw](https://alive2.llvm.org/ce/z/e8SDhV), [nuw](https://alive2.llvm.org/ce/z/dtE6ZL)

Closes #118164.

>From c495dbb3509fa121afa7553a12728635a2ce4000 Mon Sep 17 00:00:00 2001
From: Pedro Lobo <pedro.lobo at tecnico.ulisboa.pt>
Date: Sun, 1 Dec 2024 17:14:06 +0000
Subject: [PATCH] [InstCombine] Simplify `add nsw/nuw i1` to `or disjoint i1`

---
 .../InstCombine/InstCombineAddSub.cpp          |  5 ++++-
 llvm/test/Transforms/InstCombine/add2.ll       | 18 ++++++++++++++++++
 2 files changed, 22 insertions(+), 1 deletion(-)

diff --git a/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp b/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
index 63725e4ca8113e..1323958a2b4242 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
@@ -1549,8 +1549,11 @@ Instruction *InstCombinerImpl::visitAdd(BinaryOperator &I) {
                                               I.hasNoUnsignedWrap()))
     return R;
   Type *Ty = I.getType();
-  if (Ty->isIntOrIntVectorTy(1))
+  if (Ty->isIntOrIntVectorTy(1)) {
+    if (I.hasNoUnsignedWrap() || I.hasNoSignedWrap())
+      return BinaryOperator::CreateDisjoint(Instruction::Or, LHS, RHS);
     return BinaryOperator::CreateXor(LHS, RHS);
+  }
 
   // X + X --> X << 1
   if (LHS == RHS) {
diff --git a/llvm/test/Transforms/InstCombine/add2.ll b/llvm/test/Transforms/InstCombine/add2.ll
index ae80ab2e92ad15..7107a8443a2edd 100644
--- a/llvm/test/Transforms/InstCombine/add2.ll
+++ b/llvm/test/Transforms/InstCombine/add2.ll
@@ -498,3 +498,21 @@ define i32 @sub_undemanded_low_bits(i32 %x) {
   %shr = lshr i32 %sub, 4
   ret i32 %shr
 }
+
+define i1 @add_nuw_i1(i1 %x, i1 %y) {
+; CHECK-LABEL: @add_nuw_i1(
+; CHECK-NEXT:    [[Z:%.*]] = or disjoint i1 [[X:%.*]], [[Y:%.*]]
+; CHECK-NEXT:    ret i1 [[Z]]
+;
+  %z = add nuw i1 %x, %y
+  ret i1 %z
+}
+
+define i1 @add_nsw_i1(i1 %x, i1 %y) {
+; CHECK-LABEL: @add_nsw_i1(
+; CHECK-NEXT:    [[Z:%.*]] = or disjoint i1 [[X:%.*]], [[Y:%.*]]
+; CHECK-NEXT:    ret i1 [[Z]]
+;
+  %z = add nsw i1 %x, %y
+  ret i1 %z
+}



More information about the llvm-commits mailing list