Implement C23 memalignment
Wilco Dijkstra
Wilco.Dijkstra@arm.com
Thu Oct 2 16:44:02 GMT 2025
Hi Paul,
> I agree that casts are error-prone. However, here the performance of
> memalignment is bad enough that some documentation would be helpful. (In
> Gnulib we never use memalignment, due to this performance hit.)
It's always going to be faster than a division...
> To check whether a pointer @var{P} has alignment @var{A},
> testing @code{(uintptr_t) @var{P} % @var{A}}
> suffices on all but theoretical platforms,
> and because the @code{%} is typically implemented via a simple bitmask
That is incorrect. I just removed very similar code from malloc where it did:
if ((((unsigned long) (m)) % alignment) != 0) /* misaligned */
This always uses a division.
> such a test is typically more efficient than
> comparing @code{memalignment (@var{P})} to @var{A}.
> To avoid errors due to overuse of casts,
> the test can be worded as @code{ptr2uint (@var{P}) % @var{A}}
> where @code{ptr2uint} is a trivial inlined function
> whose body contains the cast to @code{uintptr_t}.
I don't think we should ever recommend using '%' since it is too slow.
Writing it as p & (a - 1) would be better since that really does avoid division.
However I still don't see why we would need to document anything at all -
do we document the same for abs() and all other functions that if you switch
off compiler optimization, you might be better off expanding things by hand?
Cheers,
Wilco
More information about the Libc-alpha
mailing list