https://gcc.gnu.org/bugzilla/show_bug.cgi?id=115658

--- Comment #3 from Tom Honermann <tom at honermann dot net> ---
In retrospect, I think I misunderstood Andrew's motivation for filing this
issue.

There is a difference of behavior between gcc and clang with regard to aliasing
of `char16_t` and `char32_t` with respect to other types. This is illustrated
by the following example as demonstrated at
https://www.godbolt.org/z/PsMsPMa73.

Please note that (at least) `-O2` is necessary to reliably demonstrate
differences in behavior. Additionally, the use of `-fshort-wchar` to influence
the size of `wchar_t` affects behavior.

```
template<typename T, typename U>
U f(T *p, U *q) {
  *p = 1;
  U u = *q;
  *p = 2;
  return u;
}
template wchar_t f(char16_t*, wchar_t*);
template unsigned short f(char16_t*, unsigned short*);
template wchar_t f(char32_t*, wchar_t*);
template unsigned int f(char32_t*, unsigned int*);
```

The test case exercises dead store elimination in the presence of aliasing
types. If `T` may alias `U`, then the write of `1` to `*p` is observable by
`*q`, but may otherwise be eliminated due to the later write of `2` to `*p`.

For Clang, there is no aliasing between any of these types and the store of `1`
to `*p` is always eliminated.

For MSVC, it appears that either dead store elimination is not performed at
all, or aliasing is permitted across all of these types (even when the size
differs).

For gcc with `-fshort-wchar`, there appear to be two alias sets:
- `wchar_t`, `char16_t`, and `unsigned short`.
- `char32_t` and `unsigned int`.

For gcc without `-fshort-wchar`, there are also two alias sets, but they are
not symmetric in the presence of that option. Note that `char32_t` never
aliases with `wchar_t` even when they have the same size. This asymmetry is
explainable in consideration of compatibility with MSVC (where `wchar_t` is
always 16-bit).
- `char16_t` and `unsigned short`.
- `char32_t` and `unsigned int`.

Adding the following explicit template instantiations demonstrates that all of
gcc, clang, and MSVC permit aliasing between the set of `char`, `unsigned
char`, and `char8_t` (because `char` and `unsigned char` are permitted to alias
all types). https://www.godbolt.org/z/Pjxb661Y7.

```
template char f(char8_t*, char*);
template unsigned char f(char8_t*, unsigned char*);
```

To reiterate, I think the current gcc behavior is correct and defensible given
two goals:
- A desire to match MSVC behavior in the limited context of a 16-bit `wchar_t`
type.
- A desire to match C behavior with respect to `char16_t` and `char32_t`
aliasing the underlying types of `uint_least16_t` and `uint_least32_t` (the
former are typedefs in C).

Reply via email to