util_aligned_malloc.cpp 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. /*
  2. * Copyright 2011-2015 Blender Foundation
  3. *
  4. * Licensed under the Apache License, Version 2.0 (the "License");
  5. * you may not use this file except in compliance with the License.
  6. * You may obtain a copy of the License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software
  11. * distributed under the License is distributed on an "AS IS" BASIS,
  12. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  13. * See the License for the specific language governing permissions and
  14. * limitations under the License.
  15. */
  16. #include "util/util_aligned_malloc.h"
  17. #include "util/util_guarded_allocator.h"
  18. #include <cassert>
  19. /* Adopted from Libmv. */
  20. #if !defined(__APPLE__) && !defined(__FreeBSD__) && !defined(__NetBSD__)
  21. /* Needed for memalign on Linux and _aligned_alloc on Windows. */
  22. # ifdef FREE_WINDOWS
  23. /* Make sure _aligned_malloc is included. */
  24. # ifdef __MSVCRT_VERSION__
  25. # undef __MSVCRT_VERSION__
  26. # endif
  27. # define __MSVCRT_VERSION__ 0x0700
  28. # endif /* FREE_WINDOWS */
  29. # include <malloc.h>
  30. #else
  31. /* Apple's malloc is 16-byte aligned, and does not have malloc.h, so include
  32. * stdilb instead.
  33. */
  34. # include <cstdlib>
  35. #endif
  36. CCL_NAMESPACE_BEGIN
  37. void *util_aligned_malloc(size_t size, int alignment)
  38. {
  39. #ifdef WITH_BLENDER_GUARDEDALLOC
  40. return MEM_mallocN_aligned(size, alignment, "Cycles Aligned Alloc");
  41. #elif defined(_WIN32)
  42. return _aligned_malloc(size, alignment);
  43. #elif defined(__APPLE__)
  44. /* On Mac OS X, both the heap and the stack are guaranteed 16-byte aligned so
  45. * they work natively with SSE types with no further work.
  46. */
  47. assert(alignment == 16);
  48. return malloc(size);
  49. #elif defined(__FreeBSD__) || defined(__NetBSD__)
  50. void *result;
  51. if (posix_memalign(&result, alignment, size)) {
  52. /* Non-zero means allocation error
  53. * either no allocation or bad alignment value.
  54. */
  55. return NULL;
  56. }
  57. return result;
  58. #else /* This is for Linux. */
  59. return memalign(alignment, size);
  60. #endif
  61. }
  62. void util_aligned_free(void *ptr)
  63. {
  64. #if defined(WITH_BLENDER_GUARDEDALLOC)
  65. if (ptr != NULL) {
  66. MEM_freeN(ptr);
  67. }
  68. #elif defined(_WIN32)
  69. _aligned_free(ptr);
  70. #else
  71. free(ptr);
  72. #endif
  73. }
  74. CCL_NAMESPACE_END