This is the mail archive of the gcc@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]
Other format: [Raw text]

Re: [llvm-dev] GCC 5 and -Wstrict-aliasing in JSON.h


Hi LH_Mouse,

Thanks!

On Fri, Aug 10, 2018 at 6:30 AM, Liu Hao <lh_mouse@126.com> wrote:
>
> When I used to do such type punning in C, I got similar warnings. Then I
> looked for some solutions... I can't recall the principle now and I fail to
> find it in the C or C++ standard. Despite that, the solution is simple:
>
> Only an lvalue of a pointer to (possibly CV-qualified) `void` or a pointer
> to a character type (in C) / any of `char`, `unsigned char` or `std::byte`
> (in C++) can alias objects.
>
> That is to say, in order to eliminate the aliasing problem an intermediate
> lvalue pointer is required.
>
> Hence, altering
> ```
>     return *reinterpret_cast<T *>(Union.buffer);
> ```
> to
> ```
>     auto p = static_cast<void *>(Union.buffer);
>     return *static_cast<T *>(p);
> ```
> will probably resolve this problem.

I'm worried that this might only serve to trick the compiler.

Explicitly using `-fno-strict-aliasing` for GCC < 6 would seem more
direct to me -- as Jonathan says, if the compiler classifies a strict
aliasing rule violation as undefined behavior, and that is further
used to optimize in an unexpected manner, it doesn't matter whether it
warns or not. Then again, I guess disabling strict aliasing would also
disable optimizations that are generally useful for LLVM as a whole.

I'm reading up on safe aliasing techniques, but so far nothing stands
out to me as applicable in this scenario.

- Kim


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]