[libc-commits] [libc] [libc][malloc] Align blocks to max_align_t. (PR #100279)

Daniel Thornburgh via libc-commits libc-commits at lists.llvm.org
Tue Jul 23 16:29:23 PDT 2024


https://github.com/mysterymath created https://github.com/llvm/llvm-project/pull/100279

Since there are two offsets from block start to usable area, this ensures that the usable area is maximally aligned, so long as the offset type size is no less than half the max alignment. This is true on at least typical 32-bit and 64-bit targets.

Previously, there was a roughly 50-50 chance a given block's usable area would be misaligned for a malloc on a 32-bit system. The half that were misaligned would require at least one block of additional padding, costing 12 bytes. With this change, the only cost is 0-4 bytes at the beginning of the heap to reach an initial 8-byte alignment.

>From 153a181c1566bba1ff250b6ac9394c3b0e06eb7f Mon Sep 17 00:00:00 2001
From: Daniel Thornburgh <dthorn at google.com>
Date: Tue, 23 Jul 2024 14:05:56 -0700
Subject: [PATCH] [libc][malloc] Align blocks to max_align_t.

Since there are two offsets from block start to usable area, this
ensures that the usable area is maximally aligned, so long as the offset
type size is no less than half the max alignment. This is true on at
least typical 32-bit and 64-bit targets.

Previously, there was a roughly 50-50 chance a given block's usable area
would be misaligned for a malloc on a 32-bit system. The half that were
misaligned would require at least one block of additional padding,
costing 12 bytes. With this change, the only cost is up to 4 bytes at
the beginning of the heap to reach an 8-byte alignment.
---
 libc/src/__support/block.h | 9 ++++++---
 1 file changed, 6 insertions(+), 3 deletions(-)

diff --git a/libc/src/__support/block.h b/libc/src/__support/block.h
index af3ce181f1c99..86cb4bd7ad582 100644
--- a/libc/src/__support/block.h
+++ b/libc/src/__support/block.h
@@ -102,9 +102,12 @@ using cpp::optional;
 ///                       types can address more memory, but consume greater
 ///                       overhead.
 /// @tparam   kAlign      Sets the overall alignment for blocks. Minimum is
-///                       `alignof(OffsetType)` (the default). Larger values
-///                       cause greater overhead.
-template <typename OffsetType = uintptr_t, size_t kAlign = alignof(OffsetType)>
+///                       `alignof(OffsetType)`, but the default is max_align_t,
+///                       since the usable space will then already be
+///                       aligned to max_align_t if the size of OffsetType is no
+///                       less than half of max_align_t. Larger values cause
+///                       greater overhead.
+template <typename OffsetType = uintptr_t, size_t kAlign = alignof(max_align_t)>
 class Block {
   // Masks for the contents of the next_ field.
   static constexpr size_t USED_MASK = 1 << 0;



More information about the libc-commits mailing list