Core: Round integer casts to bfloat16 and int64 casts to float once (!3305 follow-ups)

libeigen/eigen!3337

Co-authored-by: Rasmus Munk Larsen <rmlarsen@gmail.com>
diff --git a/Eigen/src/Core/MathFunctions.h b/Eigen/src/Core/MathFunctions.h
index 1074a55..7ede5d8 100644
--- a/Eigen/src/Core/MathFunctions.h
+++ b/Eigen/src/Core/MathFunctions.h
@@ -370,10 +370,29 @@
 struct cast_impl<OldType, NewType, std::enable_if_t<!NumTraits<OldType>::IsComplex && NumTraits<NewType>::IsComplex>> {
   EIGEN_DEVICE_FUNC static inline NewType run(const OldType& x) {
     using NewReal = typename NumTraits<NewType>::Real;
-    return static_cast<NewType>(static_cast<NewReal>(x));
+    return static_cast<NewType>(cast_impl<OldType, NewReal>::run(x));
   }
 };
 
+#if EIGEN_ARCH_ARM64 && EIGEN_COMP_CLANG && !EIGEN_CLANG_STRICT_AT_LEAST(21, 0, 0)
+// Clang before 21, and the Clang forks whose version does not say, vectorize a loop of 64-bit integer to float
+// conversions through double on AArch64, which rounds twice. Rounding x to odd on the multiples of 2^11 where
+// |x| >= 2^53 makes the conversion to double exact and leaves a direct conversion unchanged.
+template <typename OldType>
+struct cast_impl<OldType, float, std::enable_if_t<std::is_integral<OldType>::value && sizeof(OldType) == 8>> {
+  EIGEN_DEVICE_FUNC static inline float run(const OldType& x) {
+    using U = std::make_unsigned_t<OldType>;
+    const U u = static_cast<U>(x);
+    // In two's complement, clearing the low bits rounds toward -inf for either sign; setting bit 11 then picks the odd
+    // neighbor.
+    const U low = 0x7ff;
+    const U odd = (u & ~low) | ((u & low) != 0 ? U(0x800) : U(0));
+    const U magnitude = std::is_signed<OldType>::value && (u >> 63) != 0 ? U(0) - u : u;
+    return static_cast<float>(magnitude >= (U(1) << 53) ? numext::bit_cast<OldType>(odd) : x);
+  }
+};
+#endif
+
 // Returns NewType directly to avoid unintended intermediate conversions.
 
 template <typename OldType, typename NewType>
diff --git a/Eigen/src/Core/arch/Default/GenericPacketMathComplex.h b/Eigen/src/Core/arch/Default/GenericPacketMathComplex.h
index 350eb87..4c237f8 100644
--- a/Eigen/src/Core/arch/Default/GenericPacketMathComplex.h
+++ b/Eigen/src/Core/arch/Default/GenericPacketMathComplex.h
@@ -73,9 +73,11 @@
   const RealScalar hi = numext::sqrt(NumTraits<RealScalar>::highest()) / RealScalar(2);
   const RealPacket is_large = pcmp_lt(pset1<RealPacket>(hi), x_max);
   const RealPacket is_small = pcmp_lt(x_max, pset1<RealPacket>(lo));
