[libc-commits] [libc] [libc] implement `memalignment` (PR #132493)
Joseph Huber via libc-commits
libc-commits at lists.llvm.org
Sat Mar 22 18:54:57 PDT 2025
================
@@ -0,0 +1,68 @@
+//===-- Unittests for memalignment ---------------------------------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+
+#include "src/stdlib/free.h"
+#include "src/stdlib/malloc.h"
+#include "src/stdlib/memalignment.h"
+#include "test/UnitTest/Test.h"
+
+#include <stdint.h>
+
+TEST(LlvmLibcMemAlignmentTest, NullPointer) {
+ void *ptr = nullptr;
+ EXPECT_EQ(LIBC_NAMESPACE::memalignment(ptr), static_cast<size_t>(0));
+}
+
+TEST(LlvmLibcMemAlignmentTest, MallocedPointers) {
+ int *int_ptr = reinterpret_cast<int *>(LIBC_NAMESPACE::malloc(sizeof(int)));
+ EXPECT_NE(reinterpret_cast<void *>(int_ptr), static_cast<void *>(nullptr));
+
+ size_t int_alignment = LIBC_NAMESPACE::memalignment(int_ptr);
+ EXPECT_GE(int_alignment, alignof(int));
+
+ LIBC_NAMESPACE::free(int_ptr);
+
+ // Allocate a double (typically 8-byte aligned)
+ double *double_ptr =
+ reinterpret_cast<double *>(LIBC_NAMESPACE::malloc(sizeof(double)));
+ EXPECT_NE(reinterpret_cast<void *>(double_ptr), static_cast<void *>(nullptr));
+
+ size_t double_alignment = LIBC_NAMESPACE::memalignment(double_ptr);
+ EXPECT_GE(double_alignment, alignof(double));
+
+ EXPECT_EQ(double_alignment & (double_alignment - 1), static_cast<size_t>(0));
+
+ LIBC_NAMESPACE::free(double_ptr);
+}
+
+TEST(LlvmLibcMemAlignmentTest, SpecificAlignment) {
+
----------------
jhuber6 wrote:
Something fun you could add is a test like
```
alignas(256) static int x;
EXPECT_GE(memalignment(&x), 256);
```
https://github.com/llvm/llvm-project/pull/132493
More information about the libc-commits
mailing list