[libc-commits] [libc] [libc] implement `memalignment` (PR #132493)
Mohamed Emad via libc-commits
libc-commits at lists.llvm.org
Fri Mar 21 16:39:30 PDT 2025
https://github.com/hulxv created https://github.com/llvm/llvm-project/pull/132493
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
>From 152894ee1076d18efed7730bed774e0f2b5aa9f9 Mon Sep 17 00:00:00 2001
From: hulxv <hulxxv at gmail.com>
Date: Sat, 22 Mar 2025 01:33:30 +0200
Subject: [PATCH] [libc] implement `memalignment`
---
libc/src/stdlib/memalignment.c | 19 +++++++++++++++++++
libc/src/stdlib/memalignment.h | 22 ++++++++++++++++++++++
2 files changed, 41 insertions(+)
create mode 100644 libc/src/stdlib/memalignment.c
create mode 100644 libc/src/stdlib/memalignment.h
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
+
More information about the libc-commits
mailing list