[cfe-dev] Questions/discussions about cast types in clang

Arthur O'Dwyer via cfe-dev cfe-dev at lists.llvm.org
Sat Jun 20 13:22:40 PDT 2020


On Sat, Jun 20, 2020 at 3:31 PM Ray Zhang via cfe-dev <
cfe-dev at lists.llvm.org> wrote:

> Hi all,
>
> I'm currently implementing a clang tool to replace C style casts to C++
> style casts, i.e. const/static/reinterpret_casts. I'm almost done, but I've
> ran into a collection of issues/questions that I'd like to raise here to
> make sure it's not a misunderstanding on my part. My solutions are included
> in each bullet point:
>
> 1. (Question) For dependent types, it is unknown whether static_cast or
> reinterpret_cast is appropriate for the situation, so I would like to leave
> that as a C-style cast in the refactor tool. Example below:
>
> template <typename T> void foo() { int* ptr; (T*) ptr; }
> If we call foo<int>, it can be a const_cast, but if we call foo<double>,
> it has to be a reinterpret_cast.
>

It could even involve both a const_cast and a static_cast; or it could be
unrepresentable as a non-C-style cast (e.g. a cast to a private base).


> In a situation where the user is writing library code, it won't only be
> relevant to the current translation unit but also for future purposes.
> Therefore, I propose that we leave dependent type c-style casts as they are.
>

Sounds reasonable. Although, it would be nice to flag such casts for human
inspection somehow; see my very informal proposal here
<https://quuxplusone.github.io/blog/2020/01/22/expression-list-in-functional-cast/#it-would-be-useful-for-clang-or>
for example.


>
> 2. (Issue/bug) In OperationKinds.def, there is an enum detailing casting
> to union types. This doesn't work in clang(nor GCC). Here's a compiler
> explorer MVCE: https://godbolt.org/z/rp8DDt. The first statement is *not
> a cast*, but rather a CompoundLiteralExpr(InitListExpr(...)), and should
> not be treated as a cast. Here is the corresponding GCC document:
> https://gcc.gnu.org/onlinedocs/gcc/Cast-to-Union.html about union casts.
> If CastKind::CK_ToUnion is ever encountered in my program, I will leave the
> C-style cast as is.
>

It works in GCC trunk for me... but only in C++20 mode.
https://godbolt.org/z/Qjpxga
I suspect that your analysis is still correct: this feature is documented,
but does not work, in GCC pre-C++20, and then in C++20 the changes around
parens-initialization of aggregates broke it in such a way that now it *appears
*to work but nobody should trust it to *actually *work. It might be nice to
submit a patch ripping this broken stuff out of Clang and/or out of GCC.

my $.02,
–Arthur
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20200620/b7be3194/attachment.html>


More information about the cfe-dev mailing list