Browse Source

Using non-aligned allocations when possible in the TempAllocator (#1827)

virtul 2 weeks ago
parent
commit
5b7b06f48d
1 changed files with 27 additions and 6 deletions
  1. 27 6
      Jolt/Core/TempAllocator.h

+ 27 - 6
Jolt/Core/TempAllocator.h

@@ -17,6 +17,9 @@ class JPH_EXPORT TempAllocator : public NonCopyable
 public:
 public:
 	JPH_OVERRIDE_NEW_DELETE
 	JPH_OVERRIDE_NEW_DELETE
 
 
+	/// If this allocator needs to fall back to aligned allocations because JPH_RVECTOR_ALIGNMENT is bigger than the platform default
+	static constexpr bool			needs_aligned_allocate = JPH_RVECTOR_ALIGNMENT > (JPH_CPU_ADDRESS_BITS == 32? 8 : 16);
+
 	/// Destructor
 	/// Destructor
 	virtual							~TempAllocator() = default;
 	virtual							~TempAllocator() = default;
 
 
@@ -34,17 +37,22 @@ public:
 	JPH_OVERRIDE_NEW_DELETE
 	JPH_OVERRIDE_NEW_DELETE
 
 
 	/// Constructs the allocator with a maximum allocatable size of inSize
 	/// Constructs the allocator with a maximum allocatable size of inSize
-	explicit						TempAllocatorImpl(size_t inSize) :
-		mBase(static_cast<uint8 *>(AlignedAllocate(inSize, JPH_RVECTOR_ALIGNMENT))),
-		mSize(inSize)
+	explicit						TempAllocatorImpl(size_t inSize) : mSize(inSize)
 	{
 	{
+		if constexpr (needs_aligned_allocate)
+			mBase = static_cast<uint8 *>(AlignedAllocate(inSize, JPH_RVECTOR_ALIGNMENT));
+		else
+			mBase = static_cast<uint8 *>(JPH::Allocate(inSize));
 	}
 	}
 
 
 	/// Destructor, frees the block
 	/// Destructor, frees the block
 	virtual							~TempAllocatorImpl() override
 	virtual							~TempAllocatorImpl() override
 	{
 	{
 		JPH_ASSERT(mTop == 0);
 		JPH_ASSERT(mTop == 0);
-		AlignedFree(mBase);
+		if constexpr (needs_aligned_allocate)
+			AlignedFree(mBase);
+		else
+			JPH::Free(mBase);
 	}
 	}
 
 
 	// See: TempAllocator
 	// See: TempAllocator
@@ -132,14 +140,27 @@ public:
 	// See: TempAllocator
 	// See: TempAllocator
 	virtual void *					Allocate(uint inSize) override
 	virtual void *					Allocate(uint inSize) override
 	{
 	{
-		return inSize > 0? AlignedAllocate(inSize, JPH_RVECTOR_ALIGNMENT) : nullptr;
+		if (inSize > 0)
+		{
+			if constexpr (needs_aligned_allocate)
+				return AlignedAllocate(inSize, JPH_RVECTOR_ALIGNMENT);
+			else
+				return JPH::Allocate(inSize);
+		}
+		else
+			return nullptr;
 	}
 	}
 
 
 	// See: TempAllocator
 	// See: TempAllocator
 	virtual void					Free(void *inAddress, [[maybe_unused]] uint inSize) override
 	virtual void					Free(void *inAddress, [[maybe_unused]] uint inSize) override
 	{
 	{
 		if (inAddress != nullptr)
 		if (inAddress != nullptr)
-			AlignedFree(inAddress);
+		{
+			if constexpr (needs_aligned_allocate)
+				AlignedFree(inAddress);
+			else
+				JPH::Free(inAddress);
+		}
 	}
 	}
 };
 };