https://gcc.gnu.org/g:e548eb628c689e2836e570aef98b9547aff97a02

commit r17-4377-ge548eb628c689e2836e570aef98b9547aff97a02
Author: Andrea Pinski <[email protected]>
Date:   Fri Sep 11 13:32:39 2026 -0700

    match: x+umax(x,1) -> umax(x*2, 1) [PR127103]
    
    This adds a simplification for `x+umax(x,1)` to `umax(x*2, 1)` when `x*2`
    is known not to overflow. This shows up with std::vector::push_back
    after the patch which adds `x+minmax(a,b)` simplification; it is also
    a special case of that patch for `umax and 1`.  This gives a small
    code generation improvement with std::vector::push_back because we
    trade an add after the umax with a shift beforehand.
    
    Bootstrapped and tested on x86_64-linux-gnu.
    
            PR tree-optimization/127103
    
    gcc/ChangeLog:
    
            * match.pd (`x+umax(x,1)`): New pattern.
    
    gcc/testsuite/ChangeLog:
    
            * gcc.dg/tree-ssa/max1-plus-1.c: New test.
    
    Signed-off-by: Andrea Pinski <[email protected]>

Diff:
---
 gcc/match.pd                                | 12 ++++++++++++
 gcc/testsuite/gcc.dg/tree-ssa/max1-plus-1.c | 22 ++++++++++++++++++++++
 2 files changed, 34 insertions(+)

diff --git a/gcc/match.pd b/gcc/match.pd
index 4059ed787f05..82cf6ae0a3c6 100644
--- a/gcc/match.pd
+++ b/gcc/match.pd
@@ -522,6 +522,18 @@ DEFINE_INT_AND_FLOAT_ROUND_FN (RINT)
  (if (ANY_INTEGRAL_TYPE_P (type) && TYPE_OVERFLOW_UNDEFINED (type))
   (abs @0)))
 
+#if GIMPLE
+/* x + uMax(x, 1) -> uMax(x+x, 1)
+   if x+x is known not to wrap/overflow.  */
+(simplify
+ (plus:c @0 (max:s@2 @0 integer_onep@1))
+ (if (TYPE_UNSIGNED (type))
+  (with { int_range_max vr0; }
+   (if (gimple_match_range_of_expr (vr0, @0, @2)
+       && range_op_handler (PLUS_EXPR).overflow_free_p (vr0, vr0))
+    (max (plus @0 @0) @1)))))
+#endif
+
 /* X * 1, X / 1 -> X.  */
 (for op (mult trunc_div ceil_div floor_div round_div exact_div)
   (simplify
diff --git a/gcc/testsuite/gcc.dg/tree-ssa/max1-plus-1.c 
b/gcc/testsuite/gcc.dg/tree-ssa/max1-plus-1.c
new file mode 100644
index 000000000000..9fdf0a40cc48
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/tree-ssa/max1-plus-1.c
@@ -0,0 +1,22 @@
+/* { dg-do compile } */
+/* { dg-options "-O2 -fdump-tree-optimized-raw" } */
+/* x + uMax(x, 1) -> uMax(x+x, 1) */
+/* PR tree-optimization/127103 */
+
+__attribute__((always_inline))
+static inline unsigned
+max(unsigned a, unsigned b)
+{
+  if (a < b)
+    return b;
+  return a;
+}
+
+unsigned f1(unsigned a, unsigned t1)
+{
+  if (a > __INT_MAX__)
+    return 0;
+  return a + max(1, a);
+}
+
+/* { dg-final { scan-tree-dump "gimple_assign <mult_expr, _\[0-9\], 
a_\[0-9\].D., 2" "optimized" } } */

Reply via email to