Expressions of the form "X + CST < Y + CST" where X and Y are of int type and CST is of unsigned type with only the MSB on can be simplified to "X < Y" because "X + 0x80000000" increases monotonically with X.
gcc/ * match.pd (X + C < Y + C -> X < Y, if C is 0x80000000): New simplification. gcc/testsuite/ * gcc.dg/pr94899.c: New test. --- gcc/match.pd | 18 ++++++++++++++++++ gcc/testsuite/gcc.dg/pr94899.c | 28 ++++++++++++++++++++++++++++ 2 files changed, 46 insertions(+) create mode 100644 gcc/testsuite/gcc.dg/pr94899.c
diff --git a/gcc/match.pd b/gcc/match.pd index b942cb2930a..49ac0c43f83 100644 --- a/gcc/match.pd +++ b/gcc/match.pd @@ -1975,6 +1975,24 @@ DEFINE_INT_AND_FLOAT_ROUND_FN (RINT) (if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (@0)) && TYPE_OVERFLOW_UNDEFINED (TREE_TYPE (@0))) (op @0 @1)))) + +/* As a special case, X + C < Y + C is the same as X < Y even with wrapping + overflow if X and Y are signed integers of the same size, and C is an + unsigned constant with all bits except MSB set to 0 and size >= that of + X/Y. */ +(for op (lt le ge gt) + (simplify + (op (plus:c (convert@0 @1) @4) (plus:c (convert@2 @3) @4)) + (if (CONSTANT_CLASS_P (@4) + && TYPE_UNSIGNED (TREE_TYPE (@4)) + && !TYPE_UNSIGNED (TREE_TYPE (@1)) + && !TYPE_UNSIGNED (TREE_TYPE (@3)) + && (TYPE_PRECISION (TREE_TYPE (@1)) == TYPE_PRECISION (TREE_TYPE (@3))) + && (TYPE_PRECISION (TREE_TYPE (@1)) <= TYPE_PRECISION (TREE_TYPE (@4))) + && wi::only_sign_bit_p (wi::to_wide (@4), + TYPE_PRECISION (TREE_TYPE (@0)))) + (op @1 @3)))) + /* For equality and subtraction, this is also true with wrapping overflow. */ (for op (eq ne minus) (simplify diff --git a/gcc/testsuite/gcc.dg/pr94899.c b/gcc/testsuite/gcc.dg/pr94899.c new file mode 100644 index 00000000000..304aaf3c6e6 --- /dev/null +++ b/gcc/testsuite/gcc.dg/pr94899.c @@ -0,0 +1,28 @@ +/* { dg-do compile } */ +/* { dg-options "-O2 -fdump-tree-original" } */ + +typedef __INT16_TYPE__ int16_t; +typedef __INT32_TYPE__ int32_t; + +#define MAGIC 0x80000000 + +int +f_i16_i16 (int16_t x, int16_t y) +{ + return x + MAGIC < y + MAGIC; +} + +int +f_i32_i32 (int32_t x, int32_t y) +{ + return x + MAGIC < y + MAGIC; +} + +int +f_i32_i32_sub (int32_t x, int32_t y) +{ + return x - MAGIC < y - MAGIC; +} + +/* The constants above should have been optimized away. */ +/* { dg-final { scan-tree-dump-times "2147483648" 0 "original"} } */ -- 2.31.1