[gcc r17-3173] match: 1 / X -> X == 1 for positive X. [PR125735]

Kael Andrew Franco via Gcc-cvs <[email protected]>
Newsgroups gmane.comp.gcc.cvs
Message-ID <[email protected]>
https://gcc.gnu.org/g:e8f4e91989f0b57463f1b726f94344ddbe2bb128

commit r17-3173-ge8f4e91989f0b57463f1b726f94344ddbe2bb128
Author: Kael Andrew Alonzo Franco <[email protected]>
Date:   Sun Aug 9 21:47:58 2026 -0400

    match: 1 / X -> X == 1 for positive X. [PR125735]
    
    TYPE_UNSIGNED (type) doesn't cover positive signed types
    so use tree_expr_nonnegative_p ().
    
    Bootstrapped and tested on x86_64-pc-linux-gnu.
    
            PR tree-optimization/125735
    
    gcc/ChangeLog:
    
            * match.pd: 1 / X -> X == 1 for positive X.
    
    gcc/testsuite/ChangeLog:
    
            * gcc.dg/pr125735.c: New test.
    
    Signed-off-by: Kael Andrew Franco <[email protected]>

Diff:
---
 gcc/match.pd                    |  7 ++++---
 gcc/testsuite/gcc.dg/pr125735.c | 11 +++++++++++
 2 files changed, 15 insertions(+), 3 deletions(-)

diff --git a/gcc/match.pd b/gcc/match.pd
index efaf0026711c..cccb607a622c 100644
--- a/gcc/match.pd
+++ b/gcc/match.pd
@@ -628,8 +628,8 @@ DEFINE_INT_AND_FLOAT_ROUND_FN (RINT)
        && TYPE_UNSIGNED (type))
    (trunc_divmod @0 @1))))
 
-/* 1 / X -> X == 1 for unsigned integer X.
-   1 / X -> X >= -1 && X <= 1 ? X : 0 for signed integer X.
+/* 1 / X -> X == 1 for positive integer X.
+   1 / X -> X >= -1 && X <= 1 ? X : 0 for when X could be negative.
    But not for 1 / 0 so that we can get proper warnings and errors,
    and not for 1-bit integers as they are edge cases better handled
    elsewhere.  Delay the conversion of the signed division until late
@@ -640,7 +640,8 @@ DEFINE_INT_AND_FLOAT_ROUND_FN (RINT)
       && TYPE_PRECISION (type) > 1
       && !integer_zerop (@1)
       && (!flag_non_call_exceptions || tree_expr_nonzero_p (@1)))
-  (if (TYPE_UNSIGNED (type))
+  (if (TYPE_UNSIGNED (type)
+       || tree_expr_nonnegative_p (@1))
    (convert (eq:boolean_type_node @1 @0))
    (if (fold_before_rtl_expansion_p ())
     (with { tree utype = unsigned_type_for (type); }
diff --git a/gcc/testsuite/gcc.dg/pr125735.c b/gcc/testsuite/gcc.dg/pr125735.c
new file mode 100644
index 000000000000..b94d95c0de76
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/pr125735.c
@@ -0,0 +1,11 @@
+/* { dg-do compile } */
+/* { dg-options "-O2 -fdump-tree-optimized" } */
+
+_Bool
+one_div_positive (int b)
+{
+  if (b < 1) return 0;
+  return (1 / b);
+}
+
+/* { dg-final { scan-tree-dump "b_\[0-9\]+.D. == 1" "optimized" } } */
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.