Skip to content

Commit 4c9dc26

Browse files
authored
Merge pull request #14375 from mikeash/fix-slowalloc-alignment
[Runtime] Fix swift_slowAlloc to respect its alignMask parameter.
2 parents e0f4326 + 7b091bf commit 4c9dc26

File tree

1 file changed

+39
-3
lines changed

1 file changed

+39
-3
lines changed

stdlib/public/runtime/Heap.cpp

Lines changed: 39 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -18,17 +18,53 @@
1818
#include "swift/Runtime/Heap.h"
1919
#include "Private.h"
2020
#include "swift/Runtime/Debug.h"
21+
#include <algorithm>
2122
#include <stdlib.h>
2223

2324
using namespace swift;
2425

26+
#if defined(__APPLE__)
27+
// Apple malloc is always 16-byte aligned.
28+
# define MALLOC_ALIGN_MASK 15
29+
30+
#elif defined(__linux__)
31+
// Linux malloc is 16-byte aligned on 64-bit, and 8-byte aligned on 32-bit.
32+
# if defined(__LP64)
33+
# define MALLOC_ALIGN_MASK 15
34+
# else
35+
# define MALLOC_ALIGN_MASK 7
36+
# endif
37+
38+
#elif defined(_WIN64)
39+
// Windows malloc is 16-byte aligned on 64-bit and 8-byte aligned on 32-bit.
40+
# define MALLOC_ALIGN_MASK 15
41+
#elif defined(_WIN32)
42+
# define MALLOC_ALIGN_MASK 7
43+
44+
#else
45+
// Unknown alignment, but the standard requires alignment suitable for the largest
46+
// standard types.
47+
# define MALLOC_ALIGN_MASK std::max(alignof(void *), alignof(double))
48+
49+
#endif
50+
51+
52+
2553
void *swift::swift_slowAlloc(size_t size, size_t alignMask) {
26-
// FIXME: use posix_memalign if alignMask is larger than the system guarantee.
27-
void *p = malloc(size);
54+
void *p;
55+
if (alignMask <= MALLOC_ALIGN_MASK) {
56+
p = malloc(size);
57+
} else {
58+
p = AlignedAlloc(size, alignMask + 1);
59+
}
2860
if (!p) swift::crash("Could not allocate memory.");
2961
return p;
3062
}
3163

3264
void swift::swift_slowDealloc(void *ptr, size_t bytes, size_t alignMask) {
33-
free(ptr);
65+
if (alignMask <= MALLOC_ALIGN_MASK) {
66+
free(ptr);
67+
} else {
68+
AlignedFree(ptr);
69+
}
3470
}

0 commit comments

Comments
 (0)