Core: Split the exponent directly in the generic packet cbrt

libeigen/eigen!3661

Co-authored-by: Rasmus Munk Larsen <rmlarsen@gmail.com>
diff --git a/Eigen/src/Core/arch/Default/GenericPacketMathPow.h b/Eigen/src/Core/arch/Default/GenericPacketMathPow.h
index 5659911..2f75b6a 100644
--- a/Eigen/src/Core/arch/Default/GenericPacketMathPow.h
+++ b/Eigen/src/Core/arch/Default/GenericPacketMathPow.h
@@ -57,39 +57,58 @@
   }
 }
 
-// Decompose the input such that x^(1/3) = y^(1/3) * 2^e_div3, and y is in the
-// interval [0.125,1].
+// Returns y in [1/8, 1) and sets e_div3 such that |x|^(1/3) = y^(1/3) * 2^e_div3, given abs_x = |x|. Sets
+// pass_through in the lanes where x is zero, infinite or NaN, whose cube root is x. In those lanes y and e_div3 are
+// finite but meaningless.
 template <typename Packet>
-EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet cbrt_decompose(const Packet& x, Packet& e_div3) {
+EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet cbrt_decompose(const Packet& abs_x, Packet& e_div3,
+                                                                          Packet& pass_through) {
   using Scalar = typename unpacket_traits<Packet>::type;
-  // Extract the significand s in the range [0.5,1) and exponent e, such that
-  // x = 2^e * s.
-  Packet e, s;
-  s = pfrexp(x, e);
+  using ScalarUI = std::make_unsigned_t<typename make_integer<Scalar>::type>;
+  static constexpr int kMantissaBits = numext::numeric_limits<Scalar>::digits - 1;
+  static constexpr int kExponentBits = sizeof(Scalar) * CHAR_BIT - kMantissaBits - 1;
+  static constexpr int kMaxBiasedExponent = (1 << kExponentBits) - 1;
+  static constexpr int kExponentBias = kMaxBiasedExponent / 2;
 
-  // Split the exponent into a part divisible by 3 and the remainder.
-  // e = 3*e_div3 + e_mod3.
+  // |x| = s * 2^e with s in [0.5, 1). For a normal x with biased exponent E, s has the significand bits of x and
+  // e = E - (kExponentBias - 1).
+  Packet normalized = abs_x;
+  Packet biased_exponent = pfrexp_generic_get_biased_exponent(abs_x);
+  Packet exponent_offset = pset1<Packet>(Scalar(1 - kExponentBias));
+  const Packet is_zero = pcmp_eq(abs_x, pzero(abs_x));
+  const Packet is_not_finite = pcmp_eq(biased_exponent, pset1<Packet>(Scalar(kMaxBiasedExponent)));
+  pass_through = por(is_zero, is_not_finite);
+
+  // Subnormals are rare, so only a packet that holds one pays for scaling it: a subnormal times
+  // 2^(kMantissaBits + 1) is normal.
+  const Packet is_subnormal = pandnot(pcmp_eq(biased_exponent, pzero(abs_x)), is_zero);
+  if (predux_any(is_subnormal)) {
+    // The other lanes are scaled by 1, so that a large finite one does not overflow.
+    const Packet scale =
+        pselect(is_subnormal, pset1<Packet>(Scalar(ScalarUI(1) << (kMantissaBits + 1))), pset1<Packet>(Scalar(1)));
+    normalized = pmul(abs_x, scale);
+    biased_exponent = pfrexp_generic_get_biased_exponent(normalized);
+    exponent_offset =
+        pselect(is_subnormal, pset1<Packet>(Scalar(1 - kExponentBias - (kMantissaBits + 1))), exponent_offset);
+  }
+  const Packet e = padd(biased_exponent, exponent_offset);
+  const Packet mantissa_mask = pset1frombits<Packet>((ScalarUI(1) << kMantissaBits) - 1);
+  const Packet s = por(pand(normalized, mantissa_mask), pset1<Packet>(Scalar(0.5)));
+
+  // e = 3 * e_div3 + e_mod3 with e_mod3 in {-2, -1, 0}, and y = s * 2^e_mod3.
   constexpr Scalar kOneThird = Scalar(1) / 3;
   e_div3 = pceil(pmul(e, pset1<Packet>(kOneThird)));
-  Packet e_mod3 = pnmadd(pset1<Packet>(Scalar(3)), e_div3, e);
-
-  // Replace s by y = (s * 2^e_mod3).
+  const Packet e_mod3 = pnmadd(pset1<Packet>(Scalar(3)), e_div3, e);
   return pldexp_fast(s, e_mod3);
 }
 
+// Returns abs_root with the sign of x, or x itself where pass_through, as set by cbrt_decompose, says so.
 template <typename Packet>
 EIGEN_DEFINE_FUNCTION_ALLOWING_MULTIPLE_DEFINITIONS Packet cbrt_special_cases_and_sign(const Packet& x,
-                                                                                       const Packet& abs_root) {
-  // Set sign.
-  const Packet sign_mask = psignmask<Packet>();
-  const Packet x_sign = pand(sign_mask, x);
-  Packet root = por(x_sign, abs_root);
-
-  // Pass non-finite and zero values of x straight through.
-  const Packet is_not_finite = por(pisinf(x), pisnan(x));
-  const Packet is_zero = pcmp_eq(pzero(x), x);
-  const Packet use_x = por(is_not_finite, is_zero);
-  return pselect(use_x, x, root);
+                                                                                       const Packet& abs_root,
+                                                                                       const Packet& pass_through) {
+  const Packet root = por(pand(psignmask<Packet>(), x), abs_root);
+  return pselect(pass_through, x, root);
 }
 
 // Generic implementation of cbrt(x) for float.
@@ -126,10 +145,8 @@
   using Scalar = typename unpacket_traits<Packet>::type;
   static_assert(std::is_same<Scalar, float>::value, "Scalar type must be float");
 
-  // Decompose the input such that x^(1/3) = y^(1/3) * 2^e_div3, and y is in the
-  // interval [0.125,1].
-  Packet e_div3;
-  const Packet y = cbrt_decompose(pabs(x), e_div3);
+  Packet e_div3, pass_through;
+  const Packet y = cbrt_decompose(pabs(x), e_div3, pass_through);
 
   // Initial approximation with relative error <= 1.87e-3, which one Halley step reduces to 0.07 ULP. Sollya 8.0:
   //   fpminimax(x^(1/3), 4, [|single...|], [1/8; 1], relative, floating);
@@ -142,8 +159,7 @@
 
   // Finally multiply by 2^(e_div3)
   r = pldexp_fast(r, e_div3);
-
-  return cbrt_special_cases_and_sign(x, r);
+  return cbrt_special_cases_and_sign(x, r, pass_through);
 }
 
 // Generic implementation of cbrt(x) for double.
