Path: blob/main/contrib/llvm-project/libc/src/__support/FPUtil/cast.h
213799 views
//===-- Conversion between floating-point types -----------------*- C++ -*-===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#ifndef LLVM_LIBC_SRC___SUPPORT_FPUTIL_CAST_H9#define LLVM_LIBC_SRC___SUPPORT_FPUTIL_CAST_H1011#include "FPBits.h"12#include "dyadic_float.h"13#include "hdr/fenv_macros.h"14#include "src/__support/CPP/algorithm.h"15#include "src/__support/CPP/type_traits.h"16#include "src/__support/macros/properties/types.h"1718namespace LIBC_NAMESPACE::fputil {1920// TODO: Add optimization for known good targets with fast21// float to float16 conversion:22// https://github.com/llvm/llvm-project/issues/13351723template <typename OutType, typename InType>24LIBC_INLINE constexpr cpp::enable_if_t<cpp::is_floating_point_v<OutType> &&25cpp::is_floating_point_v<InType>,26OutType>27cast(InType x) {28// Casting to the same type is a no-op.29if constexpr (cpp::is_same_v<InType, OutType>)30return x;3132// bfloat16 is always defined (for now)33if constexpr (cpp::is_same_v<OutType, bfloat16> ||34cpp::is_same_v<InType, bfloat16>35#if defined(LIBC_TYPES_HAS_FLOAT16) && !defined(__LIBC_USE_FLOAT16_CONVERSION)36|| cpp::is_same_v<OutType, float16> ||37cpp::is_same_v<InType, float16>38#endif39) {40using InFPBits = FPBits<InType>;41using InStorageType = typename InFPBits::StorageType;42using OutFPBits = FPBits<OutType>;43using OutStorageType = typename OutFPBits::StorageType;4445InFPBits x_bits(x);4647if (x_bits.is_nan()) {48if (x_bits.is_signaling_nan()) {49raise_except_if_required(FE_INVALID);50return OutFPBits::quiet_nan().get_val();51}5253InStorageType x_mant = x_bits.get_mantissa();54if (InFPBits::FRACTION_LEN > OutFPBits::FRACTION_LEN)55x_mant >>= InFPBits::FRACTION_LEN - OutFPBits::FRACTION_LEN;56return OutFPBits::quiet_nan(x_bits.sign(),57static_cast<OutStorageType>(x_mant))58.get_val();59}6061if (x_bits.is_inf())62return OutFPBits::inf(x_bits.sign()).get_val();6364constexpr size_t MAX_FRACTION_LEN =65cpp::max(OutFPBits::FRACTION_LEN, InFPBits::FRACTION_LEN);66DyadicFloat<cpp::bit_ceil(MAX_FRACTION_LEN)> xd(x);67return xd.template as<OutType, /*ShouldSignalExceptions=*/true>();68}6970return static_cast<OutType>(x);71}7273} // namespace LIBC_NAMESPACE::fputil7475#endif // LLVM_LIBC_SRC___SUPPORT_FPUTIL_CAST_H767778