Re: [PATCH] c++, v2: Reject UB in static_cast downcasts during constant evaluation

Jason Merrill <[email protected]>
Newsgroups gmane.comp.gcc.patches
Message-ID <[email protected]>
On 7/27/26 5:02 PM, Jakub Jelinek wrote:
> On Fri, Jul 24, 2026 at 02:02:25PM -0400, Jason Merrill wrote:
>> Hmm, yes, because e.g. in constexpr-base2a.C the A subobject is at a
>> non-zero offset so there isn't a B at that address.
>>
>> This seems to indicate that we're representing the conversion badly.
>>
>> This is because the cp_fold_convert in build_static_cast_1 turns
>> NOP_EXPR (B&, NOP_EXPR (B*, POINTER_PLUS_EXPR (NOP_EXPR (A*, a), -4)))
>> into
>> POINTER_PLUS_EXPR (NOP_EXPR (B&, a), -4)
>> so the NOP_EXPR is now an invalid downcast that the patch diagnoses.
> 
> Here is an updated patch, which
> 1) has slightly different wording mostly as you suggested,
>     I have just used the pointed or referenced type rather than a pointer
>     (what would be printed in the reference case anyway?)
> 2) in cp_fold_convert I've stopped using fold_convert for the
>     INDIRECT_TYPE_P to INDIRECT_TYPE_P casts so that we avoid the
>     Convert (T1)(X p+ Y) into ((T1)X p+ Y), for pointer type, when ...
>     problematic fold-const.cc optimization, instead it optimizes just
>     some simple cases
> 3) had to move -fsanitize=null checking for references on nullptr in order
>     not to regress one ubsan testcase
> 
> Bootstrapped successfull on both x86_64-linux and i686-linux, but has one
> regression on both:
> FAIL: std/ranges/adaptors/slide/1.cc  -std=gnu++23 (test for excess errors)
> Excess errors:
> /home/jakub/src/gcc/libstdc++-v3/testsuite/std/ranges/adaptors/slide/1.cc:110: error: non-constant condition for static assertion
> /home/jakub/src/gcc/obj74/x86_64-pc-linux-gnu/libstdc++-v3/include/bits/ranges_base.h:1016: error: '(((((int*)(& x)) + 12) - (((int*)(& x)) + 4)) / 4)' is not a constant expression
> and ditto with -std=gnu++29.  I'm afraid something relies on
> some of the fold_convert optimizations, dunno if we should try harder
> during POINTER_DIFF_EXPR folding or what.
What if we disable the fold_unary_loc transformation if the pointers are 
to different RECORD_TYPEs?  There are already a couple other exceptions.

Jason
lmpx.com only provides a reader for public news (NNTP) servers. It is not affiliated with the servers or forums shown here and is not responsible for the content of articles, which is written by their respective authors.