When we try to CSE -x / y with x / y we have to avoid presenting
a negate as if it were in the IL to the match-and-simplify machinery.
Instead we have to check whether the negate is available literally
when negation may invoke UB.

Bootstrapped on x86_64-unknown-linux-gnu, testing in progress.

        PR tree-optimization/128672
        * tree-ssa-sccvn.cc (visit_nary_op): Check whether a negated
        operand of a division or multiplication is available, do not
        just attempt to build or simplify it, when the negation may
        cause UB.

        * gcc.dg/torture/pr128672.c: New testcase.
---
 gcc/testsuite/gcc.dg/torture/pr128672.c | 20 ++++++++++++++++++++
 gcc/tree-ssa-sccvn.cc                   | 18 +++++++++++++++---
 2 files changed, 35 insertions(+), 3 deletions(-)
 create mode 100644 gcc/testsuite/gcc.dg/torture/pr128672.c

diff --git a/gcc/testsuite/gcc.dg/torture/pr128672.c 
b/gcc/testsuite/gcc.dg/torture/pr128672.c
new file mode 100644
index 00000000000..91a3f878db5
--- /dev/null
+++ b/gcc/testsuite/gcc.dg/torture/pr128672.c
@@ -0,0 +1,20 @@
+/* { dg-do run } */
+/* { dg-require-effective-target int32plus } */
+
+static volatile unsigned X = 0x80000000;
+int g;
+
+void __attribute__((noipa))
+test (int y)
+{
+  if (y != -1073741824)
+    __builtin_abort ();
+}
+
+int main ()
+{ 
+  unsigned x = X;
+  g = (int)x / 2;
+  test ((int)-x / 2);
+  return 0;
+} 
diff --git a/gcc/tree-ssa-sccvn.cc b/gcc/tree-ssa-sccvn.cc
index 0dd5e7f5f0b..b6e894bd7e8 100644
--- a/gcc/tree-ssa-sccvn.cc
+++ b/gcc/tree-ssa-sccvn.cc
@@ -6038,9 +6038,21 @@ visit_nary_op (tree lhs, gassign *stmt)
            {
              unsigned j = i == 0 ? 1 : 0;
              tree ops[2];
-             gimple_match_op match_op (gimple_match_cond::UNCOND,
-                                       NEGATE_EXPR, type, rhs[i]);
-             ops[i] = vn_nary_build_or_lookup_1 (&match_op, false, true);
+             if (!ANY_INTEGRAL_TYPE_P (type)
+                 || TYPE_OVERFLOW_WRAPS (type))
+               {
+                 gimple_match_op match_op (gimple_match_cond::UNCOND,
+                                           NEGATE_EXPR, type, rhs[i]);
+                 ops[i] = vn_nary_build_or_lookup_1 (&match_op, false, true);
+               }
+             else
+               {
+                 ops[i] = vn_nary_op_lookup_pieces (1, NEGATE_EXPR, type,
+                                                    &rhs[i], NULL);
+                 /* Check we have the negate operation available.  */
+                 if (ops[i] && !vn_nary_result_avail_or_insertable_p (ops[i]))
+                   ops[i] = NULL_TREE;
+               }
              ops[j] = rhs[j];
              if (ops[i]
                  && (ops[0] = vn_nary_op_lookup_pieces (2, code,
-- 
2.51.0

Reply via email to