https://gcc.gnu.org/g:e1bd0f293d8407d4e8149fbafd470612323dc938

commit r14-9353-ge1bd0f293d8407d4e8149fbafd470612323dc938
Author: Jakub Jelinek <ja...@redhat.com>
Date:   Thu Mar 7 10:01:08 2024 +0100

    sccvn: Avoid UB in ao_ref_init_from_vn_reference [PR105533]
    
    When compiling libgcc or on e.g.
    int a[64];
    int p;
    
    void
    foo (void)
    {
      int s = 1;
      while (p)
        {
          s -= 11;
          a[s] != 0;
        }
    }
    sccvn invokes UB in the compiler as detected by ubsan:
    ../../gcc/poly-int.h:1089:5: runtime error: left shift of negative value -40
    The problem is that we still use C++11..C++17 as the implementation language
    and in those C++ versions shifting negative values left is UB (well defined
    since C++20) and above in
               offset += op->off << LOG2_BITS_PER_UNIT;
    op->off is poly_int64 with -40 value (in libgcc with -8).
    I understand the offset_int << LOG2_BITS_PER_UNIT shifts but it is then well
    defined during underlying implementation which is done on the uhwi limbs,
    but for poly_int64 we use
                    offset += pop->off * BITS_PER_UNIT;
    a few lines earlier and I think that is both more readable in what it
    actually does and triggers UB only if there would be signed multiply
    overflow.  In the end, the compiler will treat them the same at least at the
    RTL level (at least, if not and they aren't the same cost, it should).
    
    2024-03-07  Jakub Jelinek  <ja...@redhat.com>
    
            PR middle-end/105533
            * tree-ssa-sccvn.cc (ao_ref_init_from_vn_reference) <case 
ARRAY_REF>:
            Multiple op->off by BITS_PER_UNIT instead of shifting it left by
            LOG2_BITS_PER_UNIT.

Diff:
---
 gcc/tree-ssa-sccvn.cc | 2 +-
 1 file changed, 1 insertion(+), 1 deletion(-)

diff --git a/gcc/tree-ssa-sccvn.cc b/gcc/tree-ssa-sccvn.cc
index 88d3b2498b9..93649895056 100644
--- a/gcc/tree-ssa-sccvn.cc
+++ b/gcc/tree-ssa-sccvn.cc
@@ -1221,7 +1221,7 @@ ao_ref_init_from_vn_reference (ao_ref *ref,
          if (maybe_eq (op->off, -1))
            max_size = -1;
          else
-           offset += op->off << LOG2_BITS_PER_UNIT;
+           offset += op->off * BITS_PER_UNIT;
          break;
 
        case REALPART_EXPR:

Reply via email to