Skip to content

Commit f6e9679

Browse files
committed
[libc++] constexpr is_sufficiently_aligned
This is indended as support for filing a LWG issue. The implementation was suggested by Nikolas in https://github.com/llvm/llvm-project/pull/122603/files#r2035285951
1 parent 551d6dd commit f6e9679

File tree

2 files changed

+7
-6
lines changed

2 files changed

+7
-6
lines changed

libcxx/include/__memory/is_sufficiently_aligned.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@ _LIBCPP_BEGIN_NAMESPACE_STD
2323
#if _LIBCPP_STD_VER >= 26
2424

2525
template <size_t _Alignment, class _Tp>
26-
_LIBCPP_HIDE_FROM_ABI bool is_sufficiently_aligned(_Tp* __ptr) {
27-
return reinterpret_cast<uintptr_t>(__ptr) % _Alignment == 0;
26+
_LIBCPP_HIDE_FROM_ABI constexpr bool is_sufficiently_aligned(_Tp* __ptr) {
27+
return __builtin_constant_p(__builtin_assume_aligned(__ptr, _Alignment) != nullptr);
2828
}
2929

3030
#endif // _LIBCPP_STD_VER >= 26

libcxx/test/std/utilities/memory/ptr.align/is_sufficiently_aligned.pass.cpp

Lines changed: 5 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@
2121
#include "test_macros.h"
2222

2323
template <typename T>
24-
void test_is_sufficiently_aligned() {
24+
constexpr void test_is_sufficiently_aligned() {
2525
constexpr std::size_t N = alignof(T);
2626

2727
alignas(8 * N) std::remove_cv_t<T> buf[5];
@@ -54,7 +54,7 @@ void test_is_sufficiently_aligned() {
5454
}
5555

5656
template <typename T>
57-
void check(T* p) {
57+
constexpr void check(T* p) {
5858
ASSERT_SAME_TYPE(bool, decltype(std::is_sufficiently_aligned<alignof(T)>(p)));
5959
test_is_sufficiently_aligned<T>();
6060
test_is_sufficiently_aligned<const T>();
@@ -73,7 +73,7 @@ struct alignas(1) X {
7373
};
7474
static_assert(sizeof(X) == 2 * alignof(X));
7575

76-
bool tests() {
76+
constexpr bool test() {
7777
char c;
7878
int i;
7979
long l;
@@ -107,7 +107,8 @@ bool tests() {
107107
}
108108

109109
int main(int, char**) {
110-
tests();
110+
test();
111+
static_assert(test());
111112

112113
return 0;
113114
}

0 commit comments

Comments
 (0)