[PATCH] D118804: Revert "[Clang] Propagate guaranteed alignment for malloc and others"

Richard Smith - zygoloid via Phabricator via cfe-commits cfe-commits at lists.llvm.org
Mon Feb 7 14:01:21 PST 2022

rsmith added a comment.

I support this revert.

`malloc`, `operator new`, and `operator new[]` (by the latter two I mean the usual global allocation functions, not user-provided ones) follow these rules:

- `malloc` always returns storage whose alignment is at least the largest fundamental alignment. This allows, for example, `T *p = (T*)malloc(n * sizeof(T) + 1);` for any non-overaligned type `T`, even when `n` is zero. (The actual alignment might depend on the allocation size, but can never be less than `max(_Alignof(long double), _Alignof(long long))`, even if the allocation size is lower. We could easily add an alignment assumption stating that fact if we so chose.)
- `operator new(n)` always returns storage whose alignment is sufficient for any type `T` with `sizeof(T) == n && alignof(T) <= __STDCPP_DEFAULT_NEW_ALIGNMENT__`. For example, `operator new(n)` for any odd size `n` is always permitted to return 1-byte aligned storage. This makes sense because `operator new` is expected to power (only) `new T`.
- `operator new[](n)` always returns storage whose alignment is sufficient for any type `T` with `sizeof(T) <= n && alignof(T) <= __STDCPP_DEFAULT_NEW_ALIGNMENT__`. This is necessary to support things like `new std::byte[n]` followed by putting objects into that storage. However, unlike the `malloc` rules, this doesn't support zero-sized arrays in general.

Note that these are three different rules and we should not confuse them. The `malloc` rules have nothing to do with the default new alignment.

One possible and intended use of the C++ new alignment rules is to set the default new alignment to *less* than that guaranteed by `malloc`. For example, using `-fnew-alignment=1` can be used to pass alignment information into the allocator whenever possible, which may result in more efficient code generation. This flag and its effect on `operator new` are entirely unrelated to the behavior of `malloc`, and should not reduce the alignment that is assumed to be provided by `malloc`.

Providing information to LLVM about the expected alignment of memory returned by `malloc` -- if we have that information and LLVM does not -- seems like a good thing, but this is not the way to do it. Adding a separate, target-specific notion of malloc alignment, and using that as the default for the new alignment, might be reasonable.

  rG LLVM Github Monorepo



More information about the cfe-commits mailing list