[libc-commits] [PATCH] D148739: [libc] Use __builtin_bit_cast only when src and dest types are trivially copyable

Mikhail Ramalho via Phabricator via libc-commits libc-commits at lists.llvm.org
Wed Apr 19 16:25:15 PDT 2023


mikhail.ramalho updated this revision to Diff 515125.
mikhail.ramalho added a comment.

Remove C++ standard library in the runtime components of the libc


Repository:
  rG LLVM Github Monorepo

CHANGES SINCE LAST ACTION
  https://reviews.llvm.org/D148739/new/

https://reviews.llvm.org/D148739

Files:
  libc/src/__support/CPP/bit.h
  libc/src/__support/CPP/type_traits.h


Index: libc/src/__support/CPP/type_traits.h
===================================================================
--- libc/src/__support/CPP/type_traits.h
+++ libc/src/__support/CPP/type_traits.h
@@ -28,6 +28,10 @@
 using true_type = cpp::integral_constant<bool, true>;
 using false_type = cpp::integral_constant<bool, false>;
 
+template <class _Tp>
+struct is_trivially_copyable
+    : public integral_constant<bool, __is_trivially_copyable(_Tp)> {};
+
 template <typename T, typename U> struct is_same : cpp::false_type {};
 template <typename T> struct is_same<T, T> : cpp::true_type {};
 template <typename T, typename U>
Index: libc/src/__support/CPP/bit.h
===================================================================
--- libc/src/__support/CPP/bit.h
+++ libc/src/__support/CPP/bit.h
@@ -9,6 +9,7 @@
 #ifndef LLVM_LIBC_SUPPORT_CPP_BIT_H
 #define LLVM_LIBC_SUPPORT_CPP_BIT_H
 
+#include "src/__support/CPP/type_traits.h"
 #include "src/__support/macros/config.h" // LIBC_HAS_BUILTIN
 
 namespace __llvm_libc::cpp {
@@ -26,8 +27,10 @@
 template <class To, class From> constexpr To bit_cast(const From &from) {
   static_assert(sizeof(To) == sizeof(From), "To and From must be of same size");
 #if defined(LLVM_LIBC_HAS_BUILTIN_BIT_CAST)
-  return __builtin_bit_cast(To, from);
-#else
+  if constexpr (cpp::is_trivially_copyable<To>::value &&
+                cpp::is_trivially_copyable<From>::value)
+    return __builtin_bit_cast(To, from);
+#endif // defined(LLVM_LIBC_HAS_BUILTIN_BIT_CAST)
   To to;
   char *dst = reinterpret_cast<char *>(&to);
   const char *src = reinterpret_cast<const char *>(&from);
@@ -38,7 +41,6 @@
     dst[i] = src[i];
 #endif // defined(LLVM_LIBC_HAS_BUILTIN_MEMCPY_INLINE)
   return to;
-#endif // defined(LLVM_LIBC_HAS_BUILTIN_BIT_CAST)
 }
 
 } // namespace __llvm_libc::cpp


-------------- next part --------------
A non-text attachment was scrubbed...
Name: D148739.515125.patch
Type: text/x-patch
Size: 1817 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/libc-commits/attachments/20230419/4ef93835/attachment.bin>


More information about the libc-commits mailing list