Malloc.h 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. //===--- Malloc.h - Aligned malloc interface --------------------*- C++ -*-===//
  2. //
  3. // This source file is part of the Swift.org open source project
  4. //
  5. // Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
  6. // Licensed under Apache License v2.0 with Runtime Library Exception
  7. //
  8. // See http://swift.org/LICENSE.txt for license information
  9. // See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
  10. //
  11. //===----------------------------------------------------------------------===//
  12. //
  13. // This file provides an implementation of C11 aligned_alloc(3) for platforms
  14. // that don't have it yet, using posix_memalign(3).
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef SWIFT_BASIC_MALLOC_H
  18. #define SWIFT_BASIC_MALLOC_H
  19. #include <cassert>
  20. #if defined(_MSC_VER)
  21. #include <malloc.h>
  22. #else
  23. #include <cstdlib>
  24. #endif
  25. namespace swift {
  26. // FIXME: Use C11 aligned_alloc if available.
  27. inline void *AlignedAlloc(size_t size, size_t align) {
  28. // posix_memalign only accepts alignments greater than sizeof(void*).
  29. //
  30. if (align < sizeof(void*))
  31. align = sizeof(void*);
  32. void *r;
  33. #if defined(_WIN32)
  34. r = _aligned_malloc(size, align);
  35. assert(r && "_aligned_malloc failed");
  36. #else
  37. int res = posix_memalign(&r, align, size);
  38. assert(res == 0 && "posix_memalign failed");
  39. (void)res; // Silence the unused variable warning.
  40. #endif
  41. return r;
  42. }
  43. inline void AlignedFree(void *p) {
  44. #if defined(_WIN32)
  45. _aligned_free(p);
  46. #else
  47. free(p);
  48. #endif
  49. }
  50. } // end namespace swift
  51. #endif // SWIFT_BASIC_MALLOC_H