Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Have jl_realloc_aligned /try/ realloc, then fallback to malloc if not aligned #32320

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 15 additions & 0 deletions src/julia_internal.h
Original file line number Diff line number Diff line change
Expand Up @@ -909,13 +909,28 @@ STATIC_INLINE void *jl_malloc_aligned(size_t sz, size_t align)
return NULL;
return ptr;
}

#define jl_is_aligned(POINTER, BYTE_COUNT) \
(((uintptr_t)(const void *)(POINTER)) % (BYTE_COUNT) == 0)

STATIC_INLINE void *jl_realloc_aligned(void *d, size_t sz, size_t oldsz,
size_t align)
{
#if defined(_P64) || defined(__APPLE__)
if (align <= 16)
return realloc(d, sz);
#endif
// Since there is no system realloc_aligned, we use the following strategy: Try realloc
// and hope that it maintains alignment. If it doesn't, manually allocate again via the
// (malloc, memcpy, and free) steps, below.
void *r = realloc(d, sz);
if (r != NULL && jl_is_aligned(r, align)) {
return r;
} else if (r != NULL) {
// (Don't overwrite d unless r is non-null; if realloc returns NULL, d is unchanged)
d = r;
}

void *b = jl_malloc_aligned(sz, align);
if (b != NULL) {
memcpy(b, d, oldsz > sz ? sz : oldsz);
Expand Down