-  const RealPacket k_large = pset1<RealPacket>(RealScalar(NumTraits<RealScalar>::max_exponent() / 2 + 2));
-  const RealPacket k_small = pset1<RealPacket>(
-      RealScalar(-((3 * NumTraits<RealScalar>::digits() - NumTraits<RealScalar>::min_exponent() - 1) / 2)));
+  // Both divisions round down: for double, k_small = -589 maps denorm_min = 2^-1074 exactly onto lo = 2^-485.
+  constexpr int kLarge = NumTraits<RealScalar>::max_exponent() / 2 + 2;
+  constexpr int kSmall = -((3 * NumTraits<RealScalar>::digits() - NumTraits<RealScalar>::min_exponent() - 1) / 2);
+  const RealPacket k_large = pset1<RealPacket>(RealScalar(kLarge));
+  const RealPacket k_small = pset1<RealPacket>(RealScalar(kSmall));
   const RealPacket cst_one = pset1<RealPacket>(RealScalar(1));
   const RealPacket k = pselect(is_large, k_large, pand(is_small, k_small));
   const RealPacket scale = pselect(is_large, pldexp_fast(cst_one, pnegate(k_large)),
diff --git a/Eigen/src/Core/arch/Default/Half.h b/Eigen/src/Core/arch/Default/Half.h
index aa4eaf3..807ee39 100644
--- a/Eigen/src/Core/arch/Default/Half.h
+++ b/Eigen/src/Core/arch/Default/Half.h
@@ -169,21 +169,62 @@
 EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC __half_raw float_to_half_rtne(float ff);
 EIGEN_STRONG_INLINE EIGEN_DEVICE_FUNC float half_to_float(__half_raw h);
 
-// Narrowing a wider floating-point value through float rounds twice. Rounding to odd in the first step keeps the
-// second rounding, to a format at least two bits narrower than float, correct.
+// Narrowing a wider floating-point value or an integer of more than 24 bits through float rounds twice. Rounding to
+// odd in the first step keeps the second rounding, to a format at least two bits narrower than float, correct.
+// Paths: 1 for wider floating-point types; 2 for integers of at most 32 bits, rounded to odd on the multiples of 2^8
+// where |x| >= 2^24, which float holds exactly and which keep a second rounding to p <= 15 bits correct (its midpoints
+// there are multiples of 2^(24 - p) >= 2^9), with no double arithmetic in device code; 3 for 64-bit integers, rounded
+// to odd on the multiples of 2^11 where |x| >= 2^53, which double holds exactly; 0 casts directly.
 template <typename T>
-EIGEN_DEVICE_FUNC inline std::enable_if_t<std::is_floating_point<T>::value && (sizeof(T) > sizeof(float)), float>
-narrow_to_float(const T& val) {
-  const float f = static_cast<float>(val);
-  if (static_cast<T>(f) == val || (numext::isnan)(val)) return f;
-  // Inexact: truncate toward zero, then set the last bit.
-  const bool away = numext::abs(static_cast<T>(f)) > numext::abs(val);
-  return numext::bit_cast<float>((numext::bit_cast<numext::uint32_t>(f) - (away ? 1u : 0u)) | 1u);
-}
+struct narrow_to_float_path
+    : std::integral_constant<int, std::is_floating_point<T>::value ? (sizeof(T) > sizeof(float) ? 1 : 0)
+                                  : !std::is_integral<T>::value || std::numeric_limits<T>::digits <= 24 ? 0
+                                  : std::numeric_limits<T>::digits <= 32                                ? 2
+                                  : std::numeric_limits<T>::digits <= 64                                ? 3
+                                                                                                        : 0> {};
+
+template <typename T, int Path = narrow_to_float_path<T>::value>
+struct narrow_to_float_impl {
+  EIGEN_DEVICE_FUNC static float run(const T& val) { return static_cast<float>(val); }
+};
 template <typename T>
-EIGEN_DEVICE_FUNC inline std::enable_if_t<!(std::is_floating_point<T>::value && (sizeof(T) > sizeof(float))), float>
-narrow_to_float(const T& val) {
-  return static_cast<float>(val);
+struct narrow_to_float_impl<T, 1> {
+  EIGEN_DEVICE_FUNC static float run(const T& val) {
+    const float f = static_cast<float>(val);
+    if (static_cast<T>(f) == val || (numext::isnan)(val)) return f;
+    // Inexact: truncate toward zero, then set the last bit.
+    const bool away = numext::abs(static_cast<T>(f)) > numext::abs(val);
+    return numext::bit_cast<float>((numext::bit_cast<numext::uint32_t>(f) - (away ? 1u : 0u)) | 1u);
+  }
+};
+// In two's complement, clearing the low bits rounds toward -inf for either sign; setting the next bit then picks the
+// odd neighbor.
+template <typename T>
+struct narrow_to_float_impl<T, 2> {
+  EIGEN_DEVICE_FUNC static float run(const T& val) {
+    using U = std::make_unsigned_t<T>;
+    const U u = static_cast<U>(val);
+    const U low = 0xff;
+    const U odd = (u & ~low) | ((u & low) != 0 ? U(0x100) : U(0));
+    const U magnitude = std::is_signed<T>::value && (u >> (sizeof(U) * CHAR_BIT - 1)) ? U(0) - u : u;
+    return static_cast<float>(magnitude >= (U(1) << 24) ? numext::bit_cast<T>(odd) : val);
+  }
+};
+template <typename T>
+struct narrow_to_float_impl<T, 3> {
+  EIGEN_DEVICE_FUNC static float run(const T& val) {
+    using U = std::make_unsigned_t<T>;
+    const U u = static_cast<U>(val);
+    const U low = 0x7ff;
+    const U odd = (u & ~low) | ((u & low) != 0 ? U(0x800) : U(0));
+    const U magnitude = std::is_signed<T>::value && (u >> (sizeof(U) * CHAR_BIT - 1)) ? U(0) - u : u;
+    return narrow_to_float_impl<double>::run(
+        static_cast<double>(magnitude >= (U(1) << 53) ? numext::bit_cast<T>(odd) : val));
+  }
+};
+template <typename T>
+EIGEN_DEVICE_FUNC inline float narrow_to_float(const T& val) {
+  return narrow_to_float_impl<T>::run(val);
 }
 
 struct half_base : public __half_raw {
@@ -247,9 +288,13 @@
 
   explicit EIGEN_DEVICE_FUNC _EIGEN_MAYBE_CONSTEXPR half(bool b)
       : half_impl::half_base(half_impl::raw_uint16_to_half(b ? 0x3c00 : 0)) {}
-  template <class T>
+  template <class T, std::enable_if_t<!std::is_integral<T>::value, int> = 0>
   explicit EIGEN_DEVICE_FUNC half(T val)
       : half_impl::half_base(half_impl::float_to_half_rtne(half_impl::narrow_to_float(val))) {}
+  // Float rounds only integers beyond 2^24, which half overflows either way.
+  template <class T, std::enable_if_t<std::is_integral<T>::value, int> = 0>
+  explicit EIGEN_DEVICE_FUNC half(T val)
+      : half_impl::half_base(half_impl::float_to_half_rtne(static_cast<float>(val))) {}
   explicit EIGEN_DEVICE_FUNC half(float f) : half_impl::half_base(half_impl::float_to_half_rtne(f)) {}
 
   // Following the convention of numpy, converting between complex and
diff --git a/Eigen/src/Core/arch/clang/TypeCasting.h b/Eigen/src/Core/arch/clang/TypeCasting.h
index f7d6dae..fd69684 100644
--- a/Eigen/src/Core/arch/clang/TypeCasting.h
+++ b/Eigen/src/Core/arch/clang/TypeCasting.h
@@ -80,6 +80,26 @@
 }
 
 template <>
+struct type_casting_traits<numext::int64_t, float> {
+  static constexpr int VectorizedCast = 1, SrcCoeffRatio = 2, TgtCoeffRatio = 1;
+};
+// Clang before 21 lowers an int64 -> float vector conversion through double on AArch64, which rounds twice. Rounding x
+// to odd on the multiples of 2^11 where |x| >= 2^53 makes that intermediate exact, and leaves a direct conversion
+// unchanged.
+template <>
+EIGEN_STRONG_INLINE PacketXf pcast<PacketXl, PacketXf>(const PacketXl& a, const PacketXl& b) {
+  using HalfFloat = detail::half_vector_t<PacketXf>;
+  const auto round_to_odd = [](const PacketXl& x) {
+    const PacketXl low = PacketXl(0x7ff);
+    const PacketXl odd = (x & ~low) | ((x & low) != 0 ? PacketXl(0x800) : PacketXl(0));
+    const PacketXl limit = PacketXl(int64_t(1) << 53);
+    return ((x >= limit) | (x <= -limit)) ? odd : x;
+  };
+  return detail::concat_halves<PacketXf>(__builtin_convertvector(round_to_odd(a), HalfFloat),
+                                         __builtin_convertvector(round_to_odd(b), HalfFloat));
+}
+
+template <>
 EIGEN_STRONG_INLINE PacketXl pcast<PacketXi, PacketXl>(const PacketXi& a) {
   return __builtin_convertvector(detail::lower_half(a), PacketXl);
 }
diff --git a/test/array_cwise.cpp b/test/array_cwise.cpp
index 3cb60af..b1ce0f2 100644
--- a/test/array_cwise.cpp
+++ b/test/array_cwise.cpp
@@ -1468,18 +1468,28 @@
 }
 
 // cast_test compares approximately. A 64-bit integer must round to float once: 2^60 + 2^36 + 1 rounds up, but
-// rounding through double first lands on the midpoint 2^60 + 2^36, which ties down to 2^60.
-template <typename = void>
-void int64_to_float_cast_test() {
-  const int64_t big = (int64_t(1) << 60) + (int64_t(1) << 36) + 1;
-  const ArrayX<int64_t> a =
-      ArrayX<int64_t>::LinSpaced(17, 0, 16).unaryExpr([&](int64_t i) { return i % 2 ? big : -big; });
-  const ArrayXf f = a.cast<float>(), g = a.abs().cast<uint64_t>().cast<float>();
+// rounding through double first lands on the midpoint 2^60 + 2^36, which ties down to 2^60. Clang before 21 converts
+// that way on AArch64 when it vectorizes a scalar loop: without explicit vectorization, for a type with no vectorized
+// cast, for the unrolled remainder of a fixed size (14 in the generic backend with 16-byte vectors), and for
+// complex<float>, which no backend casts to from int64.
+template <typename T, int Size>
+void int64_to_float_cast_test(Index size = Size) {
+  const bool is_signed = std::is_signed<T>::value;
+  // Read through volatile: EIGEN_OPTIMIZATION_BARRIER is empty on MSVC, which folds constant conversions through
+  // double.
+  const volatile T big_source = (T(1) << 60) + (T(1) << 36) + 1;
+  const T big = big_source;
+  Array<T, Size, 1> a;
+  a.resize(size);
+  for (Index i = 0; i < a.size(); ++i) a(i) = is_signed && i % 2 == 0 ? T(0) - big : big;
+  const Array<float, Size, 1> f = a.template cast<float>();
+  const Array<std::complex<float>, Size, 1> c = a.template cast<std::complex<float>>();
   // 2^60 + 2^37, spelled exactly: MSVC folds a constant int64-to-float conversion through double.
   const float rounded = std::ldexp(1.f + std::ldexp(1.f, -23), 60);
   for (Index i = 0; i < a.size(); ++i) {
-    VERIFY_IS_EQUAL(f(i), i % 2 ? rounded : -rounded);
-    VERIFY_IS_EQUAL(g(i), rounded);
+    const float expected = is_signed && i % 2 == 0 ? -rounded : rounded;
+    VERIFY_IS_EQUAL(f(i), expected);
+    VERIFY_IS_EQUAL(c(i), std::complex<float>(expected, 0.f));
   }
 }
 
@@ -1687,9 +1697,15 @@
     CALL_SUBTEST_28((cast_truncation_test<double, 8>()));
     CALL_SUBTEST_28((cast_truncation_test<double, 16>()));
     CALL_SUBTEST_28((cast_truncation_test<float, 16>()));
-    CALL_SUBTEST_28(int64_to_float_cast_test<>());
+    // QEMU, which runs the ppc64le tests, emulates xscvsxdsp and xscvuxdsp through double, so they round twice.
+#if !EIGEN_ARCH_PPC
+    CALL_SUBTEST_28((int64_to_float_cast_test<int64_t, Dynamic>(17)));
+    CALL_SUBTEST_28((int64_to_float_cast_test<int64_t, 14>()));
     CALL_SUBTEST_28(int64_to_float_midpoint_cast_test<int64_t>());
+    CALL_SUBTEST_28((int64_to_float_cast_test<uint64_t, Dynamic>(17)));
+    CALL_SUBTEST_28((int64_to_float_cast_test<uint64_t, 14>()));
     CALL_SUBTEST_28(int64_to_float_midpoint_cast_test<uint64_t>());
+#endif
     CALL_SUBTEST_29((cast_test<3, 1>()));
     CALL_SUBTEST_30((cast_test<5, 1>()));
     CALL_SUBTEST_31((cast_test<9, 1>()));
diff --git a/test/bfloat16_float.cpp b/test/bfloat16_float.cpp
index a255f30..1d04cc6 100644
--- a/test/bfloat16_float.cpp
+++ b/test/bfloat16_float.cpp
@@ -75,6 +75,33 @@
                              0xbf81);
   VERIFY_BFLOAT16_BITS_EQUAL(bfloat16(std::complex<double>(1.0 + std::ldexp(1.0, -8) + std::ldexp(1.0, -40), 0.0)),
                              0x3f81);
+  // Beyond float's range a double overflows to infinity or underflows to zero, keeping its sign. A bfloat16 subnormal
+  // just above the midpoint 2.5 * 2^-133 rounds up, although the excess is below float's subnormal spacing 2^-149.
+  VERIFY_BFLOAT16_BITS_EQUAL(bfloat16(1e39), 0x7f80);
+  VERIFY_BFLOAT16_BITS_EQUAL(bfloat16(-1e39), 0xff80);
+  VERIFY_BFLOAT16_BITS_EQUAL(bfloat16(1e-300), 0x0000);
+  VERIFY_BFLOAT16_BITS_EQUAL(bfloat16(-1e-300), 0x8000);
+  VERIFY_BFLOAT16_BITS_EQUAL(bfloat16(std::ldexp(2.5, -133) + std::ldexp(1.0, -160)), 0x0003);
+  VERIFY((numext::isnan)(bfloat16(std::numeric_limits<double>::quiet_NaN())));
+
+  // An integer of more than 24 bits rounds once too: just above the midpoint 2^30 + 2^22 it rounds up, although its
+  // float rounding is the midpoint. Just below a midpoint, 2^30 + 3 * 2^22 - 1 and -(2^62 + 3 * 2^54 - 1) round toward
+  // zero, and 2^53 + 1 and the extremes of the integer types round to the nearest power of two.
+  VERIFY_BFLOAT16_BITS_EQUAL(bfloat16(int32_t((1 << 30) + (1 << 22) + 1)), 0x4e81);
+  VERIFY_BFLOAT16_BITS_EQUAL(bfloat16(int32_t(-((1 << 30) + (1 << 22) + 1))), 0xce81);
+  VERIFY_BFLOAT16_BITS_EQUAL(bfloat16(int32_t((1 << 30) + 3 * (1 << 22) - 1)), 0x4e81);
+  VERIFY_BFLOAT16_BITS_EQUAL(bfloat16(int32_t((1 << 24) + (1 << 16) + 1)), 0x4b81);
+  VERIFY_BFLOAT16_BITS_EQUAL(bfloat16(std::numeric_limits<int32_t>::lowest()), 0xcf00);
+  VERIFY_BFLOAT16_BITS_EQUAL(bfloat16((std::numeric_limits<uint32_t>::max)()), 0x4f80);
+  VERIFY_BFLOAT16_BITS_EQUAL(bfloat16(uint32_t((1u << 31) + (1u << 23) + 1)), 0x4f01);
+  VERIFY_BFLOAT16_BITS_EQUAL(bfloat16(-((int64_t(1) << 40) + (int64_t(1) << 32) + 1)), 0xd381);
+  VERIFY_BFLOAT16_BITS_EQUAL(bfloat16(-((int64_t(1) << 60) + (int64_t(1) << 52) + 1)), 0xdd81);
+  VERIFY_BFLOAT16_BITS_EQUAL(bfloat16((uint64_t(1) << 63) + (uint64_t(1) << 55) + 1), 0x5f01);
+  VERIFY_BFLOAT16_BITS_EQUAL(bfloat16(-((int64_t(1) << 62) + 3 * (int64_t(1) << 54) - 1)), 0xde81);
+  VERIFY_BFLOAT16_BITS_EQUAL(bfloat16((int64_t(1) << 53) + 1), 0x5a00);
+  VERIFY_BFLOAT16_BITS_EQUAL(bfloat16(std::numeric_limits<int64_t>::lowest()), 0xdf00);
+  VERIFY_BFLOAT16_BITS_EQUAL(bfloat16((std::numeric_limits<int64_t>::max)()), 0x5f00);
+  VERIFY_BFLOAT16_BITS_EQUAL(bfloat16((std::numeric_limits<uint64_t>::max)()), 0x5f80);
 
   // Conversion from int.
   VERIFY_BFLOAT16_BITS_EQUAL(bfloat16(-1), 0xbf80);
diff --git a/test/half_float.cpp b/test/half_float.cpp
index e566d38..92da5c5 100644
--- a/test/half_float.cpp
+++ b/test/half_float.cpp
@@ -116,6 +116,16 @@
   VERIFY_IS_EQUAL(
       numext::bit_cast<numext::uint16_t>(half(std::complex<double>(std::ldexp(1.0, -25) + std::ldexp(1.0, -60)))),
       0x0001);
+  // Beyond float's range a double overflows to infinity or underflows to zero, keeping its sign.
+  VERIFY_IS_EQUAL(numext::bit_cast<numext::uint16_t>(half(1e39)), 0x7c00);
+  VERIFY_IS_EQUAL(numext::bit_cast<numext::uint16_t>(half(-1e39)), 0xfc00);
+  VERIFY_IS_EQUAL(numext::bit_cast<numext::uint16_t>(half(1e-300)), 0x0000);
+  VERIFY_IS_EQUAL(numext::bit_cast<numext::uint16_t>(half(-1e-300)), 0x8000);
+  VERIFY((numext::isnan)(half(std::numeric_limits<double>::quiet_NaN())));
+  // Integers convert through float directly: those it rounds overflow half anyway.
+  VERIFY_IS_EQUAL(numext::bit_cast<numext::uint16_t>(half(int32_t(65519))), 0x7bff);
+  VERIFY_IS_EQUAL(numext::bit_cast<numext::uint16_t>(half(-int64_t(65520))), 0xfc00);
+  VERIFY_IS_EQUAL(numext::bit_cast<numext::uint16_t>(half((std::numeric_limits<uint64_t>::max)())), 0x7c00);
 }
 
 void test_numtraits() {
diff --git a/test/packetmath.cpp b/test/packetmath.cpp
index aef642f..57becb0 100644
--- a/test/packetmath.cpp
+++ b/test/packetmath.cpp
@@ -2313,6 +2313,23 @@
     VERIFY(test::areApprox(ref, pval, PacketSize) && "pcplxflip");
   }
 
+  // pcmp_eq is true for a complex element only where both components are equal: data2[i] - data1[i] is (0, 0), (1, 0)
+  // or (0, 1) as (i + shift) % 3 is 0, 1 or 2.
+  for (int shift = 0; shift < 3; ++shift) {
+    for (int i = 0; i < PacketSize; ++i) {
+      data1[i] = Scalar(RealScalar(i + 1), RealScalar(-i - 2));
+      const int k = (i + shift) % 3;
+      data2[i] = data1[i] + Scalar(RealScalar(k == 1), RealScalar(k == 2));
+    }
+    const Packet a = internal::pload<Packet>(data1);
+    internal::pstore(pval, internal::pcmp_eq(a, internal::pload<Packet>(data2)));
+    internal::pstore(ref, internal::ptrue(a));
+    for (int i = 0; i < PacketSize; ++i) {
+      if ((i + shift) % 3 != 0) ref[i] = Scalar(0);
+    }
+    VERIFY(test::areEqualBits(ref, pval, PacketSize, false) && "pcmp_eq");
+  }
+
   const RealScalar zero = RealScalar(0);
   const RealScalar one = RealScalar(1);
   const RealScalar inf = std::numeric_limits<RealScalar>::infinity();