[PATCH v3] Implement C23 memalignment

Paul Eggert eggert@cs.ucla.edu
Thu Oct 16 16:11:10 GMT 2025


On 2025-10-15 23:37, Florian Weimer wrote:

>> +In general, performance does not improve if different code is used for
>> +aligned and unaligned pointers.  For example, if you want to read an
>> +@code{int} at the pointer @code{p}, use this code:
>> +
>> +@smallexample
>> +int i;
>> +memcpy (&i, p, sizeof (i));
>> +@end smallexample
>> +
>> +And then use the value in the variable @code{i}.  The compiler will
>> +generate the most effecient way to access unaligned data for the
>> +architecture, optimizing away the @code{memcpy} call.
>> +@end deftypefun
> 
> Paul, what's your take on this performance advice?

The advice is confusing, because its relevance to memalignment is 
unclear. The example should be enlarged to be two examples: the first 
calls memalignment in a poorly-designed way, and the second is a better 
way to do things.

More importantly, the advice doesn't address the question "What is 
mealignment for? Why would someone want to use it?" The manual should 
explain this.

(One nit: "efficient" is misspelled.)


I suggest replacing the above text with the following. If the examples 
seem too long, then use just the first paragraph:

-----

This function was added to the C23 standard to support unconventional
platforms where a pointer's low-order bits are unrelated to alignment.
For conventional platforms, one can instead cast the pointer to
@code{uintptr_t} and then test the low order bits:
this is portable to pre-C23 and is typically a bit faster.

For example, if you want to read an @code{int}
addressed by possibly-misaligned pointer @code{p},
the following pre-C23 code works on all conventional platforms:

@smallexample
int i;
if (((uintptr_t) p & (alignof (int) - 1)) != 0)
   memcpy (&i, p, sizeof i);
else
   i = *p;
@end smallexample

However, it might not work on unconventional platforms, where one
would need something like the following C23 code:

@smallexample
int i;
if (memalignment (p) < alignof (int))
   memcpy (&i, p, sizeof i);
else
   i = *p;
@end smallexample

However, for this particular case, performance does not improve if
different code is used for aligned and unaligned pointers,
and the following code is preferable:

@smallexample
int i;
memcpy (&i, p, sizeof i);
@end smallexample

The compiler will generate the most efficient way to access unaligned
data for the architecture, optimizing away the @code{memcpy} call.
@end deftypefun



More information about the Libc-alpha mailing list