1193326Sed/*===---- mm_malloc.h - Allocating and Freeing Aligned Memory Blocks -------===
2193326Sed *
3353358Sdim * Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4353358Sdim * See https://llvm.org/LICENSE.txt for license information.
5353358Sdim * SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6193326Sed *
7193326Sed *===-----------------------------------------------------------------------===
8193326Sed */
9193326Sed
10193326Sed#ifndef __MM_MALLOC_H
11193326Sed#define __MM_MALLOC_H
12193326Sed
13193326Sed#include <stdlib.h>
14193326Sed
15218893Sdim#ifdef _WIN32
16218893Sdim#include <malloc.h>
17218893Sdim#else
18218893Sdim#ifndef __cplusplus
19249423Sdimextern int posix_memalign(void **__memptr, size_t __alignment, size_t __size);
20218893Sdim#else
21218893Sdim// Some systems (e.g. those with GNU libc) declare posix_memalign with an
22218893Sdim// exception specifier. Via an "egregious workaround" in
23218893Sdim// Sema::CheckEquivalentExceptionSpec, Clang accepts the following as a valid
24218893Sdim// redeclaration of glibc's declaration.
25249423Sdimextern "C" int posix_memalign(void **__memptr, size_t __alignment, size_t __size);
26218893Sdim#endif
27218893Sdim#endif
28218893Sdim
29221345Sdim#if !(defined(_WIN32) && defined(_mm_malloc))
30218893Sdimstatic __inline__ void *__attribute__((__always_inline__, __nodebug__,
31218893Sdim                                       __malloc__))
32249423Sdim_mm_malloc(size_t __size, size_t __align)
33193326Sed{
34249423Sdim  if (__align == 1) {
35249423Sdim    return malloc(__size);
36193326Sed  }
37193326Sed
38249423Sdim  if (!(__align & (__align - 1)) && __align < sizeof(void *))
39249423Sdim    __align = sizeof(void *);
40193326Sed
41249423Sdim  void *__mallocedMemory;
42226633Sdim#if defined(__MINGW32__)
43249423Sdim  __mallocedMemory = __mingw_aligned_malloc(__size, __align);
44226633Sdim#elif defined(_WIN32)
45249423Sdim  __mallocedMemory = _aligned_malloc(__size, __align);
46218893Sdim#else
47249423Sdim  if (posix_memalign(&__mallocedMemory, __align, __size))
48193326Sed    return 0;
49218893Sdim#endif
50193326Sed
51249423Sdim  return __mallocedMemory;
52193326Sed}
53193326Sed
54206084Srdivackystatic __inline__ void __attribute__((__always_inline__, __nodebug__))
55249423Sdim_mm_free(void *__p)
56193326Sed{
57249423Sdim  free(__p);
58193326Sed}
59221345Sdim#endif
60193326Sed
61193326Sed#endif /* __MM_MALLOC_H */
62