[Openmp-commits] [openmp] [OpenMP] Align up the size when calling aligned_alloc (PR #65525)

Shilei Tian via Openmp-commits openmp-commits at lists.llvm.org
Wed Sep 6 13:10:05 PDT 2023


https://github.com/shiltian created https://github.com/llvm/llvm-project/pull/65525:

Based on https://en.cppreference.com/w/c/memory/aligned_alloc, the `size` is supposed
to be a multiple of `alignment`, and it is implementation defined behavior if not.
We have a non-conformant use in `kmp_barrier.h` when allocating distribute barrier.
The size of the barrier is 576 and the alignment is `4*CACHE_LINE`, which is 64
on most systems. Apparently it works perfectly fine for Linux and Intel-based Mac,
but not for Apple Silicon based Mac.

Fix #63194.


>From 1154af3c3c2e3b7684b069c6e02e8a3ad35caf3b Mon Sep 17 00:00:00 2001
From: Shilei Tian <i at tianshilei.me>
Date: Wed, 6 Sep 2023 16:09:33 -0400
Subject: [PATCH] [OpenMP] Align up the size when calling aligned_alloc

Based on https://en.cppreference.com/w/c/memory/aligned_alloc, the `size` is supposed
to be a multiple of `alignment`, and it is implementation defined behavior if not.
We have a non-conformant use in `kmp_barrier.h` when allocating distribute barrier.
The size of the barrier is 576 and the alignment is `4*CACHE_LINE`, which is 64
on most systems. Apparently it works perfectly fine for Linux and Intel-based Mac,
but not for Apple Silicon based Mac.

Fix #63194.
---
 openmp/runtime/src/kmp_barrier.h | 5 ++++-
 1 file changed, 4 insertions(+), 1 deletion(-)

diff --git a/openmp/runtime/src/kmp_barrier.h b/openmp/runtime/src/kmp_barrier.h
index ac28a13217e9b4e..ae9b8d62f4c3dc5 100644
--- a/openmp/runtime/src/kmp_barrier.h
+++ b/openmp/runtime/src/kmp_barrier.h
@@ -21,7 +21,10 @@
 #define KMP_ALIGNED_ALLOCATE(size, alignment) _mm_malloc(size, alignment)
 #define KMP_ALIGNED_FREE(ptr) _mm_free(ptr)
 #elif KMP_HAVE_ALIGNED_ALLOC
-#define KMP_ALIGNED_ALLOCATE(size, alignment) aligned_alloc(alignment, size)
+#define KMP_ALGIN_UP(val, alignment)                                           \
+  (((val) + (alignment)-1) / (alignment) * (alignment))
+#define KMP_ALIGNED_ALLOCATE(size, alignment)                                  \
+  aligned_alloc(alignment, KMP_ALGIN_UP(size, alignment))
 #define KMP_ALIGNED_FREE(ptr) free(ptr)
 #elif KMP_HAVE_POSIX_MEMALIGN
 static inline void *KMP_ALIGNED_ALLOCATE(size_t size, size_t alignment) {



More information about the Openmp-commits mailing list