aboutsummaryrefslogtreecommitdiff
path: root/gcc/fold-const.c
diff options
context:
space:
mode:
authorJakub Jelinek <jakub@redhat.com>2020-06-24 10:40:02 +0200
committerJakub Jelinek <jakub@redhat.com>2020-06-24 10:41:04 +0200
commit01e10b0ee77e82cb331414c569e02dc7a2c4999e (patch)
tree4fd662b22fa60263df1fe1b0596242a88aa0655d /gcc/fold-const.c
parentf0008858dec9b16da153b948834abb20b9f1ab32 (diff)
downloadgcc-01e10b0ee77e82cb331414c569e02dc7a2c4999e.zip
gcc-01e10b0ee77e82cb331414c569e02dc7a2c4999e.tar.gz
gcc-01e10b0ee77e82cb331414c569e02dc7a2c4999e.tar.bz2
fold-const: Fix A <= 0 ? A : -A folding [PR95810]
We folded A <= 0 ? A : -A into -ABS (A), which is for signed integral types incorrect - can invoke on INT_MIN UB twice, once on ABS and once on its negation. The following patch fixes it by instead folding it to (type)-ABSU (A). 2020-06-24 Jakub Jelinek <jakub@redhat.com> PR middle-end/95810 * fold-const.c (fold_cond_expr_with_comparison): Optimize A <= 0 ? A : -A into (type)-absu(A) rather than -abs(A). * gcc.dg/ubsan/pr95810.c: New test.
Diffstat (limited to 'gcc/fold-const.c')
-rw-r--r--gcc/fold-const.c18
1 files changed, 16 insertions, 2 deletions
diff --git a/gcc/fold-const.c b/gcc/fold-const.c
index 212d0ba..67a379f 100644
--- a/gcc/fold-const.c
+++ b/gcc/fold-const.c
@@ -5770,8 +5770,22 @@ fold_cond_expr_with_comparison (location_t loc, tree type,
case LT_EXPR:
if (TYPE_UNSIGNED (TREE_TYPE (arg1)))
break;
- tem = fold_build1_loc (loc, ABS_EXPR, TREE_TYPE (arg1), arg1);
- return negate_expr (fold_convert_loc (loc, type, tem));
+ if (ANY_INTEGRAL_TYPE_P (TREE_TYPE (arg1))
+ && !TYPE_OVERFLOW_WRAPS (TREE_TYPE (arg1)))
+ {
+ /* A <= 0 ? A : -A for A INT_MIN is valid, but -abs(INT_MIN)
+ is not, invokes UB both in abs and in the negation of it.
+ So, use ABSU_EXPR instead. */
+ tree utype = unsigned_type_for (TREE_TYPE (arg1));
+ tem = fold_build1_loc (loc, ABSU_EXPR, utype, arg1);
+ tem = negate_expr (tem);
+ return fold_convert_loc (loc, type, tem);
+ }
+ else
+ {
+ tem = fold_build1_loc (loc, ABS_EXPR, TREE_TYPE (arg1), arg1);
+ return negate_expr (fold_convert_loc (loc, type, tem));
+ }
default:
gcc_assert (TREE_CODE_CLASS (comp_code) == tcc_comparison);
break;