[llvm] 8a12039 - [llvm adt] Use `__builtin_bswap16` in `byteswap()` when available (#190002)

via llvm-commits llvm-commits at lists.llvm.org
Wed Apr 15 05:17:17 PDT 2026


Author: Roy Shi
Date: 2026-04-15T05:17:12-07:00
New Revision: 8a12039aa538b13451b1864e7eafbbe04d58b6f3

URL: https://github.com/llvm/llvm-project/commit/8a12039aa538b13451b1864e7eafbbe04d58b6f3
DIFF: https://github.com/llvm/llvm-project/commit/8a12039aa538b13451b1864e7eafbbe04d58b6f3.diff

LOG: [llvm adt] Use `__builtin_bswap16` in `byteswap()` when available (#190002)

The 32-bit and 64-bit branch of the code has the same pattern of using
`__builtin_bswapXX` when available (before trying to use
`_byteswap_XXXXX`). But the 16-bit branch doesn't do this (it only tries
to use the latter).

It seems `__builtin_bswap16` is a thing (see
[doc](https://gcc.gnu.org/onlinedocs/gcc/Byte-Swapping-Builtins.html)),
so I wonder if we just forgot to use it in the 16-bit branch.

Adding it and hope it helps (i.e. faster than the default shift-and-or
approach).

Added: 
    

Modified: 
    llvm/include/llvm/ADT/bit.h

Removed: 
    


################################################################################
diff  --git a/llvm/include/llvm/ADT/bit.h b/llvm/include/llvm/ADT/bit.h
index 2bb0b881f6ede..3ac23d6d48cc4 100644
--- a/llvm/include/llvm/ADT/bit.h
+++ b/llvm/include/llvm/ADT/bit.h
@@ -104,7 +104,9 @@ template <typename T, typename = std::enable_if_t<std::is_integral_v<T>>>
     return V;
   } else if constexpr (sizeof(T) == 2) {
     uint16_t UV = V;
-#if defined(_MSC_VER) && !defined(_DEBUG)
+#if __has_builtin(__builtin_bswap16)
+    return __builtin_bswap16(UV);
+#elif defined(_MSC_VER) && !defined(_DEBUG)
     // The DLL version of the runtime lacks these functions (bug!?), but in a
     // release build they're replaced with BSWAP instructions anyway.
     return _byteswap_ushort(UV);


        


More information about the llvm-commits mailing list