match.pd: Add pattern to fold (X - (X<0)) ^ -(X<0) into ABS_EXPR<X> [PR123514]

Message ID 20260408124847.1911596-1-eikansh.gupta@oss.qualcomm.com
State New
Headers
Series match.pd: Add pattern to fold (X - (X<0)) ^ -(X<0) into ABS_EXPR<X> [PR123514] |

Checks

Context Check Description
linaro-tcwg-bot/tcwg_gcc_build--master-aarch64 success Build passed
linaro-tcwg-bot/tcwg_gcc_build--master-arm success Build passed

Commit Message

Eikansh Gupta April 8, 2026, 12:48 p.m. UTC
  Adds a pattern to fold (x - (x<0)) ^ -(x<0) into ABS_EXPR<x>.

	PR 123514

gcc/ChangeLog:

	* match.pd (x - (x<0)) ^ -(x<0) into ABS_EXPR<x>): New pattern.

gcc/testsuite/ChangeLog:

	* gcc.dg/tree-ssa/pr123514.c: New test.

Signed-off-by: Eikansh Gupta <eikansh.gupta@oss.qualcomm.com>
---
 gcc/match.pd                             |  8 ++++++++
 gcc/testsuite/gcc.dg/tree-ssa/pr123514.c | 11 +++++++++++
 2 files changed, 19 insertions(+)
 create mode 100644 gcc/testsuite/gcc.dg/tree-ssa/pr123514.c
  

Patch

diff --git a/gcc/match.pd b/gcc/match.pd
index 7b652afb43d..211e5d99ae5 100644
--- a/gcc/match.pd
+++ b/gcc/match.pd
@@ -230,6 +230,14 @@  DEFINE_INT_AND_FLOAT_ROUND_FN (RINT)
   (abs @0)))
 #endif
 
+/* (X - (X < 0)) ^ -(X < 0) -> abs (X) */
+(simplify
+ (bit_xor:c (minus @0 (convert@1 (lt @0 integer_zerop)))
+	    (negate @1))
+ (if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (@0))
+      && !TYPE_UNSIGNED (TREE_TYPE (@0)))
+  (abs @0)))
+
 /* Simplifications of operations with one constant operand and
    simplifications to constants or single values.  */
 
diff --git a/gcc/testsuite/gcc.dg/tree-ssa/pr123514.c b/gcc/testsuite/gcc.dg/tree-ssa/pr123514.c
new file mode 100644
index 00000000000..4a09d859031
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/tree-ssa/pr123514.c
@@ -0,0 +1,11 @@ 
+/* { dg-do compile } */
+/* { dg-options "-O1 -fdump-tree-optimized" } */
+
+int
+bit_trick (int x)
+{
+  int mask = -(x < 0);
+  return ((x + mask) ^ mask);
+}
+
+/* { dg-final { scan-tree-dump "ABS_EXPR" "optimized" } } */