From ab04175aad4252aa149e691b2e7c27141a53f489 Mon Sep 17 00:00:00 2001 From: Ben Vanik Date: Fri, 28 Aug 2015 14:27:44 -0700 Subject: [PATCH] Abstracting aligned alloc/free. --- src/xenia/base/memory.h | 25 +++++++++++++++++++++++++ src/xenia/cpu/thread_state.cc | 19 +++---------------- 2 files changed, 28 insertions(+), 16 deletions(-) diff --git a/src/xenia/base/memory.h b/src/xenia/base/memory.h index e24dd0d94..abb83bb45 100644 --- a/src/xenia/base/memory.h +++ b/src/xenia/base/memory.h @@ -63,6 +63,31 @@ bool DeallocFixed(void* base_address, size_t length, bool Protect(void* base_address, size_t length, PageAccess access, PageAccess* out_old_access); +// Allocates a block of memory for a type with the given alignment. +// The memory must be freed with AlignedFree. +template +inline T* AlignedAlloc(size_t alignment) { +#if __STDC_VERSION__ >= 201112L + return reinterpret_cast(aligned_alloc(alignment, sizeof(T))); +#elif XE_COMPILER_MSVC + return reinterpret_cast(_aligned_malloc(sizeof(T), alignment)); +#else +#error No aligned alloc. +#endif // __STDC_VERSION__ >= 201112L +} + +// Frees memory previously allocated with AlignedAlloc. +template +void AlignedFree(T* ptr) { +#if __STDC_VERSION__ >= 201112L + free(ptr); +#elif XE_COMPILER_MSVC + _aligned_free(ptr); +#else +#error No aligned alloc. +#endif // __STDC_VERSION__ >= 201112L +} + typedef void* FileMappingHandle; FileMappingHandle CreateFileMappingHandle(std::wstring path, size_t length, diff --git a/src/xenia/cpu/thread_state.cc b/src/xenia/cpu/thread_state.cc index 3f99b2f9d..a512f92a4 100644 --- a/src/xenia/cpu/thread_state.cc +++ b/src/xenia/cpu/thread_state.cc @@ -84,15 +84,8 @@ ThreadState::ThreadState(Processor* processor, uint32_t thread_id, } assert_not_zero(stack_address_); -// Allocate with 64b alignment. -#if __STDC_VERSION__ >= 201112L - void* context_ptr = aligned_alloc(64, sizeof(PPCContext)); -#elif XE_COMPILER_MSVC - void* context_ptr = _aligned_malloc(sizeof(PPCContext), 64); -#else -#error No aligned alloc. -#endif - context_ = reinterpret_cast(context_ptr); + // Allocate with 64b alignment. + context_ = memory::AlignedAlloc(64); assert_true(((uint64_t)context_ & 0x3F) == 0); std::memset(context_, 0, sizeof(PPCContext)); @@ -117,13 +110,7 @@ ThreadState::~ThreadState() { thread_state_ = nullptr; } -#if __STDC_VERSION__ >= 201112L - free(context_); -#elif XE_COMPILER_MSVC - _aligned_free(context_); -#else -#error No aligned alloc. -#endif + memory::AlignedFree(context_); if (stack_allocated_) { memory()->LookupHeap(stack_address_)->Decommit(stack_address_, stack_size_); }