Hi!

When we have (intptr_t) x == cst where x has REFERENCE_TYPE, this
optimization creates x == cst out of it where cst has REFERENCE_TYPE.
If it is done in GENERIC folding, it can results in ubsan failures
where the INTEGER_CST with REFERENCE_TYPE is instrumented.

Fixed by deferring it to GIMPLE folding in this case.

Bootstrapped/regtested on x86_64-linux and i686-linux, ok for trunk?

2021-06-29  Jakub Jelinek  <ja...@redhat.com>

        PR c++/101210
        * match.pd ((intptr_t)x eq/ne CST to x eq/ne (typeof x) CST): Don't
        perform the optimization in GENERIC when sanitizing and x has a
        reference type.

        * g++.dg/ubsan/pr101210.C: New test.

--- gcc/match.pd.jj     2021-06-14 12:27:18.605410685 +0200
+++ gcc/match.pd        2021-06-28 10:08:22.535038549 +0200
@@ -5124,7 +5124,12 @@ (define_operator_list COND_TERNARY
   (cmp (convert @0) INTEGER_CST@1)
   (if (((POINTER_TYPE_P (TREE_TYPE (@0))
         && !FUNC_OR_METHOD_TYPE_P (TREE_TYPE (TREE_TYPE (@0)))
-        && INTEGRAL_TYPE_P (TREE_TYPE (@1)))
+        && INTEGRAL_TYPE_P (TREE_TYPE (@1))
+        /* Don't perform this optimization in GENERIC if @0 has reference
+           type when sanitizing.  See PR101210.  */
+        && !(GENERIC
+             && TREE_CODE (TREE_TYPE (@0)) == REFERENCE_TYPE
+             && (flag_sanitize & (SANITIZE_NULL | SANITIZE_ALIGNMENT))))
        || (INTEGRAL_TYPE_P (TREE_TYPE (@0))
            && POINTER_TYPE_P (TREE_TYPE (@1))
            && !FUNC_OR_METHOD_TYPE_P (TREE_TYPE (TREE_TYPE (@1)))))
--- gcc/testsuite/g++.dg/ubsan/pr101210.C.jj    2021-06-28 10:08:37.773825299 
+0200
+++ gcc/testsuite/g++.dg/ubsan/pr101210.C       2021-06-28 10:06:10.647884171 
+0200
@@ -0,0 +1,13 @@
+// PR c++/101210
+// { dg-do run }
+// { dg-options "-fsanitize=null,alignment 
-fno-sanitize-recover=null,alignment" }
+
+int v[2];
+int
+main ()
+{
+  int x;
+  int &y = x;
+  v[0] = reinterpret_cast<__INTPTR_TYPE__>(&y) == 0;
+  v[1] = reinterpret_cast<__INTPTR_TYPE__>(&y) == 1;
+}

        Jakub

Reply via email to