[llvm] [InstCombine] Infer nuw flags for `C-(X+C2)` -> `(C-C2)-X` (PR #72373)

Yingwei Zheng via llvm-commits llvm-commits at lists.llvm.org
Wed Nov 15 03:44:19 PST 2023


https://github.com/dtcxzyw created https://github.com/llvm/llvm-project/pull/72373

This patch improves https://reviews.llvm.org/D152068 by inferring NUW flags for sub insts.
It is worth noting that we don't need to check overflow for `C-C2`.
Alive2: https://alive2.llvm.org/ce/z/uutGpS

This missed optimization is discovered with the help of https://github.com/AliveToolkit/alive2/pull/962.


>From 0fa1a86ad0dc9312f20e674e727d7cfcb8d8b8e3 Mon Sep 17 00:00:00 2001
From: Yingwei Zheng <dtcxzyw2333 at gmail.com>
Date: Wed, 15 Nov 2023 19:36:21 +0800
Subject: [PATCH] [InstCombine] Infer nuw flags for `C-(X+C2)` -> `(C-C2)-X`

---
 llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp       | 6 ++++--
 llvm/test/Transforms/InstCombine/addsub-constant-folding.ll | 2 +-
 2 files changed, 5 insertions(+), 3 deletions(-)

diff --git a/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp b/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
index 2bd738c95ecaa7f..318992b55e4f9f8 100644
--- a/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
+++ b/llvm/lib/Transforms/InstCombine/InstCombineAddSub.cpp
@@ -2111,14 +2111,16 @@ Instruction *InstCombinerImpl::visitSub(BinaryOperator &I) {
 
     // C-(X+C2) --> (C-C2)-X
     if (match(Op1, m_Add(m_Value(X), m_ImmConstant(C2)))) {
-      // C-C2 never overflow, and C-(X+C2), (X+C2) has NSW
-      // => (C-C2)-X can have NSW
+      // C-C2 never overflow, and C-(X+C2), (X+C2) has NSW/NUW
+      // => (C-C2)-X can have NSW/NUW
       bool WillNotSOV = willNotOverflowSignedSub(C, C2, I);
       BinaryOperator *Res =
           BinaryOperator::CreateSub(ConstantExpr::getSub(C, C2), X);
       auto *OBO1 = cast<OverflowingBinaryOperator>(Op1);
       Res->setHasNoSignedWrap(I.hasNoSignedWrap() && OBO1->hasNoSignedWrap() &&
                               WillNotSOV);
+      Res->setHasNoUnsignedWrap(I.hasNoUnsignedWrap() &&
+                                OBO1->hasNoUnsignedWrap());
       return Res;
     }
   }
diff --git a/llvm/test/Transforms/InstCombine/addsub-constant-folding.ll b/llvm/test/Transforms/InstCombine/addsub-constant-folding.ll
index 83a45e697e59e16..3a297880b794963 100644
--- a/llvm/test/Transforms/InstCombine/addsub-constant-folding.ll
+++ b/llvm/test/Transforms/InstCombine/addsub-constant-folding.ll
@@ -175,7 +175,7 @@ define i8 @add_nsw_const_const_sub_nsw_ov(i8 %arg) {
 
 define i8 @add_nuw_const_const_sub_nuw(i8 %arg) {
 ; CHECK-LABEL: @add_nuw_const_const_sub_nuw(
-; CHECK-NEXT:    [[T1:%.*]] = sub i8 -128, [[ARG:%.*]]
+; CHECK-NEXT:    [[T1:%.*]] = sub nuw i8 -128, [[ARG:%.*]]
 ; CHECK-NEXT:    ret i8 [[T1]]
 ;
   %t0 = add nuw i8 %arg, 1



More information about the llvm-commits mailing list