Path: blob/main/contrib/llvm-project/libcxx/include/__memory/aligned_alloc.h
35233 views
//===----------------------------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#ifndef _LIBCPP___MEMORY_ALIGNED_ALLOC_H9#define _LIBCPP___MEMORY_ALIGNED_ALLOC_H1011#include <__config>12#include <cstddef>13#include <cstdlib>1415#if !defined(_LIBCPP_HAS_NO_PRAGMA_SYSTEM_HEADER)16# pragma GCC system_header17#endif1819_LIBCPP_BEGIN_NAMESPACE_STD2021#ifndef _LIBCPP_HAS_NO_LIBRARY_ALIGNED_ALLOCATION2223// Low-level helpers to call the aligned allocation and deallocation functions24// on the target platform. This is used to implement libc++'s own memory25// allocation routines -- if you need to allocate memory inside the library,26// chances are that you want to use `__libcpp_allocate` instead.27//28// Returns the allocated memory, or `nullptr` on failure.29inline _LIBCPP_HIDE_FROM_ABI void* __libcpp_aligned_alloc(std::size_t __alignment, std::size_t __size) {30# if defined(_LIBCPP_MSVCRT_LIKE)31return ::_aligned_malloc(__size, __alignment);32# elif _LIBCPP_STD_VER >= 17 && !defined(_LIBCPP_HAS_NO_C11_ALIGNED_ALLOC)33// aligned_alloc() requires that __size is a multiple of __alignment,34// but for C++ [new.delete.general], only states "if the value of an35// alignment argument passed to any of these functions is not a valid36// alignment value, the behavior is undefined".37// To handle calls such as ::operator new(1, std::align_val_t(128)), we38// round __size up to the next multiple of __alignment.39size_t __rounded_size = (__size + __alignment - 1) & ~(__alignment - 1);40// Rounding up could have wrapped around to zero, so we have to add another41// max() ternary to the actual call site to avoid succeeded in that case.42return ::aligned_alloc(__alignment, __size > __rounded_size ? __size : __rounded_size);43# else44void* __result = nullptr;45(void)::posix_memalign(&__result, __alignment, __size);46// If posix_memalign fails, __result is unmodified so we still return `nullptr`.47return __result;48# endif49}5051inline _LIBCPP_HIDE_FROM_ABI void __libcpp_aligned_free(void* __ptr) {52# if defined(_LIBCPP_MSVCRT_LIKE)53::_aligned_free(__ptr);54# else55::free(__ptr);56# endif57}5859#endif // !_LIBCPP_HAS_NO_LIBRARY_ALIGNED_ALLOCATION6061_LIBCPP_END_NAMESPACE_STD6263#endif // _LIBCPP___MEMORY_ALIGNED_ALLOC_H646566