SuperDex Physics C++ API
Loading...
Searching...
No Matches
simd_inl.h
Go to the documentation of this file.
1/*
2 * Copyright (c) Meta Platforms, Inc. and affiliates.
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#pragma once
18
21
22#include <array>
23#include <cmath>
24#include <cstring>
25#include <limits>
26#include <type_traits>
27#include <utility>
28
29// Reverse include for intellisense
30#include "../simd.h"
31
32namespace superdex {
33
34namespace details {
35#if MOCHI_ARCH_X64_SVML
36inline constexpr bool kUseSvml = true;
37#else
38inline constexpr bool kUseSvml = false;
39#endif
40} // namespace details
41
42/***********************************************************************************************
43 Overloaded Operators for Simd<T, N>
44*/
45
46// Defines operators like += for Simd types. The right hand side can be any type as long as
47// the corresponding binary operator (e.g. operator+) exists.
48#define MOCHI_DEFINE_SIMD_OP_EQ(OP_EQ, OP) \
49 template <class T, int N, class RHS> \
50 MOCHI_ANY MOCHI_FORCE_INLINE Simd<T, N>& operator OP_EQ(Simd<T, N>& lhs, RHS rhs) { \
51 lhs = lhs OP rhs; \
52 return lhs; \
53 }
54
55// Defines binary operators between Simd<T, N> and T (either order).
56#define MOCHI_DEFINE_MIXED_SIMD_SCALAR_OP(OP) \
57 template <class T, int N> \
58 MOCHI_ANY MOCHI_FORCE_INLINE auto operator OP(Simd<T, N> lhs, T rhs) { \
59 return lhs OP Simd<T, N>{rhs}; \
60 } \
61 template <class T, int N> \
62 MOCHI_ANY MOCHI_FORCE_INLINE auto operator OP(T lhs, Simd<T, N> rhs) { \
63 return Simd<T, N>{lhs} OP rhs; \
64 }
65
73#undef MOCHI_DEFINE_SIMD_OP_EQ
74
79#undef MOCHI_DEFINE_MIXED_SIMD_SCALAR_OP
80
81namespace details {
82// Returns true if every lane is either all-bits-0 (logical false) or all-bits-1 (logical true).
83template <class T, int N>
84[[nodiscard]] MOCHI_ANY MOCHI_FORCE_INLINE bool IsValidLogicalMask(Simd<T, N> a) {
85 static_assert(sizeof(T) == sizeof(int) || sizeof(T) == sizeof(int64_t));
86 using I = std::conditional_t<sizeof(T) == sizeof(int), int, int64_t>;
87 using IVec = Simd<I, N>;
88 auto const ia = ReinterpretCast<IVec>(a);
89 auto const zero = IVec{};
90 auto const ones = ~zero;
91 // The free AllTrue asserts IsValidLogicalMask, so calling it here would recurse.
92 return IVec::template AllTrue<N>(VEqual(ia, zero) | VEqual(ia, ones));
93}
94} // namespace details
95
96template <class T, int N>
99 superdex::details::IsValidLogicalMask(lhs) && superdex::details::IsValidLogicalMask(rhs),
100 "operator&& requires all lanes to have all-bits-0 or all-bits-1");
101 return lhs & rhs;
102}
103
104template <class T, int N>
107 superdex::details::IsValidLogicalMask(lhs) && superdex::details::IsValidLogicalMask(rhs),
108 "operator|| requires all lanes to have all-bits-0 or all-bits-1");
109 return lhs | rhs;
110}
111
112/***********************************************************************************************
113 Simd Function Definitions
114*/
115
116template <class V, MOCHI_CONCEPT_DEF(IsSimd<V>)>
117MOCHI_ANY MOCHI_FORCE_INLINE V Broadcast(typename V::Scalar a) {
118 return V{a};
119}
120
121// Default implementation for most vector type
122template <class V, MOCHI_CONCEPT_DEF(IsSimd<V>)>
123MOCHI_ANY MOCHI_FORCE_INLINE V Broadcast(typename V::Scalar const* p) {
124 return V::Broadcast(p);
125}
126
127template <int i, class T, int N>
131
132template <class T, int N>
134 // TODO: Other implementations may be faster for specific vector sizes, but this covers the bases.
135 return Simd<T, N>{v[i]};
136}
137
138template <class V, class... MoreBools>
139MOCHI_ANY MOCHI_FORCE_INLINE V SimdMask(bool b0, bool b1, MoreBools... bs) {
140 static_assert(V::kSize == sizeof...(bs) + 2, "Incorrect number of arguments");
141 using I = std::conditional_t<sizeof(typename V::Scalar) == sizeof(int), int, int64_t>;
142 using IVec = Simd<I, V::kSize>;
143 constexpr I kSimdBool[2] = {0, -1}; // false, true
144 return ReinterpretCast<V>(IVec{kSimdBool[b0], kSimdBool[b1], kSimdBool[bs]...});
145}
146
147template <class V>
149 return V::Zero();
150}
151
152template <int i, class V>
154 return V::template SetBasisVector<i>();
155}
156
157template <class V>
159 static_assert(V::kSize == 4, "Unsupported SIMD size");
160 switch (axis) {
161 case 0:
162 return V::template SetBasisVector<0>();
163 case 1:
164 return V::template SetBasisVector<1>();
165 case 2:
166 return V::template SetBasisVector<2>();
167 case 3:
168 return V::template SetBasisVector<3>();
169 default:
170 MOCHI_ASSERT(axis >= 0 && axis <= 3, "Invalid component index");
171 return {};
172 }
173}
174
175template <class V>
177 return V::AsPoint(a);
178}
179
180template <class V>
182 return V::AsDirection(a);
183}
184
185template <class V, MOCHI_CONCEPT_DEF(IsSimd<V>)>
186MOCHI_ANY MOCHI_FORCE_INLINE V Load(typename V::Scalar const* ptr) {
187 return V::template Load<V::kSize>(ptr);
188}
189
190template <int N, class V, MOCHI_CONCEPT_DEF(IsSimd<V>)>
191MOCHI_ANY MOCHI_FORCE_INLINE V Load(typename V::Scalar const* ptr) {
192 return V::template Load<N>(ptr);
193}
194
195template <class V, MOCHI_CONCEPT_DEF(IsSimd<V>)>
196MOCHI_ANY MOCHI_FORCE_INLINE V Load(typename V::Scalar const* ptr, int n) {
197 return V::Load(ptr, n);
198}
199
200template <class V, class I, MOCHI_CONCEPT_DEF(IsSimd<V>)>
202LoadIndexed(typename V::Scalar const* ptr, Simd<I, V::kSize> indices) {
203 static_assert(std::is_integral_v<I>, "Requires integral type");
204 return V::LoadIndexed(ptr, indices);
205}
206
207template <int kTupleCount, class T, int N>
209LoadTransposed(T const* ptr, Simd<T, N>& out0, Simd<T, N>& out1, Simd<T, N>& out2) {
210 constexpr int kTupleCount_ = (kTupleCount == -1) ? N : kTupleCount;
212}
213
214template <class T, int N>
216LoadTransposed(T const* ptr, Simd<T, N>& out0, Simd<T, N>& out1, Simd<T, N>& out2, int count) {
217 Simd<T, N>::LoadTransposed(ptr, out0, out1, out2, count);
218}
219
220template <int COUNT, class T, int N>
222 constexpr int COUNT_ = (COUNT == -1) ? N : COUNT;
224}
225
226template <class T, int N>
227MOCHI_ANY MOCHI_FORCE_INLINE void Store(T* ptr, Simd<T, N> a, int count) {
228 Simd<T, N>::Store(ptr, a, count);
229}
230
231template <class T, int N, class MaskT>
233StoreSelected(T* ptr, Simd<MaskT, N> condition, Simd<T, N> values) {
235 superdex::details::IsValidLogicalMask(condition),
236 "Not a valid logical mask. Each lane must be all-bits-0 or all-bits-1.");
237 if constexpr (sizeof(MaskT) == 8 && sizeof(T) == 4) { // Example: MaskT = double, T = int
238 auto conditionI64 = ReinterpretCast<Simd<int64_t, N>>(condition);
239 auto conditionI32 = StaticCast<Simd<int, N>>(conditionI64);
241 (conditionI32 == StaticCast<Simd<int, N>>(conditionI64 & int64_t(0x00000000FFFFFFFFLL))),
242 "Expected StaticCast from int64_t to int32_t to return the lower 32 bits. This is not guaranteed by the C++ standard for static_cast, "
243 "but it is guaranteed by the x64 and ARM implementations. Your new CPU architecture behaves differenty. Therefore, this code will "
244 "need to perform a masking operation, or use Simd<uint64_t, N> and Simd<uint32_t, N> (not supported at the time of writing).");
245 return Simd<T, N>::StoreSelected(ptr, ReinterpretCast<Simd<T, N>>(conditionI32), values);
246 } else {
247 return Simd<T, N>::StoreSelected(ptr, ReinterpretCast<Simd<T, N>>(condition), values);
248 }
249}
250
251template <int kTupleCount, class T, int N>
254 constexpr int kTupleCount_ = (kTupleCount == -1) ? N : kTupleCount;
256}
257
258template <class T, int N>
260StoreTransposed(T* ptr, Simd<T, N> a, Simd<T, N> b, Simd<T, N> c, int count) {
261 Simd<T, N>::StoreTransposed(ptr, a, b, c, count);
262}
263
264template <class T, int N, class MaskT>
268 superdex::details::IsValidLogicalMask(conditionMask),
269 "Not a valid logical mask. Each lane must be all-bits-0 or all-bits-1.");
270 return Simd<T, N>::Select(ReinterpretCast<Simd<T, N>>(conditionMask), a, b);
271}
272
273template <int kShift, class T, int N>
275 static_assert(
276 Simd<T, N>::kIsSupported && std::is_integral_v<T> && std::is_signed_v<T>,
277 "ShiftRight requires a supported signed integer Simd type");
278 static_assert(kShift >= 0 && kShift < (8 * sizeof(T)), "Shift amount out-of-range");
279 if constexpr (kShift == 0) {
280 return a;
281 } else {
283 }
284}
285
286template <int x, int y, class T>
290
291template <int x, int y, int z, int w, class T>
295
296template <int x, int y, int z, int w, class T>
300
301template <int x, int y, class T, int N>
305
306template <int x, int y, int z, int w, class T, int N>
310
311template <class T, int N>
315
316template <int i, class T, int N>
320
321template <int iHalf, class T, int N>
325
326template <int i, class T, int N>
327[[nodiscard]] Simd<T, N> Set(Simd<T, N> a, T value) {
328 return Simd<T, N>::template Set<i>(a, value);
329}
330
331template <class T, int N>
332[[nodiscard]] MOCHI_ANY MOCHI_FORCE_INLINE Simd<T, N> Set(Simd<T, N> a, int i, T value) {
333 return Simd<T, N>::Set(a, i, value);
334}
335
336template <class V>
338 using T = typename V::Scalar;
339 static_assert(V::kIsSupported && std::is_integral_v<T>, "Must be a supported integral Simd type");
340 if constexpr (V::kIsComposite) {
341 return V::Sequence();
342 } else {
343 alignas(V) T constexpr kSequence[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15};
344 static_assert(
345 std::size(kSequence) >= V::kSize,
346 "Vector size is too large. Size of kSequence must be increased.");
347 return V::template Load<V::kSize>(kSequence);
348 }
349}
350
351template <bool x, bool y, bool z, bool w, class T, int N>
353 static_assert(
354 std::is_floating_point_v<T> && (N == 4),
355 "This implementation is intended for Vec4f or Vec4d only");
356 return Blend<x, y, z, w>(a, -a);
357}
358
359template <class T, int N>
361 static_assert(std::is_floating_point_v<T>, "Requires float or double");
362 return Simd<T, N>::Sqrt(a);
363}
364
365template <class T, int N>
369
370template <class T, int N>
374
375template <class T, int N>
379
380template <class T, int N>
384
385template <class T, int N>
389
390template <int COUNT, class T, int N>
392 constexpr int COUNT_ = (COUNT == -1) ? N : COUNT;
393 if constexpr (COUNT_ == 1) {
394 return Get0(a);
395 } else {
397 }
398}
399
400template <class T>
404
405namespace details {
406// True if V has its own HSumEach of four vectors, which the generic HSumEach then prefers. A vector
407// that declares HSumEach at sizes it doesn't support must constrain it in the declaration, as the
408// composite and emulated vectors do: this detection can't see a static_assert in the body.
409template <class V, class = void>
410inline constexpr bool kHasOwnHSumEach = false;
411template <class V>
412inline constexpr bool kHasOwnHSumEach<
413 V,
414 std::void_t<decltype(V::HSumEach(
415 std::declval<V>(),
416 std::declval<V>(),
417 std::declval<V>(),
418 std::declval<V>()))>> = true;
419} // namespace details
420
421template <class T, int N>
424 static_assert(kHasHSumEach<Simd<T, N>>, "Unsupported N");
425 if constexpr (N == 4) {
426 return Simd<T, 4>::HSumEach(a, b, c, d);
427 } else if constexpr (details::kHasOwnHSumEach<Simd<T, N>>) {
428 // Wider vectors with their own reduction (x64 Vec8f, and Vec8d with AVX-512) reduce at full
429 // width, in fewer instructions than adding the halves of each vector first.
430 return Simd<T, N>::HSumEach(a, b, c, d);
431 } else {
432 return HSumEach(
433 GetHalf<0>(a) + GetHalf<1>(a),
434 GetHalf<0>(b) + GetHalf<1>(b),
435 GetHalf<0>(c) + GetHalf<1>(c),
436 GetHalf<0>(d) + GetHalf<1>(d));
437 }
438}
439
440template <int COUNT, class T, int N>
442 constexpr int COUNT_ = (COUNT == -1) ? N : COUNT;
443 if constexpr (COUNT_ == 1) {
444 return Get0(a);
445 } else {
447 }
448}
449
450template <int COUNT, class T, int N>
452 constexpr int COUNT_ = (COUNT == -1) ? N : COUNT;
453 if constexpr (COUNT_ == 1) {
454 return Get0(a);
455 } else {
457 }
458}
459
460template <int COUNT, class T, int N>
462 constexpr int COUNT_ = (COUNT == -1) ? N : COUNT;
463 if constexpr (COUNT_ == 1) {
464 return Get0(a);
465 } else {
467 }
468}
469
470#define MOCHI_SIMD_MEMBERWISE_FALLBACK(T, N, FN, inVec) \
471 ([&]() { \
472 alignas(alignof(Simd<T, N>)) T buf[N]; \
473 Store(buf, inVec); \
474 for (int i = 0; i < N; ++i) { \
475 buf[i] = FN(buf[i]); \
476 } \
477 return Load<Simd<T, N>>(buf); \
478 }())
479
480template <class T, int N>
484
485template <class T, int N>
489
490namespace details {
491// We have a custom SIMD implementation of single-precision sine and cosine. These are computed by
492// summing the first few terms of the Taylor series. The problem is that precision decreases as
493// abs(x) increases. Therefore, the first step is to reduce the range of x. Depending on the
494// quadrant, we may return either the sine or the cosine, and we may need to flip the sign. All of
495// this can be done quickly with branchless SIMD instructions.
496//
497// Some details of this implementation were inspired by code provided by ARM Software:
498// https://github.com/ARM-software/optimized-routines
499//
500template <int N>
502SinCosImpl(Simd<float, N> xf, Simd<float, N>& outSin, Simd<float, N>& outCos, Simd<int, N>& outN) {
503 // Convert to double precision
504 auto x = StaticCast<Simd<double, N>>(xf);
505
506 // Reduce x to [-pi/4, pi/4] in quadrant n
507 auto r = FastRound(x * 0x1.45f306dc9c883p-1); // round(x * (2/pi))
508 outN = StaticCast<Simd<int, N>>(r);
509 x = x - r * 0x1.921fb54442d18p0; // x - n * (pi/2)
510
511 // Compute Taylor series for both sin and cos
512 auto x2 = x * x; // x^2
513 auto x3 = x * x2; // x^3
514 auto x4 = x2 * x2; // x^4
515 auto s1 = 0x1.1107605230bc4p-7 - x2 * 0x1.994eb3774cf24p-13; // 1/5! - (x^2)/7!
516 auto c1 = 1.0 - x2 * 0.5;
517 auto c2 = -0x1.6c087e89a359dp-10 + x2 * 0x1.99343027bf8c3p-16; // -1/6! + (x^2)/8!
518 auto x5 = x3 * x2; // x^5
519 auto x6 = x4 * x2; // x^6
520 auto s0 = x - x3 * 0x1.555545995a603p-3; // x - (x^3)/3!
521 auto c0 = c1 + x4 * 0x1.55553e1068f19p-5; // 1 - (x^2)/2! + (x^4)/4!
522
523 // outSin = x - (x^3)/3! + (x^5)/5! - (x^7)/7!
524 outSin = StaticCast<Simd<float, N>>(s0 + x5 * s1);
525
526 // outCos = 1 - (x^2)/2! + (x^4)/4! - (x^6)/6! + (x^8)/8!
527 outCos = StaticCast<Simd<float, N>>(c0 + x6 * c2);
528}
529
530// Preserve the documented accuracy bound and keep the quadrant index
531// representable by falling back for larger inputs.
532inline constexpr float kMaxFastSinCosInput = 1e6f;
533
534template <int N>
535MOCHI_ANY MOCHI_FORCE_INLINE bool IsFastSinCosInput(Simd<float, N> a) {
536 return AllTrue(Abs(a) <= Simd<float, N>{kMaxFastSinCosInput});
537}
538} // namespace details
539
540template <class T, int N>
542 // TODO: When C++20 syntax in this header is legal, gate based on whether Simd<T, N>::Cos() is
543 // implemented. Same for all other functions with a SIMD memberwise fallback.
544 if constexpr (details::kUseSvml || Simd<T, N>::kIsEmulated) {
545 // There are x64 intrinsics if SVML extension is available
546 return Simd<T, N>::Cos(a);
547 } else if constexpr (std::is_same_v<T, float>) {
548 if (!details::IsFastSinCosInput(a)) MOCHI_UNLIKELY {
549 return MOCHI_SIMD_MEMBERWISE_FALLBACK(T, N, std::cos, a);
550 }
551 // Reduce x to [-pi/4, pi/4) in quadrant n and compute Taylor series
552 Simd<float, N> sin, cos;
553 Simd<int, N> n;
554 details::SinCosImpl(a, sin, cos, n);
555 // Use bitwise ops to select cos for (n == 0) || (n == 2). Else select sin.
556 auto result = Select((n & 1) - 1, cos, sin);
557 // Then flip the sign if (n == 1) || (n == 2).
558 return result ^ ReinterpretCast<Simd<float, N>>((n ^ ShiftRight<1>(n)) << 31);
559 } else {
560 return MOCHI_SIMD_MEMBERWISE_FALLBACK(T, N, std::cos, a); // Fallback
561 }
562}
563
564template <class T, int N>
566 if constexpr (details::kUseSvml || Simd<T, N>::kIsEmulated) {
567 // There are x64 intrinsics if SVML extension is available
568 return Simd<T, N>::Sin(a);
569 } else if constexpr (std::is_same_v<T, float>) {
570 if (!details::IsFastSinCosInput(a)) MOCHI_UNLIKELY {
571 return MOCHI_SIMD_MEMBERWISE_FALLBACK(T, N, std::sin, a);
572 }
573 // Reduce x to [-pi/4, pi/4) in quadrant n and compute Taylor series
574 Simd<T, N> sin, cos;
575 Simd<int, N> n;
576 details::SinCosImpl(a, sin, cos, n);
577 // Use bitwise ops to select sin for (n == 0) || (n == 2). Else select cos.
578 auto result = Select((n & 1) - 1, sin, cos);
579 // Then flip the sign if (n == 2) || (n == 3).
580 return result ^ ReinterpretCast<Simd<T, N>>(ShiftRight<1>(n) << 31);
581 } else {
582 return MOCHI_SIMD_MEMBERWISE_FALLBACK(T, N, std::sin, a);
583 }
584}
585
586template <class T, int N>
587inline std::pair<Simd<T, N>, Simd<T, N>> SinCos(Simd<T, N> a) {
588 // Our custom single-precision implementation can efficiently compute sin and cos at the same
589 // time. However, we still use call Sin and Cos separately when they are implemented with SVML, so
590 // that the results will be exactly the same.
591 if constexpr (!MOCHI_ARCH_X64_SVML && std::is_same_v<T, float>) {
592 if (!details::IsFastSinCosInput(a)) MOCHI_UNLIKELY {
593 return {Sin(a), Cos(a)};
594 }
595 Simd<float, N> sin, cos;
596 Simd<int, N> n;
597 details::SinCosImpl(a, sin, cos, n);
598 auto mask = ReinterpretCast<Simd<float, N>>((n & 1) - 1);
599 auto nr = ShiftRight<1>(n);
600 auto sresult = Select(mask, sin, cos) ^ ReinterpretCast<Simd<float, N>>(nr << 31);
601 auto cresult = Select(mask, cos, sin) ^ ReinterpretCast<Simd<float, N>>((n ^ nr) << 31);
602 return {sresult, cresult};
603 } else {
604 return {Sin(a), Cos(a)};
605 }
606}
607
608template <class T, int N>
610 if constexpr (details::kUseSvml || Simd<T, N>::kIsEmulated) {
611 // Simd<T, N>::Tan only implemented in this case.
612 return Simd<T, N>::Tan(a);
613 } else {
614 return MOCHI_SIMD_MEMBERWISE_FALLBACK(T, N, std::tan, a);
615 }
616}
617
618template <class T, int N>
620 if constexpr (details::kUseSvml || Simd<T, N>::kIsEmulated) {
621 // Simd<T, N>::ACos only implemented in this case.
622 return Simd<T, N>::ACos(a);
623 } else {
624 return MOCHI_SIMD_MEMBERWISE_FALLBACK(T, N, std::acos, a);
625 }
626}
627
628template <class T, int N>
630 if constexpr (details::kUseSvml || Simd<T, N>::kIsEmulated) {
631 // Simd<T, N>::ASin only implemented in this case.
632 return Simd<T, N>::ASin(a);
633 } else {
634 return MOCHI_SIMD_MEMBERWISE_FALLBACK(T, N, std::asin, a);
635 }
636}
637
638template <class T, int N>
640 if constexpr (details::kUseSvml || Simd<T, N>::kIsEmulated) {
641 // Simd<T, N>::ATan only implemented in this case.
642 return Simd<T, N>::ATan(a);
643 } else {
644 return MOCHI_SIMD_MEMBERWISE_FALLBACK(T, N, std::atan, a);
645 }
646}
647
648template <class T, int N>
650 if constexpr (details::kUseSvml || Simd<T, N>::kIsEmulated) {
651 // Simd<T, N>::Exp only implemented in this case.
652 return Simd<T, N>::Exp(a);
653 } else {
654 // exp(a) = 2^n exp(x), with n = round(a / ln(2)) and |x| <= ln(2) / 2. On that interval,
655 // 1 + x + x^2 P(x) is a minimax approximation of exp(x), with P of degree 4 for float and 9 for
656 // double, and relative errors of 3.8e-9 and 1.1e-17.
657 using V = Simd<T, N>;
658 using VI = Simd<std::conditional_t<std::is_same_v<T, float>, int32_t, int64_t>, N>;
659 using I = typename VI::Scalar;
660 constexpr int kMantissaBits = std::numeric_limits<T>::digits - 1;
661 constexpr int kExponentBias = std::numeric_limits<T>::max_exponent - 1;
662 constexpr T kInvLn2 = T(1) / kLn2<T>;
663
664 // Clamping `a` to [-kExponentBias ln(2), (kExponentBias + 1) ln(2)] bounds `n` to
665 // [-kExponentBias, kExponentBias + 1], at whose ends the 2^n built below is 0 and inf. A NaN
666 // `a` fails both comparisons, so it propagates.
667 V const lo(T(-kExponentBias) * kLn2<T>);
668 V const hi(T(kExponentBias + 1) * kLn2<T>);
669 V clamped = Select(a < lo, lo, a);
670 clamped = Select(clamped > hi, hi, clamped);
671
672 // Adding 1.5 * 2^kMantissaBits + kExponentBias rounds `clamped` / ln(2) to the integer `n` and
673 // leaves n + kExponentBias, the biased exponent of 2^n, in the low mantissa bits of `t`. ln(2)
674 // is split into a short high part, whose product with `n` is exact, and a small low part.
675 V const shift(T(1.5) * static_cast<T>(I{1} << kMantissaBits) + T(kExponentBias));
676 V const t = clamped * kInvLn2 + shift;
677 V const n = t - shift;
678 V x = clamped - n * T(0.693145751953125);
679 x -= n * T(1.42860682030941723212e-6);
680
681 V const z = x * x;
682 V p;
683 if constexpr (std::is_same_v<T, float>) {
684 V const p01 = x * T(1.6666521e-1) + T(4.9999994e-1);
685 V const p23 = x * T(8.36871e-3) + T(4.166839e-2);
686 p = p01 + z * (p23 + z * T(1.3814613e-3));
687 } else {
688 static_assert(std::is_same_v<T, double>);
689 V const z2 = z * z;
690 V const p01 = x * T(1.6666666666666413e-1) + T(5.000000000000011e-1);
691 V const p23 = x * T(8.33333333349434e-3) + T(4.166666666653026e-2);
692 V const p45 = x * T(1.98412695067651e-4) + T(1.3888888943598715e-3);
693 V const p67 = x * T(2.755758627776603e-6) + T(2.4801493135021792e-5);
694 V const p89 = x * T(2.500006925707656e-8) + T(2.763023436834589e-7);
695 p = (p23 * z + p01) + z2 * ((p67 * z + p45) + z2 * p89);
696 }
697
698 // 2^n, from its biased exponent in the low bits of `t`.
699 V const scale = ReinterpretCast<V>(ReinterpretCast<VI>(t) << kMantissaBits);
700 return (p * z + x + T(1)) * scale;
701 }
702}
703
704template <class T, int N>
706 if constexpr (details::kUseSvml || Simd<T, N>::kIsEmulated) {
707 // Simd<T, N>::Ln only implemented in this case.
708 return Simd<T, N>::Ln(a);
709 } else {
710 // Cephes logf.c (float) and log.c (double,
711 // https://github.com/jeremybarnes/cephes/blob/master/cmath/log.c): for a = m 2^e with m in
712 // [sqrt(1/2), sqrt(2)), ln(a) = ln(1 + x) + e ln(2), where x = m - 1 and
713 // ln(1 + x) = x - x^2 / 2 + x^3 R(x). Cephes log switches to another approximation for
714 // |e| > 2; this one serves every e. ln(2) is split into a short high part, whose product with
715 // e is exact, and a small low part.
716 using V = Simd<T, N>;
717 using VI = Simd<std::conditional_t<std::is_same_v<T, float>, int32_t, int64_t>, N>;
718 using I = typename VI::Scalar;
719 constexpr int kMantissaBits = std::numeric_limits<T>::digits - 1;
720 constexpr int kExponentBias = std::numeric_limits<T>::max_exponent - 1;
721 V const one(T(1));
722
723 // Scale denormals into the normal range.
724 V const twoToMantissaBits(static_cast<T>(I{1} << kMantissaBits));
725 V const isDenormal = a < V(std::numeric_limits<T>::min());
726 VI const bits = ReinterpretCast<VI>(a * Select(isDenormal, twoToMantissaBits, one));
727
728 // m and e from the bits of a > 0 minus those of sqrt(1/2): their exponent field is e plus the
729 // bias, and their mantissa field, added to the bits of sqrt(1/2), gives m. OR-ing the exponent
730 // field into the mantissa of 2^kMantissaBits turns it into a value of T without an integer
731 // conversion.
732 VI const sqrtHalfBits = ReinterpretCast<VI>(V(T(0.707106781186547524)));
733 VI const reducedBits = bits - (sqrtHalfBits - VI(I{kExponentBias} << kMantissaBits));
734 V const x =
735 ReinterpretCast<V>((reducedBits & VI((I{1} << kMantissaBits) - 1)) + sqrtHalfBits) - one;
736 V e = ReinterpretCast<V>(
737 ShiftRight<kMantissaBits>(reducedBits) | ReinterpretCast<VI>(twoToMantissaBits)) -
738 (twoToMantissaBits + T(kExponentBias));
739 e -= isDenormal & V(T(kMantissaBits));
740
741 V const z = x * x;
742 V y;
743 if constexpr (std::is_same_v<T, float>) {
744 y = x * T(7.0376836292e-2) - T(1.1514610310e-1);
745 y = y * x + T(1.1676998740e-1);
746 y = y * x - T(1.2420140846e-1);
747 y = y * x + T(1.4249322787e-1);
748 y = y * x - T(1.6668057665e-1);
749 y = y * x + T(2.0000714765e-1);
750 y = y * x - T(2.4999993993e-1);
751 y = y * x + T(3.3333331174e-1);
752 y = y * x * z;
753 } else {
754 static_assert(std::is_same_v<T, double>);
755 V p = x * T(1.01875663804580931796e-4) + T(4.97494994976747001425e-1);
756 p = p * x + T(4.70579119878881725854e0);
757 p = p * x + T(1.44989225341610930846e1);
758 p = p * x + T(1.79368678507819816313e1);
759 p = p * x + T(7.70838733755885391666e0);
760
761 V q = x + T(1.12873587189167450590e1);
762 q = q * x + T(4.52279145837532221105e1);
763 q = q * x + T(8.29875266912776603211e1);
764 q = q * x + T(7.11544750618563894466e1);
765 q = q * x + T(2.31251620126765340583e1);
766 y = x * (z * p / q);
767 }
768
769 y -= e * T(2.121944400546905827679e-4);
770 y -= z * T(0.5);
771 V const result = x + y + e * T(0.693359375);
772
773 // ln(0) = -inf, ln(inf) = inf, and ln(a) is NaN for a < 0 and a NaN.
774 V const infinity(std::numeric_limits<T>::infinity());
775 return Select(
776 a >= V(T(0)),
777 Select(VEqual(a, V(T(0))), -infinity, Select(VEqual(a, infinity), infinity, result)),
778 V(std::numeric_limits<T>::quiet_NaN()));
779 }
780}
781
782template <class T, int N>
784 if constexpr (details::kUseSvml || Simd<T, N>::kIsEmulated) {
785 // Simd<T, N>::Tanh only implemented in this case.
786 return Simd<T, N>::Tanh(a);
787 } else {
788 return MOCHI_SIMD_MEMBERWISE_FALLBACK(T, N, std::tanh, a);
789 }
790}
791
792#undef MOCHI_SIMD_MEMBERWISE_FALLBACK
793
794template <class V>
796 return V::Equal(a, b);
797}
798
799template <class V>
801 return V::NotEqual(a, b);
802}
803
804template <int COUNT, class T, int N>
806 if constexpr (COUNT == 1) {
807 return Get0(a) == Get0(b);
808 } else {
809 return AllTrue<COUNT>(VEqual(a, b));
810 }
811}
812
813template <int COUNT, class T, int N>
815#if MOCHI_PLATFORM_MACOS && MOCHI_ARCH_X64 && MOCHI_OPTIMIZED
816 // Work-around for a compiler bug in optimized builds on Intel macOS.
817 return !Equal<COUNT>(a, b);
818#else
819 if constexpr (COUNT == 1) {
820 return Get0(a) != Get0(b);
821 } else {
822 return AnyTrue<COUNT>(VNotEqual(a, b));
823 }
824#endif
825}
826
827template <class V>
829 return Abs(a - b) <= epsilon;
830}
831
832template <class V>
834 return Abs(a) <= epsilon;
835}
836
837template <int COUNT, class T, int N>
839 constexpr int COUNT_ = (COUNT == -1) ? N : COUNT; // -1 means "all"
840 // IsValidLogicalMask needs 4- or 8-byte lanes, so Simd<Half, N> masks go unchecked.
841 if constexpr (sizeof(T) == sizeof(int) || sizeof(T) == sizeof(int64_t)) {
843 superdex::details::IsValidLogicalMask(a),
844 "Not a valid logical mask. Each lane must be all-bits-0 or all-bits-1.");
845 }
847}
848
849template <int COUNT, class T, int N>
851 constexpr int COUNT_ = (COUNT == -1) ? N : COUNT; // -1 means "all"
852 // IsValidLogicalMask needs 4- or 8-byte lanes, so Simd<Half, N> masks go unchecked.
853 if constexpr (sizeof(T) == sizeof(int) || sizeof(T) == sizeof(int64_t)) {
855 superdex::details::IsValidLogicalMask(a),
856 "Not a valid logical mask. Each lane must be all-bits-0 or all-bits-1.");
857 }
859}
860
861template <class T, int N>
863 if constexpr (std::is_same_v<T, float>) {
864 constexpr int kMask = 0x7F800000; // These bits set for inf and NaN variants
865 auto mask = Simd<int, N>{kMask};
866 return ReinterpretCast<Simd<T, N>>(VNotEqual(ReinterpretCast<Simd<int, N>>(a) & mask, mask));
867 } else {
868 static_assert(std::is_same_v<T, double>, "VIsFinite only supports float and double.");
869 constexpr int kMask = 0x7FF00000; // These bits set for inf and NaN variants
870 if constexpr (N == 2 && Simd<int, 4>::kIsSupported) {
871 // Use an Int4 mask. Result comes from the 2 that correspond to the high bits of each
872 // double.
873 auto mask = Simd<int, 4>{kMask};
874 auto temp4i32 = VNotEqual(ReinterpretCast<Simd<int, 4>>(a) & mask, mask);
875 auto temp2i64 = Shuffle<1, 1, 3, 3>(temp4i32);
876 return ReinterpretCast<Simd<double, 2>>(temp2i64);
877 } else if constexpr (N == 4 && Simd<int, 8>::kIsSupported) {
878 // Use an int8 mask. Result comes from the 4 that correspond to the high bits of each
879 // double.
880 auto mask = Simd<int, 8>{kMask};
881 auto temp8i32 = VNotEqual(ReinterpretCast<Simd<int, 8>>(a) & mask, mask);
882 auto low2i64 = Shuffle<1, 1, 3, 3>(GetHalf<0>(temp8i32)); // no 8-way shuffle currently
883 auto high2i64 = Shuffle<1, 1, 3, 3>(GetHalf<1>(temp8i32));
884 auto temp4i64 = Simd<int, 8>(low2i64, high2i64);
885 return ReinterpretCast<Simd<double, 4>>(temp4i64);
886 } else if constexpr (N == 8 && Simd<int64_t, 8>::kIsSupported) {
887 auto mask = Simd<int64_t, 8>{INT64_C(0x7FF0000000000000)};
888 auto bits = ReinterpretCast<Simd<int64_t, 8>>(a);
889 return ReinterpretCast<Simd<double, 8>>(VNotEqual(bits & mask, mask));
890 } else if constexpr (Simd<T, N>::kIsComposite) {
891 return Simd<T, N>{VIsFinite(a.first), VIsFinite(a.second)};
892 } else if constexpr (!MOCHI_USE_SIMD) {
893 // Simd Emulated
894 Simd<T, N> result;
895 for (int i = 0; i < N; ++i) {
896 uint64_t isFinite = -static_cast<uint64_t>(IsFinite(a.raw[i])); // true = -1, false = 0
897 memcpy(&result.raw[i], &isFinite, sizeof(T));
898 }
899 return result;
900 } else {
901 static_assert(std::is_void_v<T>, "Unsupported type or size");
902 }
903 }
904}
905
906template <int i, class T, int N>
908 // The bits of mask[i] should be all zeros for "false", or all ones for "true". Therefore we can
909 // test any byte(s) within mask[i]. We never return a floating-point type so that the caller
910 // doesn't have to worry about comparisons with NaN.
911 constexpr int kNumInts{(sizeof(T) * N) / sizeof(int)};
912 constexpr int kStride = kNumInts / N;
913 return Get<i * kStride>(ReinterpretCast<Simd<int, kNumInts>>(mask));
914}
915
916template <class T, int N>
920
921template <class T, int N>
925
926template <class T, int N>
930
931template <class T, int N>
935
936template <int COUNT, class V>
938 constexpr int COUNT_ = (COUNT == -1) ? V::kSize : COUNT;
939 if constexpr (COUNT_ == 1) {
940 return Broadcast<0>(a * b);
941 } else {
942 return V::template Dot<COUNT_>(a, b);
943 }
944}
945
946template <class T, int N>
950
951template <int COUNT, class T, int N>
953 static_assert(COUNT == -1 || COUNT >= 2, "Unsupported COUNT");
954 static_assert(std::is_floating_point_v<T>, "Requires float or double");
955 return VDot<COUNT>(a, a);
956}
957
958template <int COUNT, class T, int N>
962
963template <int COUNT, class T, int N>
967
968template <int COUNT, class T, int N>
972
973template <int COUNT, class T, int N>
975 // By adding the smallest possible scalar we prevent divide-by-zero and get a zero vector result
976 // There is no change in result for any vector longer than.... something very very very small
977 return a / (VNorm<COUNT>(a) + std::numeric_limits<T>::min());
978}
979
980template <class T, int N>
982 // By adding the smallest possible scalar we prevent divide-by-zero and get a zero vector result
983 // There is no change in result for any vector longer than.... something very very very small
984 return a / (Sqrt(normSqr) + std::numeric_limits<T>::min());
985}
986
987template <class T, int N>
989 return Normalize(a, Simd<T, N>{normSqr});
990}
991
992template <class T>
994 static_assert(std::is_floating_point_v<T>, "Requires float or double");
995
996 // Project the coordinate of the minimum absolute value
997 // then build the orthogonal vector in that subspace
998
999 // Compute mask selecting the minimum absolute value(s)
1000 auto abs = Abs(a);
1001 auto absMin = HMin<3>(abs);
1002
1003 // Build possible orthogonal vectors and select them according to the mask.
1004 a = ToSimdDirection(a);
1005 if (absMin == Get<0>(abs)) { // abs(v[0]) was the smallest value (or tied for smallest)
1007 } else if (absMin == Get<1>(abs)) { // abs(v[1]) was the smallest value (or tied for smallest)
1009 } else { // abs(v[2]) was the smallest value
1011 }
1012 return a;
1013}
1014
1015namespace details {
1016
1017/**
1018 Determines the smallest supported SIMD size that uses the minimum possible number of native
1019 registers for the requested lane count.
1020*/
1021template <typename T, int kSize, bool kExceedsNativeSize = (kSize > kSimdDefaultSize<T>)>
1022struct NextSupportedSimdSizeHelper;
1023
1024template <typename T, int kSize>
1025struct NextSupportedSimdSizeHelper<T, kSize, true> {
1026 static_assert(kSize > 0, "SIMD size must be positive.");
1027 static_assert(Simd<T>::kIsSupported, "Type T is not supported for any size N.");
1028 static constexpr int value =
1029 kSimdDefaultSize<T> + NextSupportedSimdSizeHelper<T, kSize - kSimdDefaultSize<T>>::value;
1030};
1031
1032template <typename T, int kSize>
1033struct NextSupportedSimdSizeHelper<T, kSize, false> {
1034 static_assert(kSize > 0, "SIMD size must be positive.");
1035 static_assert(Simd<T>::kIsSupported, "Type T is not supported for any size N.");
1036 static constexpr bool kIsSingleRegister =
1038 static constexpr int value = std::conditional_t<
1039 kIsSingleRegister,
1040 std::integral_constant<int, kSize>,
1041 NextSupportedSimdSizeHelper<T, kSize + 1>>::value;
1042};
1043
1044template <typename T, int kSize>
1045inline constexpr int kNextSupportedSimdSize = NextSupportedSimdSizeHelper<T, kSize>::value;
1046
1047} // namespace details
1048
1049} // namespace superdex
1050
1051/************************************************************************************
1052 Reflection support for Simd<T, N>
1053 Serializes like std::array<T, N>.
1054*/
1055#if MOCHI_USE_REFLECTION
1056template <typename T, int N>
1057struct SReflectTypeTraits<superdex::Simd<T, N>> {
1058 static constexpr SReflect::CoreType coreType = SReflect::CoreType::CT_array;
1059 static SReflect::ArrayTypeInfo const& GetTypeInfo() {
1060 static auto* s_typeInfo =
1061 SReflect::MakeFixedArrayTypeInfo<superdex::Simd<T, N>, T, N>("superdex::Simd", true);
1062 return *s_typeInfo;
1063 }
1064};
1065#endif // MOCHI_USE_REFLECTION
NativeType raw
Definition simd.h:174
static constexpr bool kIsComposite
Definition simd.h:98
static constexpr bool kIsEmulated
Definition simd.h:99
static constexpr bool kIsSupported
Definition simd.h:97
#define MOCHI_ASSERT(condition_without_side_effects,...)
Definition debug.h:81
#define MOCHI_ASSERT_VERBOSE(condition_without_side_effects,...)
Definition debug.h:102
#define MOCHI_USE_SIMD
#define MOCHI_UNLIKELY
#define MOCHI_ARCH_X64_SVML
#define MOCHI_FORCE_INLINE
#define MOCHI_ANY
T Dot(Simd< T, N > a, Simd< T, N > b)
Definition simd.h:710
constexpr T ACos(T a)
constexpr T NegMulAdd(T a, T b, T c)
Simd< T, N > VIsFinite(Simd< T, N > a)
Definition simd_inl.h:862
Simd< T, 2 > Shuffle(Simd< T, 2 > a)
Definition simd_inl.h:287
constexpr int kSimdDefaultSize
Definition simd.h:33
Simd< T, 2 > HSumEach(Simd< T, 2 > a, Simd< T, 2 > b)
Returns {HSum(a), HSum(b)}.
Definition simd_inl.h:401
V LoadIndexed(typename V::Scalar const *ptr, Simd< I, V::kSize > indices)
Definition simd_inl.h:202
constexpr T const & Min(T const &a, T const &b)
T NormSqr(Simd< T, N > a)
Definition simd_inl.h:964
constexpr auto Equal(T const &a, T const &b)
Simd< T, N > Cross3(Simd< T, N > a, Simd< T, N > b)
Definition simd_inl.h:947
constexpr T Sin(T a)
T HSum(Simd< T, N > a)
Definition simd_inl.h:391
constexpr To StaticCast(From const &a)
Definition basic_utils.h:79
V VDot(V a, V b)
Definition simd_inl.h:937
T HMin(Simd< T, N > a)
Definition simd_inl.h:451
T Norm(Simd< T, N > a)
Definition simd_inl.h:969
bool AllTrue(T const &a)
Definition basic_utils.h:60
constexpr T NegMulSub(T a, T b, T c)
V SimdBasisVector()
Definition simd_inl.h:153
Simd< T, N > Tanh(Simd< T, N > a)
Definition simd_inl.h:783
V VEqual(V a, V b)
Definition simd_inl.h:795
V ToSimdDirection(V a)
Definition simd_inl.h:181
Simd< T, N > Set(Simd< T, N > a, T value)
Definition simd_inl.h:327
V Sequence()
Definition simd_inl.h:337
constexpr auto NotEqual(T const &a, T const &b)
constexpr T Exp(T a)
constexpr T Cos(T a)
V VNearEqual(V a, V b, V epsilon)
Definition simd_inl.h:828
constexpr T kLn2
Definition constants.h:29
V SimdZero()
Definition simd_inl.h:148
T HMax(Simd< T, N > a)
Definition simd_inl.h:461
constexpr bool kHasHSumEach
True if HSumEach of four vectors of type V is supported.
Definition simd.h:533
Simd< T, N > VNormSqr(Simd< T, N > a)
Definition simd_inl.h:952
int IsTrue(Simd< T, N > mask)
Definition simd_inl.h:907
V Broadcast(typename V::Scalar a)
Definition simd_inl.h:117
constexpr T Abs(T a)
Definition basic_utils.h:50
V VNotEqual(V a, V b)
Definition simd_inl.h:800
constexpr T MulSub(T a, T b, T c)
Simd< T, N > Normalize(Simd< T, N > a)
Definition simd_inl.h:974
Simd< T, N > Blend(Simd< T, N > a, Simd< T, N > b)
Definition simd_inl.h:302
constexpr T Tan(T a)
bool AnyTrue(T const &a)
Definition basic_utils.h:66
constexpr T Select(bool condition, T a, T b)
constexpr T Sqrt(T a)
constexpr T ATan(T a)
Simd< T, N > Ln(Simd< T, N > a)
Definition simd_inl.h:705
std::pair< Simd< T, N >, Simd< T, N > > SinCos(Simd< T, N > a)
Definition simd_inl.h:587
T Get(Simd< T, N > v)
Definition simd_inl.h:317
constexpr T Floor(T a)
constexpr T ASin(T a)
Simd< T, N > operator||(Simd< T, N > lhs, Simd< T, N > rhs)
Definition simd_inl.h:105
Simd< T, N > operator&&(Simd< T, N > lhs, Simd< T, N > rhs)
Definition simd_inl.h:97
V SimdMask(bool b0, bool b1, MoreBools... bs)
Definition simd_inl.h:139
Simd< T, N/2 > GetHalf(Simd< T, N > a)
Definition simd_inl.h:322
T HProd(Simd< T, N > a)
Definition simd_inl.h:441
Simd< T, 4 > OrthogonalVector3(Simd< T, 4 > a)
T Get0(Simd< T, N > v)
Definition simd_inl.h:312
Simd< T, N > VNorm(Simd< T, N > a)
Definition simd_inl.h:959
constexpr T const & Max(T const &a, T const &b)
void LoadTransposed(T const *ptr, Simd< T, N > &out0, Simd< T, N > &out1, Simd< T, N > &out2)
Definition simd_inl.h:209
Simd< T, N > FastRound(Simd< T, N > a)
Definition simd_inl.h:486
void StoreTransposed(T *ptr, Simd< T, N > a, Simd< T, N > b, Simd< T, N > c)
Definition simd_inl.h:253
void Store(T *ptr, Simd< T, N > a)
Definition simd_inl.h:221
Simd< T, N > RcpSqrtApprox(Simd< T, N > a)
Definition simd_inl.h:371
constexpr T RcpApprox(T a)
constexpr T MulAdd(T a, T b, T c)
V VNearZero(V a, V epsilon)
Definition simd_inl.h:833
int StoreSelected(T *ptr, Simd< MaskT, N > condition, Simd< T, N > values)
Definition simd_inl.h:233
V Load(typename V::Scalar const *ptr)
Definition simd_inl.h:186
Simd< T, N > Neg(Simd< T, N > a)
Definition simd_inl.h:352
V ToSimdPoint(V a)
Definition simd_inl.h:176
bool IsFinite(TransformRT const &a)
Simd< T, N > ShiftRight(Simd< T, N > a)
Definition simd_inl.h:274
#define MOCHI_SIMD_MEMBERWISE_FALLBACK(T, N, FN, inVec)
Definition simd_inl.h:470
#define MOCHI_DEFINE_MIXED_SIMD_SCALAR_OP(OP)
Definition simd_inl.h:56
#define MOCHI_DEFINE_SIMD_OP_EQ(OP_EQ, OP)
Definition simd_inl.h:48