@@ -158,10 +174,8 @@
   using Scalar = typename unpacket_traits<Packet>::type;
   static_assert(std::is_same<Scalar, double>::value, "Scalar type must be double");
 
-  // Decompose the input such that x^(1/3) = y^(1/3) * 2^e_div3, and y is in the
-  // interval [0.125,1].
-  Packet e_div3;
-  const Packet y = cbrt_decompose(pabs(x), e_div3);
+  Packet e_div3, pass_through;
+  const Packet y = cbrt_decompose(pabs(x), e_div3, pass_through);
 
   // Initial approximation with relative error <= 5.22e-3, which two Halley steps reduce to 6e-22. Sollya 8.0:
   //   fpminimax(x^(1/3), 3, [|double...|], [1/8; 1], relative, floating);
@@ -176,7 +190,7 @@
 
   // Finally multiply by 2^(e_div3).
   r = pldexp_fast(r, e_div3);
-  return cbrt_special_cases_and_sign(x, r);
+  return cbrt_special_cases_and_sign(x, r, pass_through);
 }
 
 //----------------------------------------------------------------------
diff --git a/test/packetmath.cpp b/test/packetmath.cpp
index e0ae5db..d9211ae 100644
--- a/test/packetmath.cpp
+++ b/test/packetmath.cpp
@@ -1434,6 +1434,87 @@
   }
 }
 
