[llvm] dd8ecde - [ADT] llvm::bit_cast - use __builtin_bit_cast if available

Simon Pilgrim via llvm-commits llvm-commits at lists.llvm.org
Sun Jan 22 10:21:24 PST 2023


Author: Simon Pilgrim
Date: 2023-01-22T18:21:08Z
New Revision: dd8ecde00b3b3d8d0f80d7df43393f583d782413

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

LOG: [ADT] llvm::bit_cast - use __builtin_bit_cast if available

If the compiler supports __builtin_bit_cast we should try to use it instead of std::memcpy (and avoid including the cstring header).

Differential Revision: https://reviews.llvm.org/D142305

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 887dd519fa44..d93023d88b4e 100644
--- a/llvm/include/llvm/ADT/bit.h
+++ b/llvm/include/llvm/ADT/bit.h
@@ -16,10 +16,13 @@
 
 #include "llvm/Support/Compiler.h"
 #include <cstdint>
-#include <cstring>
 #include <limits>
 #include <type_traits>
 
+#if !__has_builtin(__builtin_bit_cast)
+#include <cstring>
+#endif
+
 #if defined(_MSC_VER) && !defined(_DEBUG)
 #include <cstdlib>  // for _byteswap_{ushort,ulong,uint64}
 #endif
@@ -48,9 +51,13 @@ template <
     typename = std::enable_if_t<std::is_trivially_copyable<To>::value>,
     typename = std::enable_if_t<std::is_trivially_copyable<From>::value>>
 [[nodiscard]] inline To bit_cast(const From &from) noexcept {
+#if __has_builtin(__builtin_bit_cast)
+  return __builtin_bit_cast(To, from);
+#else
   To to;
   std::memcpy(&to, &from, sizeof(To));
   return to;
+#endif
 }
 
 /// Reverses the bytes in the given integer value V.


        


More information about the llvm-commits mailing list