Back to home page

EIC code displayed by LXR

 
 

    


File indexing completed on 2026-05-03 08:13:55

0001 //===----------------------------------------------------------------------===//
0002 //
0003 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
0004 // See https://llvm.org/LICENSE.txt for license information.
0005 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
0006 //
0007 //===----------------------------------------------------------------------===//
0008 
0009 #ifndef _LIBCPP___MEMORY_ALIGNED_ALLOC_H
0010 #define _LIBCPP___MEMORY_ALIGNED_ALLOC_H
0011 
0012 #include <__config>
0013 #include <cstdlib>
0014 
0015 #if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)
0016 #  pragma GCC system_header
0017 #endif
0018 
0019 _LIBCPP_BEGIN_NAMESPACE_STD
0020 
0021 #if _LIBCPP_HAS_LIBRARY_ALIGNED_ALLOCATION
0022 
0023 // Low-level helpers to call the aligned allocation and deallocation functions
0024 // on the target platform. This is used to implement libc++'s own memory
0025 // allocation routines -- if you need to allocate memory inside the library,
0026 // chances are that you want to use `__libcpp_allocate` instead.
0027 //
0028 // Returns the allocated memory, or `nullptr` on failure.
0029 inline _LIBCPP_HIDE_FROM_ABI void* __libcpp_aligned_alloc(std::size_t __alignment, std::size_t __size) {
0030 #  if defined(_LIBCPP_MSVCRT_LIKE)
0031   return ::_aligned_malloc(__size, __alignment);
0032 #  elif _LIBCPP_STD_VER >= 17 && _LIBCPP_HAS_C11_ALIGNED_ALLOC
0033   // aligned_alloc() requires that __size is a multiple of __alignment,
0034   // but for C++ [new.delete.general], only states "if the value of an
0035   // alignment argument passed to any of these functions is not a valid
0036   // alignment value, the behavior is undefined".
0037   // To handle calls such as ::operator new(1, std::align_val_t(128)), we
0038   // round __size up to the next multiple of __alignment.
0039   size_t __rounded_size = (__size + __alignment - 1) & ~(__alignment - 1);
0040   // Rounding up could have wrapped around to zero, so we have to add another
0041   // max() ternary to the actual call site to avoid succeeded in that case.
0042   return ::aligned_alloc(__alignment, __size > __rounded_size ? __size : __rounded_size);
0043 #  else
0044   void* __result = nullptr;
0045   (void)::posix_memalign(&__result, __alignment, __size);
0046   // If posix_memalign fails, __result is unmodified so we still return `nullptr`.
0047   return __result;
0048 #  endif
0049 }
0050 
0051 inline _LIBCPP_HIDE_FROM_ABI void __libcpp_aligned_free(void* __ptr) {
0052 #  if defined(_LIBCPP_MSVCRT_LIKE)
0053   ::_aligned_free(__ptr);
0054 #  else
0055   ::free(__ptr);
0056 #  endif
0057 }
0058 
0059 #endif // _LIBCPP_HAS_LIBRARY_ALIGNED_ALLOCATION
0060 
0061 _LIBCPP_END_NAMESPACE_STD
0062 
0063 #endif // _LIBCPP___MEMORY_ALIGNED_ALLOC_H