+// pcbrt passes zero, infinite and NaN lanes through and scales subnormal lanes on a branch that the whole packet
+// takes. Each lane of a packet that mixes such lanes with regular ones, or with each other, must get its own cube
+// root. Every finite input is m^3 * 2^(3k), whose root m * 2^k is exact.
+template <typename Scalar, typename Packet, std::enable_if_t<!bool(internal::packet_traits<Scalar>::HasCbrt), int> = 0>
+void packetmath_cbrt_mixed_lanes() {}
+
+template <typename Scalar, typename Packet, std::enable_if_t<bool(internal::packet_traits<Scalar>::HasCbrt), int> = 0>
+void packetmath_cbrt_mixed_lanes() {
+  using Case = std::pair<Scalar, Scalar>;  // an input and its cube root
+  const test::packet_helper<true, Packet> h;
+  const int PacketSize = internal::unpacket_traits<Packet>::size;
+  EIGEN_ALIGN_TO_BOUNDARY(internal::unpacket_traits<Packet>::alignment) Scalar data1[PacketSize];
+  EIGEN_ALIGN_TO_BOUNDARY(internal::unpacket_traits<Packet>::alignment) Scalar data2[PacketSize];
+  EIGEN_ALIGN_TO_BOUNDARY(internal::unpacket_traits<Packet>::alignment) Scalar ref[PacketSize];
+  const auto cube = [](int m, int k) {
+    return Case(std::ldexp(Scalar(m) * Scalar(m) * Scalar(m), 3 * k), std::ldexp(Scalar(m), k));
+  };
+
+  std::vector<Case> regular;
+  for (int i = 0; i < PacketSize; ++i) {
+    const Case c = cube(3 + 2 * (i % 32), i % 5 - 2);
+    regular.push_back((i % 2 == 0) ? c : Case(-c.first, -c.second));
+  }
+
+  std::vector<Case> special{Case(Scalar(0), Scalar(0))};
+#if !EIGEN_ARCH_ARM  // 32-bit ARM flushes subnormals.
+  if (std::numeric_limits<Scalar>::has_denorm == std::denorm_present) {
+    // The smallest subnormal 2^(3k), and the largest subnormal m^3 * 2^(3k) for that k, which fills the significand.
+    constexpr int kDigits = std::numeric_limits<Scalar>::digits;
+    constexpr int kMinExponent = std::numeric_limits<Scalar>::min_exponent;
+    constexpr int kMinK = -((kDigits - kMinExponent) / 3);
+    const Scalar limit = std::ldexp(Scalar(1), kMinExponent - 1 - 3 * kMinK);
+    int m = 1;
+    while (Scalar(m + 2) * Scalar(m + 2) * Scalar(m + 2) < limit) m += 2;
+    special.push_back(cube(1, kMinK));
+    special.push_back(cube(m, kMinK));
+  }
+#endif
+  special.emplace_back(std::numeric_limits<Scalar>::infinity(), std::numeric_limits<Scalar>::infinity());
+  special.emplace_back(std::numeric_limits<Scalar>::quiet_NaN(), std::numeric_limits<Scalar>::quiet_NaN());
+  for (size_t i = 0, count = special.size(); i < count; ++i) {
+    special.emplace_back(-special[i].first, -special[i].second);
+  }
+
+  const auto check = [&]() {
+    h.store(data2, internal::pcbrt(h.load(data1)));
+    for (int i = 0; i < PacketSize; ++i) {
+      if ((numext::isnan)(ref[i])) {
+        VERIFY((numext::isnan)(data2[i]));
+      } else if ((numext::isinf)(ref[i]) || ref[i] == Scalar(0)) {
+        VERIFY(data2[i] == ref[i]);
+        VERIFY(((numext::signbit)(data2[i]) == Scalar(0)) == ((numext::signbit)(ref[i]) == Scalar(0)));
+      } else {
+        // The budget of packetmath_cbrt_accuracy.
+        VERIFY(test::areWithinUlps(&ref[i], &data2[i], 1, 1) && "pcbrt");
+      }
+    }
+  };
+
+  // One special lane among regular ones, in each position.
+  for (const Case& c : special) {
+    for (int lane = 0; lane < PacketSize; ++lane) {
+      for (int i = 0; i < PacketSize; ++i) {
+        const Case& lane_case = (i == lane) ? c : regular[i];
+        data1[i] = lane_case.first;
+        ref[i] = lane_case.second;
+      }
+      check();
+    }
+  }
+  // Special lanes only, of every kind that fits.
+  for (size_t shift = 0; shift < special.size(); ++shift) {
+    for (int i = 0; i < PacketSize; ++i) {
+      const Case& lane_case = special[(shift + static_cast<size_t>(i)) % special.size()];
+      data1[i] = lane_case.first;
+      ref[i] = lane_case.second;
+    }
+    check();
+  }
+}
+
 // Arguments and their correctly rounded expm1, MPFR 4.2.2 at 256-bit precision, each at least 0.1 ulp from a rounding
 // tie: tiny arguments on both sides of the threshold below which x is returned, both sides of the points +-ln(2)/2
 // where the multiple of ln(2) in the reduction changes, and the ends of the range, where the result is -1 or near the
@@ -1818,6 +1899,7 @@
   EIGEN_ALIGN_TO_BOUNDARY(unpacket_traits<Packet>::alignment) Scalar ref[PacketSize * 4] = {};
 
   if (g_first_pass) packetmath_cbrt_accuracy<Scalar, Packet>();
+  if (g_first_pass) packetmath_cbrt_mixed_lanes<Scalar, Packet>();
   if (g_first_pass) packetmath_expm1_accuracy<Scalar, Packet>();
   if (g_first_pass) packetmath_hyperbolic_accuracy<Scalar, Packet>();
   if (g_first_pass) {