1 //===-- llvm/ADT/bit.h - C++20 <bit> ----------------------------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file implements the C++20 <bit> header. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #ifndef LLVM_ADT_BIT_H 14 #define LLVM_ADT_BIT_H 15 16 #include "llvm/Support/Compiler.h" 17 #include <cstring> 18 #include <type_traits> 19 20 namespace llvm { 21 22 // This implementation of bit_cast is different from the C++17 one in two ways: 23 // - It isn't constexpr because that requires compiler support. 24 // - It requires trivially-constructible To, to avoid UB in the implementation. 25 template <typename To, typename From 26 , typename = typename std::enable_if<sizeof(To) == sizeof(From)>::type 27 #if (__has_feature(is_trivially_constructible) && defined(_LIBCPP_VERSION)) || \ 28 (defined(__GNUC__) && __GNUC__ >= 5) 29 , typename = typename std::is_trivially_constructible<To>::type 30 #elif __has_feature(is_trivially_constructible) 31 , typename = typename std::enable_if<__is_trivially_constructible(To)>::type 32 #else 33 // See comment below. 34 #endif 35 #if (__has_feature(is_trivially_copyable) && defined(_LIBCPP_VERSION)) || \ 36 (defined(__GNUC__) && __GNUC__ >= 5) 37 , typename = typename std::enable_if<std::is_trivially_copyable<To>::value>::type 38 , typename = typename std::enable_if<std::is_trivially_copyable<From>::value>::type 39 #elif __has_feature(is_trivially_copyable) 40 , typename = typename std::enable_if<__is_trivially_copyable(To)>::type 41 , typename = typename std::enable_if<__is_trivially_copyable(From)>::type 42 #else 43 // This case is GCC 4.x. clang with libc++ or libstdc++ never get here. Unlike 44 // llvm/Support/type_traits.h's is_trivially_copyable we don't want to 45 // provide a good-enough answer here: developers in that configuration will hit 46 // compilation failures on the bots instead of locally. That's acceptable 47 // because it's very few developers, and only until we move past C++11. 48 #endif 49 > 50 inline To bit_cast(const From &from) noexcept { 51 To to; 52 std::memcpy(&to, &from, sizeof(To)); 53 return to; 54 } 55 56 } // namespace llvm 57 58 #endif 59