[libc-commits] [libc] [libc][strings] Refactor load_aligned for cleaner endianness handling (PR #186360)

Jeff Bailey via libc-commits libc-commits at lists.llvm.org
Fri Mar 20 01:03:46 PDT 2026


================
@@ -232,20 +232,18 @@ template <typename ValueType, typename T, typename... TS>
 LIBC_INLINE ValueType load_aligned(CPtr src) {
   static_assert(sizeof(ValueType) >= (sizeof(T) + ... + sizeof(TS)));
   const ValueType value = load<T>(assume_aligned<sizeof(T)>(src));
+
   if constexpr (sizeof...(TS) > 0) {
     const ValueType next = load_aligned<ValueType, TS...>(src + sizeof(T));
-    if constexpr (Endian::IS_LITTLE) {
-      // T goes at the bottom of the output, so shift up everything
-      // else by the number of bits in T.
-      constexpr size_t SHIFT = sizeof(T) * 8;
-      return value | (next << SHIFT);
-    } else if constexpr (Endian::IS_BIG) {
-      // T goes at the top of the output, so shift it up by the number
-      // of bits in everything else that goes below it.
-      constexpr size_t SHIFT = (0 + ... + sizeof(TS)) * 8;
-      return (value << SHIFT) | next;
-    } else
-      static_assert(cpp::always_false<T>, "Invalid endianness");
+
+    // Calculate shifts at compile time.
+    // In Little Endian, 'value' stays at the bottom (shift 0).
+    // In Big Endian, 'next' stays at the bottom (shift 0).
+    constexpr size_t VAL_SHIFT = Endian::IS_LITTLE ? 0 : (sizeof(TS) + ...) * 8;
----------------
kaladron wrote:

It's not needed because we're in a "if constexpr (sizeof...(TS) > 0) {" block.

Now I'm wondering if I should invert that if and do an early return...  I'll think about it today.

https://github.com/llvm/llvm-project/pull/186360


More information about the libc-commits mailing list