[libc-commits] [libc] [libc] implement `memalignment` (PR #132493)

via libc-commits libc-commits at lists.llvm.org
Fri Mar 21 16:40:09 PDT 2025


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-libc

Author: Mohamed Emad (hulxv)

<details>
<summary>Changes</summary>

This patch adds the `memalignment` function to LLVM-libc, following its description in [WG14 N3220, ยง7.24.2.1](https://www.open-std.org/jtc1/sc22/wg14/www/docs/n3220.pdf#page=387). 

Closes #<!-- -->132300

---
Full diff: https://github.com/llvm/llvm-project/pull/132493.diff


2 Files Affected:

- (added) libc/src/stdlib/memalignment.c (+19) 
- (added) libc/src/stdlib/memalignment.h (+22) 


``````````diff
diff --git a/libc/src/stdlib/memalignment.c b/libc/src/stdlib/memalignment.c
new file mode 100644
index 0000000000000..bf182f16ea138
--- /dev/null
+++ b/libc/src/stdlib/memalignment.c
@@ -0,0 +1,19 @@
+#include "src/stdlib/memalignment.h"
+#include "src/__support/macros/config.h"
+
+namespace LIBC_NAMESPACE_DECL {
+
+LLVM_LIBC_FUNCTION(size_t, memalignment, (const void *p)) {
+  if (p == NULL) {
+    return 0;
+  }
+
+  uintptr_t addr = (uintptr_t)p;
+
+  // Find the rightmost set bit, which represents the maximum alignment
+  // The alignment is a power of two, so we need to find the largest
+  // power of two that divides the address
+  return addr & (~addr + 1);
+}
+
+} // namespace LIBC_NAMESPACE_DECL
diff --git a/libc/src/stdlib/memalignment.h b/libc/src/stdlib/memalignment.h
new file mode 100644
index 0000000000000..8ed900122a153
--- /dev/null
+++ b/libc/src/stdlib/memalignment.h
@@ -0,0 +1,22 @@
+//===-- Implementation header for memalignment --------------------------*- C++ -*-===//
+//
+// 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
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_LIBC_SRC_STDLIB_MEM_ALIGNMENT_H
+#define LLVM_LIBC_SRC_STDLIB_MEM_ALIGNMENT_H
+
+#include "src/__support/macros/config.h"
+#include <stddef.h>
+
+namespace LIBC_NAMESPACE_DECL {
+
+size_t memalignment(const void* p);
+
+} // namespace LIBC_NAMESPACE_DECL
+
+#endif // LLVM_LIBC_SRC_STDLIB_LDIV_H
+

``````````

</details>


https://github.com/llvm/llvm-project/pull/132493


More information about the libc-commits mailing list