fold-const: Fix up -fsanitize=null in C++ [PR105729]
authorJakub Jelinek <jakub@redhat.com>
Fri, 27 May 2022 09:40:42 +0000 (11:40 +0200)
committerJakub Jelinek <jakub@redhat.com>
Mon, 30 May 2022 03:36:31 +0000 (05:36 +0200)
commit2f3ccb79ca859332915cb29a1c965a0f7be2408c
treeab1a064bf16978bd58d2d02e90fdb381974654a6
parent120d99a3ec3f13766e13b40e48b0614242447fea
fold-const: Fix up -fsanitize=null in C++ [PR105729]

The following testcase triggers a false positive UBSan binding a reference
to null diagnostics.
In the FE we instrument conversions from pointer to reference type
to diagnose at runtime if the operand of such a conversion is 0.
The problem is that a GENERIC folding folds
((const struct Bar *) ((const struct Foo *) this)->data) + (sizetype) range_check (x)
conversion to const struct Bar & by converting to that the first
operand of the POINTER_PLUS_EXPR.  But that changes when the -fsanitize=null
binding to reference runtime check occurs.  Without the optimization,
it is invoked on the result of the POINTER_PLUS_EXPR, and as range_check
call throws, that means it never triggers in the testcase.
With the optimization, it checks whether this->data is NULL and it is.

The following patch avoids that optimization during GENERIC folding when
-fsanitize=null is enabled and it is a cast from non-REFERENCE_TYPE to
REFERENCE_TYPE.

2022-05-27  Jakub Jelinek  <jakub@redhat.com>

PR sanitizer/105729
* fold-const.cc (fold_unary_loc): Don't optimize (X &) ((Y *) z + w)
to (X &) z + w if -fsanitize=null during GENERIC folding.

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

(cherry picked from commit e2f014fcefcd2ad56b31995329820bbd99072eae)
gcc/fold-const.cc
gcc/testsuite/g++.dg/ubsan/pr105729.C [new file with mode: 0644]