Debian Codegraph @

src/base/SkVx.h

raw
1 /*
2 * Copyright 2019 Google Inc.
3 *
4 * Use of this source code is governed by a BSD-style license that can be
5 * found in the LICENSE file.
6 */
7
8 #ifndef SKVX_DEFINED
9 #define SKVX_DEFINED
10
11 // skvx::Vec<N,T> are SIMD vectors of N T's, a v1.5 successor to SkNx<N,T>.
12 //
13 // This time we're leaning a bit less on platform-specific intrinsics and a bit
14 // more on Clang/GCC vector extensions, but still keeping the option open to
15 // drop in platform-specific intrinsics, actually more easily than before.
16 //
17 // We've also fixed a few of the caveats that used to make SkNx awkward to work
18 // with across translation units. skvx::Vec<N,T> always has N*sizeof(T) size
19 // and alignment and is safe to use across translation units freely.
20 // (Ideally we'd only align to T, but that tanks ARMv7 NEON codegen.)
21
22 #include "include/private/base/SkFeatures.h"
23 #include "src/base/SkUtils.h"
24 #include <algorithm> // std::min, std::max
25 #include <cassert> // assert()
26 #include <cmath> // ceilf, floorf, truncf, roundf, sqrtf, etc.
27 #include <cstdint> // intXX_t
28 #include <cstring> // memcpy()
29 #include <initializer_list> // std::initializer_list
30 #include <type_traits>
31 #include <utility> // std::index_sequence
32
33 // Users may disable SIMD with SKNX_NO_SIMD, which may be set via compiler flags.
34 // The gn build has no option which sets SKNX_NO_SIMD.
35 // Use SKVX_USE_SIMD internally to avoid confusing double negation.
36 // Do not use 'defined' in a macro expansion.
37 #if !defined(SKNX_NO_SIMD)
38 #define SKVX_USE_SIMD 1
39 #else
40 #define SKVX_USE_SIMD 0
41 #endif
42
43 #if SKVX_USE_SIMD
44 #if SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_AVX
45 #include <immintrin.h>
46 #elif SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSE41
47 #include <smmintrin.h>
48 #elif SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSE1
49 #include <emmintrin.h>
50 #include <xmmintrin.h>
51 #elif defined(SK_ARM_HAS_NEON)
52 #include <arm_neon.h>
53 #elif defined(__wasm_simd128__)
54 #include <wasm_simd128.h>
55 #elif SK_CPU_LSX_LEVEL >= SK_CPU_LSX_LEVEL_LASX
56 #include <lasxintrin.h>
57 #include <lsxintrin.h>
58 #elif SK_CPU_LSX_LEVEL >= SK_CPU_LSX_LEVEL_LSX
59 #include <lsxintrin.h>
60 #endif
61 #endif
62
63 // To avoid ODR violations, all methods must be force-inlined...
64 #if defined(_MSC_VER)
65 #define SKVX_ALWAYS_INLINE __forceinline
66 #else
67 #define SKVX_ALWAYS_INLINE __attribute__((always_inline))
68 #endif
69
70 // ... and all standalone functions must be static. Please use these helpers:
71 #define SI static inline
72 #define SIT template < typename T> SI
73 #define SIN template <int N > SI
74 #define SINT template <int N, typename T> SI
75 #define SINTU template <int N, typename T, typename U, \
76 typename=std::enable_if_t<std::is_convertible<U,T>::value>> SI
77
78 namespace skvx {
79
80 template <int N, typename T>
81 struct alignas(N*sizeof(T)) Vec;
82
83 template <int... Ix, int N, typename T>
84 SI Vec<sizeof...(Ix),T> shuffle(const Vec<N,T>&);
85
86 // All Vec have the same simple memory layout, the same as `T vec[N]`.
87 template <int N, typename T>
88 struct alignas(N*sizeof(T)) Vec {
89 static_assert((N & (N-1)) == 0, "N must be a power of 2.");
90 static_assert(sizeof(T) >= alignof(T), "What kind of unusual T is this?");
91
92 // Methods belong here in the class declaration of Vec only if:
93 // - they must be here, like constructors or operator[];
94 // - they'll definitely never want a specialized implementation.
95 // Other operations on Vec should be defined outside the type.
96
97 SKVX_ALWAYS_INLINE Vec() = default;
98 SKVX_ALWAYS_INLINE Vec(T s) : lo(s), hi(s) {}
99
100 // NOTE: Vec{x} produces x000..., whereas Vec(x) produces xxxx.... since this constructor fills
101 // unspecified lanes with 0s, whereas the single T constructor fills all lanes with the value.
102 SKVX_ALWAYS_INLINE Vec(std::initializer_list<T> xs) {
103 T vals[N] = {0};
104 assert(xs.size() <= (size_t)N);
105 memcpy(vals, xs.begin(), std::min(xs.size(), (size_t)N)*sizeof(T));
106
107 this->lo = Vec<N/2,T>::Load(vals + 0);
108 this->hi = Vec<N/2,T>::Load(vals + N/2);
109 }
110
111 SKVX_ALWAYS_INLINE T operator[](int i) const { return i<N/2 ? this->lo[i] : this->hi[i-N/2]; }
112 SKVX_ALWAYS_INLINE T& operator[](int i) { return i<N/2 ? this->lo[i] : this->hi[i-N/2]; }
113
114 SKVX_ALWAYS_INLINE static Vec Load(const void* ptr) {
115 return sk_unaligned_load<Vec>(ptr);
116 }
117 SKVX_ALWAYS_INLINE void store(void* ptr) const {
118 // Note: Calling sk_unaligned_store produces slightly worse code here, for some reason
119 memcpy(ptr, this, sizeof(Vec));
120 }
121
122 Vec<N/2,T> lo, hi;
123 };
124
125 // We have specializations for N == 1 (the base-case), as well as 2 and 4, where we add helpful
126 // constructors and swizzle accessors.
127 template <typename T>
128 struct alignas(4*sizeof(T)) Vec<4,T> {
129 static_assert(sizeof(T) >= alignof(T), "What kind of unusual T is this?");
130
131 SKVX_ALWAYS_INLINE Vec() = default;
132 SKVX_ALWAYS_INLINE Vec(T s) : lo(s), hi(s) {}
133 SKVX_ALWAYS_INLINE Vec(T x, T y, T z, T w) : lo(x,y), hi(z,w) {}
134 SKVX_ALWAYS_INLINE Vec(Vec<2,T> xy, T z, T w) : lo(xy), hi(z,w) {}
135 SKVX_ALWAYS_INLINE Vec(T x, T y, Vec<2,T> zw) : lo(x,y), hi(zw) {}
136 SKVX_ALWAYS_INLINE Vec(Vec<2,T> xy, Vec<2,T> zw) : lo(xy), hi(zw) {}
137
138 SKVX_ALWAYS_INLINE Vec(std::initializer_list<T> xs) {
139 T vals[4] = {0};
140 assert(xs.size() <= (size_t)4);
141 memcpy(vals, xs.begin(), std::min(xs.size(), (size_t)4)*sizeof(T));
142
143 this->lo = Vec<2,T>::Load(vals + 0);
144 this->hi = Vec<2,T>::Load(vals + 2);
145 }
146
147 SKVX_ALWAYS_INLINE T operator[](int i) const { return i<2 ? this->lo[i] : this->hi[i-2]; }
148 SKVX_ALWAYS_INLINE T& operator[](int i) { return i<2 ? this->lo[i] : this->hi[i-2]; }
149
150 SKVX_ALWAYS_INLINE static Vec Load(const void* ptr) {
151 return sk_unaligned_load<Vec>(ptr);
152 }
153 SKVX_ALWAYS_INLINE void store(void* ptr) const {
154 memcpy(ptr, this, sizeof(Vec));
155 }
156
157 SKVX_ALWAYS_INLINE Vec<2,T>& xy() { return lo; }
158 SKVX_ALWAYS_INLINE Vec<2,T>& zw() { return hi; }
159 SKVX_ALWAYS_INLINE T& x() { return lo.lo.val; }
160 SKVX_ALWAYS_INLINE T& y() { return lo.hi.val; }
161 SKVX_ALWAYS_INLINE T& z() { return hi.lo.val; }
162 SKVX_ALWAYS_INLINE T& w() { return hi.hi.val; }
163
164 SKVX_ALWAYS_INLINE Vec<2,T> xy() const { return lo; }
165 SKVX_ALWAYS_INLINE Vec<2,T> zw() const { return hi; }
166 SKVX_ALWAYS_INLINE T x() const { return lo.lo.val; }
167 SKVX_ALWAYS_INLINE T y() const { return lo.hi.val; }
168 SKVX_ALWAYS_INLINE T z() const { return hi.lo.val; }
169 SKVX_ALWAYS_INLINE T w() const { return hi.hi.val; }
170
171 // Exchange-based swizzles. These should take 1 cycle on NEON and 3 (pipelined) cycles on SSE.
172 SKVX_ALWAYS_INLINE Vec<4,T> yxwz() const { return shuffle<1,0,3,2>(*this); }
173 SKVX_ALWAYS_INLINE Vec<4,T> zwxy() const { return shuffle<2,3,0,1>(*this); }
174
175 Vec<2,T> lo, hi;
176 };
177
178 template <typename T>
179 struct alignas(2*sizeof(T)) Vec<2,T> {
180 static_assert(sizeof(T) >= alignof(T), "What kind of unusual T is this?");
181
182 SKVX_ALWAYS_INLINE Vec() = default;
183 SKVX_ALWAYS_INLINE Vec(T s) : lo(s), hi(s) {}
184 SKVX_ALWAYS_INLINE Vec(T x, T y) : lo(x), hi(y) {}
185
186 SKVX_ALWAYS_INLINE Vec(std::initializer_list<T> xs) {
187 T vals[2] = {0};
188 assert(xs.size() <= (size_t)2);
189 memcpy(vals, xs.begin(), std::min(xs.size(), (size_t)2)*sizeof(T));
190
191 this->lo = Vec<1,T>::Load(vals + 0);
192 this->hi = Vec<1,T>::Load(vals + 1);
193 }
194
195 SKVX_ALWAYS_INLINE T operator[](int i) const { return i<1 ? this->lo[i] : this->hi[i-1]; }
196 SKVX_ALWAYS_INLINE T& operator[](int i) { return i<1 ? this->lo[i] : this->hi[i-1]; }
197
198 SKVX_ALWAYS_INLINE static Vec Load(const void* ptr) {
199 return sk_unaligned_load<Vec>(ptr);
200 }
201 SKVX_ALWAYS_INLINE void store(void* ptr) const {
202 memcpy(ptr, this, sizeof(Vec));
203 }
204
205 SKVX_ALWAYS_INLINE T& x() { return lo.val; }
206 SKVX_ALWAYS_INLINE T& y() { return hi.val; }
207
208 SKVX_ALWAYS_INLINE T x() const { return lo.val; }
209 SKVX_ALWAYS_INLINE T y() const { return hi.val; }
210
211 // This exchange-based swizzle should take 1 cycle on NEON and 3 (pipelined) cycles on SSE.
212 SKVX_ALWAYS_INLINE Vec<2,T> yx() const { return shuffle<1,0>(*this); }
213 SKVX_ALWAYS_INLINE Vec<4,T> xyxy() const { return Vec<4,T>(*this, *this); }
214
215 Vec<1,T> lo, hi;
216 };
217
218 template <typename T>
219 struct Vec<1,T> {
220 T val = {};
221
222 SKVX_ALWAYS_INLINE Vec() = default;
223 SKVX_ALWAYS_INLINE Vec(T s) : val(s) {}
224
225 SKVX_ALWAYS_INLINE Vec(std::initializer_list<T> xs) : val(xs.size() ? *xs.begin() : 0) {
226 assert(xs.size() <= (size_t)1);
227 }
228
229 SKVX_ALWAYS_INLINE T operator[](int i) const { assert(i == 0); return val; }
230 SKVX_ALWAYS_INLINE T& operator[](int i) { assert(i == 0); return val; }
231
232 SKVX_ALWAYS_INLINE static Vec Load(const void* ptr) {
233 return sk_unaligned_load<Vec>(ptr);
234 }
235 SKVX_ALWAYS_INLINE void store(void* ptr) const {
236 memcpy(ptr, this, sizeof(Vec));
237 }
238 };
239
240 // Translate from a value type T to its corresponding Mask, the result of a comparison.
241 template <typename T> struct Mask { using type = T; };
242 template <> struct Mask<float > { using type = int32_t; };
243 template <> struct Mask<double> { using type = int64_t; };
244 template <typename T> using M = typename Mask<T>::type;
245
246 // Join two Vec<N,T> into one Vec<2N,T>.
247 SINT Vec<2*N,T> join(const Vec<N,T>& lo, const Vec<N,T>& hi) {
248 Vec<2*N,T> v;
249 v.lo = lo;
250 v.hi = hi;
251 return v;
252 }
253
254 // We have three strategies for implementing Vec operations:
255 // 1) lean on Clang/GCC vector extensions when available;
256 // 2) use map() to apply a scalar function lane-wise;
257 // 3) recurse on lo/hi to scalar portable implementations.
258 // We can slot in platform-specific implementations as overloads for particular Vec<N,T>,
259 // or often integrate them directly into the recursion of style 3), allowing fine control.
260
261 #if SKVX_USE_SIMD && (defined(__clang__) || defined(__GNUC__))
262
263 // VExt<N,T> types have the same size as Vec<N,T> and support most operations directly.
264 #if defined(__clang__)
265 template <int N, typename T>
266 using VExt = T __attribute__((ext_vector_type(N)));
267
268 #elif defined(__GNUC__)
269 template <int N, typename T>
270 struct VExtHelper {
271 typedef T __attribute__((vector_size(N*sizeof(T)))) type;
272 };
273
274 template <int N, typename T>
275 using VExt = typename VExtHelper<N,T>::type;
276
277 // For some reason some (new!) versions of GCC cannot seem to deduce N in the generic
278 // to_vec<N,T>() below for N=4 and T=float. This workaround seems to help...
279 SI Vec<4,float> to_vec(VExt<4,float> v) { return sk_bit_cast<Vec<4,float>>(v); }
280 #endif
281
282 SINT VExt<N,T> to_vext(const Vec<N,T>& v) { return sk_bit_cast<VExt<N,T>>(v); }
283 SINT Vec <N,T> to_vec(const VExt<N,T>& v) { return sk_bit_cast<Vec <N,T>>(v); }
284
285 SINT Vec<N,T> operator+(const Vec<N,T>& x, const Vec<N,T>& y) {
286 return to_vec<N,T>(to_vext(x) + to_vext(y));
287 }
288 SINT Vec<N,T> operator-(const Vec<N,T>& x, const Vec<N,T>& y) {
289 return to_vec<N,T>(to_vext(x) - to_vext(y));
290 }
291 SINT Vec<N,T> operator*(const Vec<N,T>& x, const Vec<N,T>& y) {
292 return to_vec<N,T>(to_vext(x) * to_vext(y));
293 }
294 SINT Vec<N,T> operator/(const Vec<N,T>& x, const Vec<N,T>& y) {
295 return to_vec<N,T>(to_vext(x) / to_vext(y));
296 }
297
298 SINT Vec<N,T> operator^(const Vec<N,T>& x, const Vec<N,T>& y) {
299 return to_vec<N,T>(to_vext(x) ^ to_vext(y));
300 }
301 SINT Vec<N,T> operator&(const Vec<N,T>& x, const Vec<N,T>& y) {
302 return to_vec<N,T>(to_vext(x) & to_vext(y));
303 }
304 SINT Vec<N,T> operator|(const Vec<N,T>& x, const Vec<N,T>& y) {
305 return to_vec<N,T>(to_vext(x) | to_vext(y));
306 }
307
308 SINT Vec<N,T> operator!(const Vec<N,T>& x) { return to_vec<N,T>(!to_vext(x)); }
309 SINT Vec<N,T> operator-(const Vec<N,T>& x) { return to_vec<N,T>(-to_vext(x)); }
310 SINT Vec<N,T> operator~(const Vec<N,T>& x) { return to_vec<N,T>(~to_vext(x)); }
311
312 SINT Vec<N,T> operator<<(const Vec<N,T>& x, int k) { return to_vec<N,T>(to_vext(x) << k); }
313 SINT Vec<N,T> operator>>(const Vec<N,T>& x, int k) { return to_vec<N,T>(to_vext(x) >> k); }
314
315 SINT Vec<N,M<T>> operator==(const Vec<N,T>& x, const Vec<N,T>& y) {
316 return sk_bit_cast<Vec<N,M<T>>>(to_vext(x) == to_vext(y));
317 }
318 SINT Vec<N,M<T>> operator!=(const Vec<N,T>& x, const Vec<N,T>& y) {
319 return sk_bit_cast<Vec<N,M<T>>>(to_vext(x) != to_vext(y));
320 }
321 SINT Vec<N,M<T>> operator<=(const Vec<N,T>& x, const Vec<N,T>& y) {
322 return sk_bit_cast<Vec<N,M<T>>>(to_vext(x) <= to_vext(y));
323 }
324 SINT Vec<N,M<T>> operator>=(const Vec<N,T>& x, const Vec<N,T>& y) {
325 return sk_bit_cast<Vec<N,M<T>>>(to_vext(x) >= to_vext(y));
326 }
327 SINT Vec<N,M<T>> operator< (const Vec<N,T>& x, const Vec<N,T>& y) {
328 return sk_bit_cast<Vec<N,M<T>>>(to_vext(x) < to_vext(y));
329 }
330 SINT Vec<N,M<T>> operator> (const Vec<N,T>& x, const Vec<N,T>& y) {
331 return sk_bit_cast<Vec<N,M<T>>>(to_vext(x) > to_vext(y));
332 }
333
334 #else
335
336 // Either SKNX_NO_SIMD is defined, or Clang/GCC vector extensions are not available.
337 // We'll implement things portably with N==1 scalar implementations and recursion onto them.
338
339 // N == 1 scalar implementations.
340 SIT Vec<1,T> operator+(const Vec<1,T>& x, const Vec<1,T>& y) { return x.val + y.val; }
341 SIT Vec<1,T> operator-(const Vec<1,T>& x, const Vec<1,T>& y) { return x.val - y.val; }
342 SIT Vec<1,T> operator*(const Vec<1,T>& x, const Vec<1,T>& y) { return x.val * y.val; }
343 SIT Vec<1,T> operator/(const Vec<1,T>& x, const Vec<1,T>& y) { return x.val / y.val; }
344
345 SIT Vec<1,T> operator^(const Vec<1,T>& x, const Vec<1,T>& y) { return x.val ^ y.val; }
346 SIT Vec<1,T> operator&(const Vec<1,T>& x, const Vec<1,T>& y) { return x.val & y.val; }
347 SIT Vec<1,T> operator|(const Vec<1,T>& x, const Vec<1,T>& y) { return x.val | y.val; }
348
349 SIT Vec<1,T> operator!(const Vec<1,T>& x) { return !x.val; }
350 SIT Vec<1,T> operator-(const Vec<1,T>& x) { return -x.val; }
351 SIT Vec<1,T> operator~(const Vec<1,T>& x) { return ~x.val; }
352
353 SIT Vec<1,T> operator<<(const Vec<1,T>& x, int k) { return x.val << k; }
354 SIT Vec<1,T> operator>>(const Vec<1,T>& x, int k) { return x.val >> k; }
355
356 SIT Vec<1,M<T>> operator==(const Vec<1,T>& x, const Vec<1,T>& y) {
357 return x.val == y.val ? ~0 : 0;
358 }
359 SIT Vec<1,M<T>> operator!=(const Vec<1,T>& x, const Vec<1,T>& y) {
360 return x.val != y.val ? ~0 : 0;
361 }
362 SIT Vec<1,M<T>> operator<=(const Vec<1,T>& x, const Vec<1,T>& y) {
363 return x.val <= y.val ? ~0 : 0;
364 }
365 SIT Vec<1,M<T>> operator>=(const Vec<1,T>& x, const Vec<1,T>& y) {
366 return x.val >= y.val ? ~0 : 0;
367 }
368 SIT Vec<1,M<T>> operator< (const Vec<1,T>& x, const Vec<1,T>& y) {
369 return x.val < y.val ? ~0 : 0;
370 }
371 SIT Vec<1,M<T>> operator> (const Vec<1,T>& x, const Vec<1,T>& y) {
372 return x.val > y.val ? ~0 : 0;
373 }
374
375 // Recurse on lo/hi down to N==1 scalar implementations.
376 SINT Vec<N,T> operator+(const Vec<N,T>& x, const Vec<N,T>& y) {
377 return join(x.lo + y.lo, x.hi + y.hi);
378 }
379 SINT Vec<N,T> operator-(const Vec<N,T>& x, const Vec<N,T>& y) {
380 return join(x.lo - y.lo, x.hi - y.hi);
381 }
382 SINT Vec<N,T> operator*(const Vec<N,T>& x, const Vec<N,T>& y) {
383 return join(x.lo * y.lo, x.hi * y.hi);
384 }
385 SINT Vec<N,T> operator/(const Vec<N,T>& x, const Vec<N,T>& y) {
386 return join(x.lo / y.lo, x.hi / y.hi);
387 }
388
389 SINT Vec<N,T> operator^(const Vec<N,T>& x, const Vec<N,T>& y) {
390 return join(x.lo ^ y.lo, x.hi ^ y.hi);
391 }
392 SINT Vec<N,T> operator&(const Vec<N,T>& x, const Vec<N,T>& y) {
393 return join(x.lo & y.lo, x.hi & y.hi);
394 }
395 SINT Vec<N,T> operator|(const Vec<N,T>& x, const Vec<N,T>& y) {
396 return join(x.lo | y.lo, x.hi | y.hi);
397 }
398
399 SINT Vec<N,T> operator!(const Vec<N,T>& x) { return join(!x.lo, !x.hi); }
400 SINT Vec<N,T> operator-(const Vec<N,T>& x) { return join(-x.lo, -x.hi); }
401 SINT Vec<N,T> operator~(const Vec<N,T>& x) { return join(~x.lo, ~x.hi); }
402
403 SINT Vec<N,T> operator<<(const Vec<N,T>& x, int k) { return join(x.lo << k, x.hi << k); }
404 SINT Vec<N,T> operator>>(const Vec<N,T>& x, int k) { return join(x.lo >> k, x.hi >> k); }
405
406 SINT Vec<N,M<T>> operator==(const Vec<N,T>& x, const Vec<N,T>& y) {
407 return join(x.lo == y.lo, x.hi == y.hi);
408 }
409 SINT Vec<N,M<T>> operator!=(const Vec<N,T>& x, const Vec<N,T>& y) {
410 return join(x.lo != y.lo, x.hi != y.hi);
411 }
412 SINT Vec<N,M<T>> operator<=(const Vec<N,T>& x, const Vec<N,T>& y) {
413 return join(x.lo <= y.lo, x.hi <= y.hi);
414 }
415 SINT Vec<N,M<T>> operator>=(const Vec<N,T>& x, const Vec<N,T>& y) {
416 return join(x.lo >= y.lo, x.hi >= y.hi);
417 }
418 SINT Vec<N,M<T>> operator< (const Vec<N,T>& x, const Vec<N,T>& y) {
419 return join(x.lo < y.lo, x.hi < y.hi);
420 }
421 SINT Vec<N,M<T>> operator> (const Vec<N,T>& x, const Vec<N,T>& y) {
422 return join(x.lo > y.lo, x.hi > y.hi);
423 }
424 #endif
425
426 // Scalar/vector operations splat the scalar to a vector.
427 SINTU Vec<N,T> operator+ (U x, const Vec<N,T>& y) { return Vec<N,T>(x) + y; }
428 SINTU Vec<N,T> operator- (U x, const Vec<N,T>& y) { return Vec<N,T>(x) - y; }
429 SINTU Vec<N,T> operator* (U x, const Vec<N,T>& y) { return Vec<N,T>(x) * y; }
430 SINTU Vec<N,T> operator/ (U x, const Vec<N,T>& y) { return Vec<N,T>(x) / y; }
431 SINTU Vec<N,T> operator^ (U x, const Vec<N,T>& y) { return Vec<N,T>(x) ^ y; }
432 SINTU Vec<N,T> operator& (U x, const Vec<N,T>& y) { return Vec<N,T>(x) & y; }
433 SINTU Vec<N,T> operator| (U x, const Vec<N,T>& y) { return Vec<N,T>(x) | y; }
434 SINTU Vec<N,M<T>> operator==(U x, const Vec<N,T>& y) { return Vec<N,T>(x) == y; }
435 SINTU Vec<N,M<T>> operator!=(U x, const Vec<N,T>& y) { return Vec<N,T>(x) != y; }
436 SINTU Vec<N,M<T>> operator<=(U x, const Vec<N,T>& y) { return Vec<N,T>(x) <= y; }
437 SINTU Vec<N,M<T>> operator>=(U x, const Vec<N,T>& y) { return Vec<N,T>(x) >= y; }
438 SINTU Vec<N,M<T>> operator< (U x, const Vec<N,T>& y) { return Vec<N,T>(x) < y; }
439 SINTU Vec<N,M<T>> operator> (U x, const Vec<N,T>& y) { return Vec<N,T>(x) > y; }
440
441 SINTU Vec<N,T> operator+ (const Vec<N,T>& x, U y) { return x + Vec<N,T>(y); }
442 SINTU Vec<N,T> operator- (const Vec<N,T>& x, U y) { return x - Vec<N,T>(y); }
443 SINTU Vec<N,T> operator* (const Vec<N,T>& x, U y) { return x * Vec<N,T>(y); }
444 SINTU Vec<N,T> operator/ (const Vec<N,T>& x, U y) { return x / Vec<N,T>(y); }
445 SINTU Vec<N,T> operator^ (const Vec<N,T>& x, U y) { return x ^ Vec<N,T>(y); }
446 SINTU Vec<N,T> operator& (const Vec<N,T>& x, U y) { return x & Vec<N,T>(y); }
447 SINTU Vec<N,T> operator| (const Vec<N,T>& x, U y) { return x | Vec<N,T>(y); }
448 SINTU Vec<N,M<T>> operator==(const Vec<N,T>& x, U y) { return x == Vec<N,T>(y); }
449 SINTU Vec<N,M<T>> operator!=(const Vec<N,T>& x, U y) { return x != Vec<N,T>(y); }
450 SINTU Vec<N,M<T>> operator<=(const Vec<N,T>& x, U y) { return x <= Vec<N,T>(y); }
451 SINTU Vec<N,M<T>> operator>=(const Vec<N,T>& x, U y) { return x >= Vec<N,T>(y); }
452 SINTU Vec<N,M<T>> operator< (const Vec<N,T>& x, U y) { return x < Vec<N,T>(y); }
453 SINTU Vec<N,M<T>> operator> (const Vec<N,T>& x, U y) { return x > Vec<N,T>(y); }
454
455 SINT Vec<N,T>& operator+=(Vec<N,T>& x, const Vec<N,T>& y) { return (x = x + y); }
456 SINT Vec<N,T>& operator-=(Vec<N,T>& x, const Vec<N,T>& y) { return (x = x - y); }
457 SINT Vec<N,T>& operator*=(Vec<N,T>& x, const Vec<N,T>& y) { return (x = x * y); }
458 SINT Vec<N,T>& operator/=(Vec<N,T>& x, const Vec<N,T>& y) { return (x = x / y); }
459 SINT Vec<N,T>& operator^=(Vec<N,T>& x, const Vec<N,T>& y) { return (x = x ^ y); }
460 SINT Vec<N,T>& operator&=(Vec<N,T>& x, const Vec<N,T>& y) { return (x = x & y); }
461 SINT Vec<N,T>& operator|=(Vec<N,T>& x, const Vec<N,T>& y) { return (x = x | y); }
462
463 SINTU Vec<N,T>& operator+=(Vec<N,T>& x, U y) { return (x = x + Vec<N,T>(y)); }
464 SINTU Vec<N,T>& operator-=(Vec<N,T>& x, U y) { return (x = x - Vec<N,T>(y)); }
465 SINTU Vec<N,T>& operator*=(Vec<N,T>& x, U y) { return (x = x * Vec<N,T>(y)); }
466 SINTU Vec<N,T>& operator/=(Vec<N,T>& x, U y) { return (x = x / Vec<N,T>(y)); }
467 SINTU Vec<N,T>& operator^=(Vec<N,T>& x, U y) { return (x = x ^ Vec<N,T>(y)); }
468 SINTU Vec<N,T>& operator&=(Vec<N,T>& x, U y) { return (x = x & Vec<N,T>(y)); }
469 SINTU Vec<N,T>& operator|=(Vec<N,T>& x, U y) { return (x = x | Vec<N,T>(y)); }
470
471 SINT Vec<N,T>& operator<<=(Vec<N,T>& x, int bits) { return (x = x << bits); }
472 SINT Vec<N,T>& operator>>=(Vec<N,T>& x, int bits) { return (x = x >> bits); }
473
474 // Some operations we want are not expressible with Clang/GCC vector extensions.
475
476 // Clang can reason about naive_if_then_else() and optimize through it better
477 // than if_then_else(), so it's sometimes useful to call it directly when we
478 // think an entire expression should optimize away, e.g. min()/max().
479 SINT Vec<N,T> naive_if_then_else(const Vec<N,M<T>>& cond, const Vec<N,T>& t, const Vec<N,T>& e) {
480 return sk_bit_cast<Vec<N,T>>(( cond & sk_bit_cast<Vec<N, M<T>>>(t)) |
481 (~cond & sk_bit_cast<Vec<N, M<T>>>(e)) );
482 }
483
484 SIT Vec<1,T> if_then_else(const Vec<1,M<T>>& cond, const Vec<1,T>& t, const Vec<1,T>& e) {
485 // In practice this scalar implementation is unlikely to be used. See next if_then_else().
486 return sk_bit_cast<Vec<1,T>>(( cond & sk_bit_cast<Vec<1, M<T>>>(t)) |
487 (~cond & sk_bit_cast<Vec<1, M<T>>>(e)) );
488 }
489 SINT Vec<N,T> if_then_else(const Vec<N,M<T>>& cond, const Vec<N,T>& t, const Vec<N,T>& e) {
490 // Specializations inline here so they can generalize what types the apply to.
491 #if SKVX_USE_SIMD && SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_AVX2
492 if constexpr (N*sizeof(T) == 32) {
493 return sk_bit_cast<Vec<N,T>>(_mm256_blendv_epi8(sk_bit_cast<__m256i>(e),
494 sk_bit_cast<__m256i>(t),
495 sk_bit_cast<__m256i>(cond)));
496 }
497 #endif
498 #if SKVX_USE_SIMD && SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSE41
499 if constexpr (N*sizeof(T) == 16) {
500 return sk_bit_cast<Vec<N,T>>(_mm_blendv_epi8(sk_bit_cast<__m128i>(e),
501 sk_bit_cast<__m128i>(t),
502 sk_bit_cast<__m128i>(cond)));
503 }
504 #endif
505 #if SKVX_USE_SIMD && defined(SK_ARM_HAS_NEON)
506 if constexpr (N*sizeof(T) == 16) {
507 return sk_bit_cast<Vec<N,T>>(vbslq_u8(sk_bit_cast<uint8x16_t>(cond),
508 sk_bit_cast<uint8x16_t>(t),
509 sk_bit_cast<uint8x16_t>(e)));
510 }
511 #endif
512 #if SKVX_USE_SIMD && SK_CPU_LSX_LEVEL >= SK_CPU_LSX_LEVEL_LASX
513 if constexpr (N*sizeof(T) == 32) {
514 return sk_bit_cast<Vec<N,T>>(__lasx_xvbitsel_v(sk_bit_cast<__m256i>(e),
515 sk_bit_cast<__m256i>(t),
516 sk_bit_cast<__m256i>(cond)));
517 }
518 #endif
519 #if SKVX_USE_SIMD && SK_CPU_LSX_LEVEL >= SK_CPU_LSX_LEVEL_LSX
520 if constexpr (N*sizeof(T) == 16) {
521 return sk_bit_cast<Vec<N,T>>(__lsx_vbitsel_v(sk_bit_cast<__m128i>(e),
522 sk_bit_cast<__m128i>(t),
523 sk_bit_cast<__m128i>(cond)));
524 }
525 #endif
526 // Recurse for large vectors to try to hit the specializations above.
527 if constexpr (N*sizeof(T) > 16) {
528 return join(if_then_else(cond.lo, t.lo, e.lo),
529 if_then_else(cond.hi, t.hi, e.hi));
530 }
531 // This default can lead to better code than the recursing onto scalars.
532 return naive_if_then_else(cond, t, e);
533 }
534
535 SIT bool any(const Vec<1,T>& x) { return x.val != 0; }
536 SINT bool any(const Vec<N,T>& x) {
537 // For any(), the _mm_testz intrinsics are correct and don't require comparing 'x' to 0, so it's
538 // lower latency compared to _mm_movemask + _mm_compneq on plain SSE.
539 #if SKVX_USE_SIMD && SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_AVX2
540 if constexpr (N*sizeof(T) == 32) {
541 return !_mm256_testz_si256(sk_bit_cast<__m256i>(x), _mm256_set1_epi32(-1));
542 }
543 #endif
544 #if SKVX_USE_SIMD && SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSE41
545 if constexpr (N*sizeof(T) == 16) {
546 return !_mm_testz_si128(sk_bit_cast<__m128i>(x), _mm_set1_epi32(-1));
547 }
548 #endif
549 #if SKVX_USE_SIMD && SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSE1
550 if constexpr (N*sizeof(T) == 16) {
551 // On SSE, movemask checks only the MSB in each lane, which is fine if the lanes were set
552 // directly from a comparison op (which sets all bits to 1 when true), but skvx::Vec<>
553 // treats any non-zero value as true, so we have to compare 'x' to 0 before calling movemask
554 return _mm_movemask_ps(_mm_cmpneq_ps(sk_bit_cast<__m128>(x), _mm_set1_ps(0))) != 0b0000;
555 }
556 #endif
557 #if SKVX_USE_SIMD && defined(__aarch64__)
558 // On 64-bit NEON, take the max across lanes, which will be non-zero if any lane was true.
559 // The specific lane-size doesn't really matter in this case since it's really any set bit
560 // that we're looking for.
561 if constexpr (N*sizeof(T) == 8 ) { return vmaxv_u8 (sk_bit_cast<uint8x8_t> (x)) > 0; }
562 if constexpr (N*sizeof(T) == 16) { return vmaxvq_u8(sk_bit_cast<uint8x16_t>(x)) > 0; }
563 #endif
564 #if SKVX_USE_SIMD && defined(__wasm_simd128__)
565 if constexpr (N == 4 && sizeof(T) == 4) {
566 return wasm_i32x4_any_true(sk_bit_cast<VExt<4,int>>(x));
567 }
568 #endif
569 #if SKVX_USE_SIMD && SK_CPU_LSX_LEVEL >= SK_CPU_LSX_LEVEL_LASX
570 if constexpr (N*sizeof(T) == 32) {
571 v8i32 retv = (v8i32)__lasx_xvmskltz_w(__lasx_xvslt_wu(__lasx_xvldi(0),
572 sk_bit_cast<__m256i>(x)));
573 return (retv[0] | retv[4]) != 0b0000;
574 }
575 #endif
576 #if SKVX_USE_SIMD && SK_CPU_LSX_LEVEL >= SK_CPU_LSX_LEVEL_LSX
577 if constexpr (N*sizeof(T) == 16) {
578 v4i32 retv = (v4i32)__lsx_vmskltz_w(__lsx_vslt_wu(__lsx_vldi(0),
579 sk_bit_cast<__m128i>(x)));
580 return retv[0] != 0b0000;
581 }
582 #endif
583 return any(x.lo)
584 || any(x.hi);
585 }
586
587 SIT bool all(const Vec<1,T>& x) { return x.val != 0; }
588 SINT bool all(const Vec<N,T>& x) {
589 // Unlike any(), we have to respect the lane layout, or we'll miss cases where a
590 // true lane has a mix of 0 and 1 bits.
591 #if SKVX_USE_SIMD && SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSE1
592 // Unfortunately, the _mm_testc intrinsics don't let us avoid the comparison to 0 for all()'s
593 // correctness, so always just use the plain SSE version.
594 if constexpr (N == 4 && sizeof(T) == 4) {
595 return _mm_movemask_ps(_mm_cmpneq_ps(sk_bit_cast<__m128>(x), _mm_set1_ps(0))) == 0b1111;
596 }
597 #endif
598 #if SKVX_USE_SIMD && defined(__aarch64__)
599 // On 64-bit NEON, take the min across the lanes, which will be non-zero if all lanes are != 0.
600 if constexpr (sizeof(T)==1 && N==8) {return vminv_u8 (sk_bit_cast<uint8x8_t> (x)) > 0;}
601 if constexpr (sizeof(T)==1 && N==16) {return vminvq_u8 (sk_bit_cast<uint8x16_t>(x)) > 0;}
602 if constexpr (sizeof(T)==2 && N==4) {return vminv_u16 (sk_bit_cast<uint16x4_t>(x)) > 0;}
603 if constexpr (sizeof(T)==2 && N==8) {return vminvq_u16(sk_bit_cast<uint16x8_t>(x)) > 0;}
604 if constexpr (sizeof(T)==4 && N==2) {return vminv_u32 (sk_bit_cast<uint32x2_t>(x)) > 0;}
605 if constexpr (sizeof(T)==4 && N==4) {return vminvq_u32(sk_bit_cast<uint32x4_t>(x)) > 0;}
606 #endif
607 #if SKVX_USE_SIMD && defined(__wasm_simd128__)
608 if constexpr (N == 4 && sizeof(T) == 4) {
609 return wasm_i32x4_all_true(sk_bit_cast<VExt<4,int>>(x));
610 }
611 #endif
612 #if SKVX_USE_SIMD && SK_CPU_LSX_LEVEL >= SK_CPU_LSX_LEVEL_LASX
613 if constexpr (N == 8 && sizeof(T) == 4) {
614 v8i32 retv = (v8i32)__lasx_xvmskltz_w(__lasx_xvslt_wu(__lasx_xvldi(0),
615 sk_bit_cast<__m256i>(x)));
616 return (retv[0] & retv[4]) == 0b1111;
617 }
618 #endif
619 #if SKVX_USE_SIMD && SK_CPU_LSX_LEVEL >= SK_CPU_LSX_LEVEL_LSX
620 if constexpr (N == 4 && sizeof(T) == 4) {
621 v4i32 retv = (v4i32)__lsx_vmskltz_w(__lsx_vslt_wu(__lsx_vldi(0),
622 sk_bit_cast<__m128i>(x)));
623 return retv[0] == 0b1111;
624 }
625 #endif
626 return all(x.lo)
627 && all(x.hi);
628 }
629
630 // cast() Vec<N,S> to Vec<N,D>, as if applying a C-cast to each lane.
631 // TODO: implement with map()?
632 template <typename D, typename S>
633 SI Vec<1,D> cast(const Vec<1,S>& src) { return (D)src.val; }
634
635 template <typename D, int N, typename S>
636 SI Vec<N,D> cast(const Vec<N,S>& src) {
637 #if SKVX_USE_SIMD && defined(__clang__)
638 return to_vec(__builtin_convertvector(to_vext(src), VExt<N,D>));
639 #else
640 return join(cast<D>(src.lo), cast<D>(src.hi));
641 #endif
642 }
643
644 // min/max match logic of std::min/std::max, which is important when NaN is involved.
645 SIT T min(const Vec<1,T>& x) { return x.val; }
646 SIT T max(const Vec<1,T>& x) { return x.val; }
647 SINT T min(const Vec<N,T>& x) { return std::min(min(x.lo), min(x.hi)); }
648 SINT T max(const Vec<N,T>& x) { return std::max(max(x.lo), max(x.hi)); }
649
650 SINT Vec<N,T> min(const Vec<N,T>& x, const Vec<N,T>& y) { return naive_if_then_else(y < x, y, x); }
651 SINT Vec<N,T> max(const Vec<N,T>& x, const Vec<N,T>& y) { return naive_if_then_else(x < y, y, x); }
652
653 SINTU Vec<N,T> min(const Vec<N,T>& x, U y) { return min(x, Vec<N,T>(y)); }
654 SINTU Vec<N,T> max(const Vec<N,T>& x, U y) { return max(x, Vec<N,T>(y)); }
655 SINTU Vec<N,T> min(U x, const Vec<N,T>& y) { return min(Vec<N,T>(x), y); }
656 SINTU Vec<N,T> max(U x, const Vec<N,T>& y) { return max(Vec<N,T>(x), y); }
657
658 // pin matches the logic of SkTPin, which is important when NaN is involved. It always returns
659 // values in the range lo..hi, and if x is NaN, it returns lo.
660 SINT Vec<N,T> pin(const Vec<N,T>& x, const Vec<N,T>& lo, const Vec<N,T>& hi) {
661 return max(lo, min(x, hi));
662 }
663
664 // Shuffle values from a vector pretty arbitrarily:
665 // skvx::Vec<4,float> rgba = {R,G,B,A};
666 // shuffle<2,1,0,3> (rgba) ~> {B,G,R,A}
667 // shuffle<2,1> (rgba) ~> {B,G}
668 // shuffle<2,1,2,1,2,1,2,1>(rgba) ~> {B,G,B,G,B,G,B,G}
669 // shuffle<3,3,3,3> (rgba) ~> {A,A,A,A}
670 // The only real restriction is that the output also be a legal N=power-of-two sknx::Vec.
671 template <int... Ix, int N, typename T>
672 SI Vec<sizeof...(Ix),T> shuffle(const Vec<N,T>& x) {
673 #if SKVX_USE_SIMD && defined(__clang__)
674 // TODO: can we just always use { x[Ix]... }?
675 return to_vec<sizeof...(Ix),T>(__builtin_shufflevector(to_vext(x), to_vext(x), Ix...));
676 #else
677 return { x[Ix]... };
678 #endif
679 }
680
681 // Call map(fn, x) for a vector with fn() applied to each lane of x, { fn(x[0]), fn(x[1]), ... },
682 // or map(fn, x,y) for a vector of fn(x[i], y[i]), etc.
683
684 template <typename Fn, typename... Args, size_t... I>
685 SI auto map(std::index_sequence<I...>,
686 Fn&& fn, const Args&... args) -> skvx::Vec<sizeof...(I), decltype(fn(args[0]...))> {
687 auto lane = [&](size_t i)
688 // CFI, specifically -fsanitize=cfi-icall, seems to give a false positive here,
689 // with errors like "control flow integrity check for type 'float (float)
690 // noexcept' failed during indirect function call... note: sqrtf.cfi_jt defined
691 // here". But we can be quite sure fn is the right type: it's all inferred!
692 // So, stifle CFI in this function.
693 SK_NO_SANITIZE_CFI
694 { return fn(args[static_cast<int>(i)]...); };
695
696 return { lane(I)... };
697 }
698
699 template <typename Fn, int N, typename T, typename... Rest>
700 auto map(Fn&& fn, const Vec<N,T>& first, const Rest&... rest) {
701 // Derive an {0...N-1} index_sequence from the size of the first arg: N lanes in, N lanes out.
702 return map(std::make_index_sequence<N>{}, fn, first,rest...);
703 }
704
705 SIN Vec<N,float> ceil(const Vec<N,float>& x) { return map( ceilf, x); }
706 SIN Vec<N,float> floor(const Vec<N,float>& x) { return map(floorf, x); }
707 SIN Vec<N,float> trunc(const Vec<N,float>& x) { return map(truncf, x); }
708 SIN Vec<N,float> round(const Vec<N,float>& x) { return map(roundf, x); }
709 SIN Vec<N,float> sqrt(const Vec<N,float>& x) { return map( sqrtf, x); }
710 SIN Vec<N,float> abs(const Vec<N,float>& x) { return map( fabsf, x); }
711 SIN Vec<N,float> fma(const Vec<N,float>& x,
712 const Vec<N,float>& y,
713 const Vec<N,float>& z) {
714 // I don't understand why Clang's codegen is terrible if we write map(fmaf, x,y,z) directly.
715 auto fn = [](float x, float y, float z) { return fmaf(x,y,z); };
716 return map(fn, x,y,z);
717 }
718
719 SI Vec<1,int> lrint(const Vec<1,float>& x) {
720 return (int)lrintf(x.val);
721 }
722 SIN Vec<N,int> lrint(const Vec<N,float>& x) {
723 #if SKVX_USE_SIMD && SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_AVX
724 if constexpr (N == 8) {
725 return sk_bit_cast<Vec<N,int>>(_mm256_cvtps_epi32(sk_bit_cast<__m256>(x)));
726 }
727 #endif
728 #if SKVX_USE_SIMD && SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSE1
729 if constexpr (N == 4) {
730 return sk_bit_cast<Vec<N,int>>(_mm_cvtps_epi32(sk_bit_cast<__m128>(x)));
731 }
732 #endif
733 #if SKVX_USE_SIMD && SK_CPU_LSX_LEVEL >= SK_CPU_LSX_LEVEL_LASX
734 if constexpr (N == 8) {
735 return sk_bit_cast<Vec<N,int>>(__lasx_xvftint_w_s(sk_bit_cast<__m256>(x)));
736 }
737 #endif
738 #if SKVX_USE_SIMD && SK_CPU_LSX_LEVEL >= SK_CPU_LSX_LEVEL_LSX
739 if constexpr (N == 4) {
740 return sk_bit_cast<Vec<N,int>>(__lsx_vftint_w_s(sk_bit_cast<__m128>(x)));
741 }
742 #endif
743 return join(lrint(x.lo),
744 lrint(x.hi));
745 }
746
747 SIN Vec<N,float> fract(const Vec<N,float>& x) { return x - floor(x); }
748
749 // Converts float to half, rounding to nearest even, and supporting de-normal f16 conversion,
750 // and overflow to f16 infinity. Should not be called with NaNs, since it can convert NaN->inf.
751 // KEEP IN SYNC with skcms' Half_from_F to ensure that f16 colors are computed consistently in both
752 // skcms and skvx.
753 SIN Vec<N,uint16_t> to_half(const Vec<N,float>& x) {
754 assert(all(x == x)); // No NaNs should reach this function
755
756 // Intrinsics for float->half tend to operate on 4 lanes, and the default implementation has
757 // enough instructions that it's better to split and join on 128 bits groups vs.
758 // recursing for each min/max/shift/etc.
759 if constexpr (N > 4) {
760 return join(to_half(x.lo),
761 to_half(x.hi));
762 }
763
764 #if SKVX_USE_SIMD && defined(__aarch64__)
765 if constexpr (N == 4) {
766 return sk_bit_cast<Vec<N,uint16_t>>(vcvt_f16_f32(sk_bit_cast<float32x4_t>(x)));
767
768 }
769 #endif
770
771 #define I(x) sk_bit_cast<Vec<N,int32_t>>(x)
772 #define F(x) sk_bit_cast<Vec<N,float>>(x)
773 Vec<N,int32_t> sem = I(x),
774 s = sem & 0x8000'0000,
775 em = min(sem ^ s, 0x4780'0000), // |x| clamped to f16 infinity
776 // F(em)*8192 increases the exponent by 13, which when added back to em will shift
777 // the mantissa bits 13 to the right. We clamp to 1/2 for subnormal values, which
778 // automatically shifts the mantissa to match 2^-14 expected for a subnorm f16.
779 magic = I(max(F(em) * 8192.f, 0.5f)) & (255 << 23),
780 rounded = I((F(em) + F(magic))), // shift mantissa with automatic round-to-even
781 // Subtract 127 for f32 bias, subtract 13 to undo the *8192, subtract 1 to remove
782 // the implicit leading 1., and add 15 to get the f16 biased exponent.
783 exp = ((magic >> 13) - ((127-15+13+1)<<10)), // shift and re-bias exponent
784 f16 = rounded + exp; // use + if 'rounded' rolled over into first exponent bit
785 return cast<uint16_t>((s>>16) | f16);
786 #undef I
787 #undef F
788 }
789
790 // Converts from half to float, preserving NaN and +/- infinity.
791 // KEEP IN SYNC with skcms' F_from_Half to ensure that f16 colors are computed consistently in both
792 // skcms and skvx.
793 SIN Vec<N,float> from_half(const Vec<N,uint16_t>& x) {
794 if constexpr (N > 4) {
795 return join(from_half(x.lo),
796 from_half(x.hi));
797 }
798
799 #if SKVX_USE_SIMD && defined(__aarch64__)
800 if constexpr (N == 4) {
801 return sk_bit_cast<Vec<N,float>>(vcvt_f32_f16(sk_bit_cast<float16x4_t>(x)));
802 }
803 #endif
804
805 Vec<N,int32_t> wide = cast<int32_t>(x),
806 s = wide & 0x8000,
807 em = wide ^ s,
808 inf_or_nan = (em >= (31 << 10)) & (255 << 23), // Expands exponent to fill 8 bits
809 is_norm = em > 0x3ff,
810 // subnormal f16's are 2^-14*0.[m0:9] == 2^-24*[m0:9].0
811 sub = sk_bit_cast<Vec<N,int32_t>>((cast<float>(em) * (1.f/(1<<24)))),
812 norm = ((em<<13) + ((127-15)<<23)), // Shifts mantissa, shifts + re-biases exp
813 finite = (is_norm & norm) | (~is_norm & sub);
814 // If 'x' is f16 +/- infinity, inf_or_nan will be the filled 8-bit exponent but 'norm' will be
815 // all 0s since 'x's mantissa is 0. Thus norm | inf_or_nan becomes f32 infinity. However, if
816 // 'x' is an f16 NaN, some bits of 'norm' will be non-zero, so it stays an f32 NaN after the OR.
817 return sk_bit_cast<Vec<N,float>>((s<<16) | finite | inf_or_nan);
818 }
819
820 // div255(x) = (x + 127) / 255 is a bit-exact rounding divide-by-255, packing down to 8-bit.
821 SIN Vec<N,uint8_t> div255(const Vec<N,uint16_t>& x) {
822 return cast<uint8_t>( (x+127)/255 );
823 }
824
825 // approx_scale(x,y) approximates div255(cast<uint16_t>(x)*cast<uint16_t>(y)) within a bit,
826 // and is always perfect when x or y is 0 or 255.
827 SIN Vec<N,uint8_t> approx_scale(const Vec<N,uint8_t>& x, const Vec<N,uint8_t>& y) {
828 // All of (x*y+x)/256, (x*y+y)/256, and (x*y+255)/256 meet the criteria above.
829 // We happen to have historically picked (x*y+x)/256.
830 auto X = cast<uint16_t>(x),
831 Y = cast<uint16_t>(y);
832 return cast<uint8_t>( (X*Y+X)/256 );
833 }
834
835 // saturated_add(x,y) sums values and clamps to the maximum value instead of overflowing.
836 SINT std::enable_if_t<std::is_unsigned_v<T>, Vec<N,T>> saturated_add(const Vec<N,T>& x,
837 const Vec<N,T>& y) {
838 #if SKVX_USE_SIMD && (SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSE1 || defined(SK_ARM_HAS_NEON) || \
839 SK_CPU_LSX_LEVEL >= SK_CPU_LSX_LEVEL_LSX)
840 // Both SSE and ARM have 16-lane saturated adds, so use intrinsics for those and recurse down
841 // or join up to take advantage.
842 if constexpr (N == 16 && sizeof(T) == 1) {
843 #if SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSE1
844 return sk_bit_cast<Vec<N,T>>(_mm_adds_epu8(sk_bit_cast<__m128i>(x),
845 sk_bit_cast<__m128i>(y)));
846 #elif SK_CPU_LSX_LEVEL >= SK_CPU_LSX_LEVEL_LSX
847 return sk_bit_cast<Vec<N,T>>(__lsx_vsadd_bu(sk_bit_cast<__m128i>(x),
848 sk_bit_cast<__m128i>(y)));
849 #else // SK_ARM_HAS_NEON
850 return sk_bit_cast<Vec<N,T>>(vqaddq_u8(sk_bit_cast<uint8x16_t>(x),
851 sk_bit_cast<uint8x16_t>(y)));
852 #endif
853 } else if constexpr (N < 16 && sizeof(T) == 1) {
854 return saturated_add(join(x,x), join(y,y)).lo;
855 } else if constexpr (sizeof(T) == 1) {
856 return join(saturated_add(x.lo, y.lo), saturated_add(x.hi, y.hi));
857 }
858 #endif
859 // Otherwise saturate manually
860 auto sum = x + y;
861 return if_then_else(sum < x, Vec<N,T>(std::numeric_limits<T>::max()), sum);
862 }
863
864 // The ScaledDividerU32 takes a divisor > 1, and creates a function divide(numerator) that
865 // calculates a numerator / denominator. For this to be rounded properly, numerator should have
866 // half added in:
867 // divide(numerator + half) == floor(numerator/denominator + 1/2).
868 //
869 // This gives an answer within +/- 1 from the true value.
870 //
871 // Derivation of half:
872 // numerator/denominator + 1/2 = (numerator + half) / d
873 // numerator + denominator / 2 = numerator + half
874 // half = denominator / 2.
875 //
876 // Because half is divided by 2, that division must also be rounded.
877 // half == denominator / 2 = (denominator + 1) / 2.
878 //
879 // The divisorFactor is just a scaled value:
880 // divisorFactor = (1 / divisor) * 2 ^ 32.
881 // The maximum that can be divided and rounded is UINT_MAX - half.
882 class ScaledDividerU32 {
883 public:
884 explicit ScaledDividerU32(uint32_t divisor)
885 : fDivisorFactor{(uint32_t)(std::round((1.0 / divisor) * (1ull << 32)))}
886 , fHalf{(divisor + 1) >> 1} {
887 assert(divisor > 1);
888 }
889
890 Vec<4, uint32_t> divide(const Vec<4, uint32_t>& numerator) const {
891 #if SKVX_USE_SIMD && defined(SK_ARM_HAS_NEON)
892 uint64x2_t hi = vmull_n_u32(vget_high_u32(to_vext(numerator)), fDivisorFactor);
893 uint64x2_t lo = vmull_n_u32(vget_low_u32(to_vext(numerator)), fDivisorFactor);
894
895 return to_vec<4, uint32_t>(vcombine_u32(vshrn_n_u64(lo,32), vshrn_n_u64(hi,32)));
896 #else
897 return cast<uint32_t>((cast<uint64_t>(numerator) * fDivisorFactor) >> 32);
898 #endif
899 }
900
901 uint32_t half() const { return fHalf; }
902 uint32_t divisorFactor() const { return fDivisorFactor; }
903
904 private:
905 const uint32_t fDivisorFactor;
906 const uint32_t fHalf;
907 };
908
909
910 SIN Vec<N,uint16_t> mull(const Vec<N,uint8_t>& x,
911 const Vec<N,uint8_t>& y) {
912 #if SKVX_USE_SIMD && defined(SK_ARM_HAS_NEON)
913 // With NEON we can do eight u8*u8 -> u16 in one instruction, vmull_u8 (read, mul-long).
914 if constexpr (N == 8) {
915 return to_vec<8,uint16_t>(vmull_u8(to_vext(x), to_vext(y)));
916 } else if constexpr (N < 8) {
917 return mull(join(x,x), join(y,y)).lo;
918 } else { // N > 8
919 return join(mull(x.lo, y.lo), mull(x.hi, y.hi));
920 }
921 #else
922 return cast<uint16_t>(x) * cast<uint16_t>(y);
923 #endif
924 }
925
926 SIN Vec<N,uint32_t> mull(const Vec<N,uint16_t>& x,
927 const Vec<N,uint16_t>& y) {
928 #if SKVX_USE_SIMD && defined(SK_ARM_HAS_NEON)
929 // NEON can do four u16*u16 -> u32 in one instruction, vmull_u16
930 if constexpr (N == 4) {
931 return to_vec<4,uint32_t>(vmull_u16(to_vext(x), to_vext(y)));
932 } else if constexpr (N < 4) {
933 return mull(join(x,x), join(y,y)).lo;
934 } else { // N > 4
935 return join(mull(x.lo, y.lo), mull(x.hi, y.hi));
936 }
937 #else
938 return cast<uint32_t>(x) * cast<uint32_t>(y);
939 #endif
940 }
941
942 SIN Vec<N,uint16_t> mulhi(const Vec<N,uint16_t>& x,
943 const Vec<N,uint16_t>& y) {
944 #if SKVX_USE_SIMD && SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSE1
945 // Use _mm_mulhi_epu16 for 8xuint16_t and join or split to get there.
946 if constexpr (N == 8) {
947 return sk_bit_cast<Vec<8,uint16_t>>(_mm_mulhi_epu16(sk_bit_cast<__m128i>(x),
948 sk_bit_cast<__m128i>(y)));
949 } else if constexpr (N < 8) {
950 return mulhi(join(x,x), join(y,y)).lo;
951 } else { // N > 8
952 return join(mulhi(x.lo, y.lo), mulhi(x.hi, y.hi));
953 }
954 #elif SKVX_USE_SIMD && SK_CPU_LSX_LEVEL >= SK_CPU_LSX_LEVEL_LSX
955 if constexpr (N == 8) {
956 return sk_bit_cast<Vec<8,uint16_t>>(__lsx_vmuh_hu(sk_bit_cast<__m128i>(x),
957 sk_bit_cast<__m128i>(y)));
958 } else if constexpr (N < 8) {
959 return mulhi(join(x,x), join(y,y)).lo;
960 } else { // N > 8
961 return join(mulhi(x.lo, y.lo), mulhi(x.hi, y.hi));
962 }
963 #else
964 return skvx::cast<uint16_t>(mull(x, y) >> 16);
965 #endif
966 }
967
968 SINT T dot(const Vec<N, T>& a, const Vec<N, T>& b) {
969 // While dot is a "horizontal" operation like any or all, it needs to remain
970 // in floating point and there aren't really any good SIMD instructions that make it faster.
971 // The constexpr cases remove the for loop in the only cases we realistically call.
972 auto ab = a*b;
973 if constexpr (N == 2) {
974 return ab[0] + ab[1];
975 } else if constexpr (N == 4) {
976 return ab[0] + ab[1] + ab[2] + ab[3];
977 } else {
978 T sum = ab[0];
979 for (int i = 1; i < N; ++i) {
980 sum += ab[i];
981 }
982 return sum;
983 }
984 }
985
986 SIT T cross(const Vec<2, T>& a, const Vec<2, T>& b) {
987 auto x = a * shuffle<1,0>(b);
988 return x[0] - x[1];
989 }
990
991 SIN float length(const Vec<N, float>& v) {
992 return std::sqrt(dot(v, v));
993 }
994
995 SIN double length(const Vec<N, double>& v) {
996 return std::sqrt(dot(v, v));
997 }
998
999 SIN Vec<N, float> normalize(const Vec<N, float>& v) {
1000 return v / length(v);
1001 }
1002
1003 SIN Vec<N, double> normalize(const Vec<N, double>& v) {
1004 return v / length(v);
1005 }
1006
1007 SINT bool isfinite(const Vec<N, T>& v) {
1008 // Multiply all values together with 0. If they were all finite, the output is
1009 // 0 (also finite). If any were not, we'll get nan.
1010 return SkIsFinite(dot(v, Vec<N, T>(0)));
1011 }
1012
1013 // De-interleaving load of 4 vectors.
1014 //
1015 // WARNING: These are really only supported well on NEON. Consider restructuring your data before
1016 // resorting to these methods.
1017 SIT void strided_load4(const T* v,
1018 Vec<1,T>& a,
1019 Vec<1,T>& b,
1020 Vec<1,T>& c,
1021 Vec<1,T>& d) {
1022 a.val = v[0];
1023 b.val = v[1];
1024 c.val = v[2];
1025 d.val = v[3];
1026 }
1027 SINT void strided_load4(const T* v,
1028 Vec<N,T>& a,
1029 Vec<N,T>& b,
1030 Vec<N,T>& c,
1031 Vec<N,T>& d) {
1032 strided_load4(v, a.lo, b.lo, c.lo, d.lo);
1033 strided_load4(v + 4*(N/2), a.hi, b.hi, c.hi, d.hi);
1034 }
1035 #if SKVX_USE_SIMD && defined(SK_ARM_HAS_NEON)
1036 #define IMPL_LOAD4_TRANSPOSED(N, T, VLD) \
1037 SI void strided_load4(const T* v, \
1038 Vec<N,T>& a, \
1039 Vec<N,T>& b, \
1040 Vec<N,T>& c, \
1041 Vec<N,T>& d) { \
1042 auto mat = VLD(v); \
1043 a = sk_bit_cast<Vec<N,T>>(mat.val[0]); \
1044 b = sk_bit_cast<Vec<N,T>>(mat.val[1]); \
1045 c = sk_bit_cast<Vec<N,T>>(mat.val[2]); \
1046 d = sk_bit_cast<Vec<N,T>>(mat.val[3]); \
1047 }
1048 IMPL_LOAD4_TRANSPOSED(2, uint32_t, vld4_u32)
1049 IMPL_LOAD4_TRANSPOSED(4, uint16_t, vld4_u16)
1050 IMPL_LOAD4_TRANSPOSED(8, uint8_t, vld4_u8)
1051 IMPL_LOAD4_TRANSPOSED(2, int32_t, vld4_s32)
1052 IMPL_LOAD4_TRANSPOSED(4, int16_t, vld4_s16)
1053 IMPL_LOAD4_TRANSPOSED(8, int8_t, vld4_s8)
1054 IMPL_LOAD4_TRANSPOSED(2, float, vld4_f32)
1055 IMPL_LOAD4_TRANSPOSED(4, uint32_t, vld4q_u32)
1056 IMPL_LOAD4_TRANSPOSED(8, uint16_t, vld4q_u16)
1057 IMPL_LOAD4_TRANSPOSED(16, uint8_t, vld4q_u8)
1058 IMPL_LOAD4_TRANSPOSED(4, int32_t, vld4q_s32)
1059 IMPL_LOAD4_TRANSPOSED(8, int16_t, vld4q_s16)
1060 IMPL_LOAD4_TRANSPOSED(16, int8_t, vld4q_s8)
1061 IMPL_LOAD4_TRANSPOSED(4, float, vld4q_f32)
1062 #undef IMPL_LOAD4_TRANSPOSED
1063
1064 #elif SKVX_USE_SIMD && SK_CPU_SSE_LEVEL >= SK_CPU_SSE_LEVEL_SSE1
1065
1066 SI void strided_load4(const float* v,
1067 Vec<4,float>& a,
1068 Vec<4,float>& b,
1069 Vec<4,float>& c,
1070 Vec<4,float>& d) {
1071 __m128 a_ = _mm_loadu_ps(v);
1072 __m128 b_ = _mm_loadu_ps(v+4);
1073 __m128 c_ = _mm_loadu_ps(v+8);
1074 __m128 d_ = _mm_loadu_ps(v+12);
1075 _MM_TRANSPOSE4_PS(a_, b_, c_, d_);
1076 a = sk_bit_cast<Vec<4,float>>(a_);
1077 b = sk_bit_cast<Vec<4,float>>(b_);
1078 c = sk_bit_cast<Vec<4,float>>(c_);
1079 d = sk_bit_cast<Vec<4,float>>(d_);
1080 }
1081
1082 #elif SKVX_USE_SIMD && SKVX_CPU_LSX_LEVEL >= SK_CPU_LSX_LEVEL_LSX
1083 #define _LSX_TRANSPOSE4(row0, row1, row2, row3) \
1084 do { \
1085 __m128i __t0 = __lsx_vilvl_w (row1, row0); \
1086 __m128i __t1 = __lsx_vilvl_w (row3, row2); \
1087 __m128i __t2 = __lsx_vilvh_w (row1, row0); \
1088 __m128i __t3 = __lsx_vilvh_w (row3, row2); \
1089 (row0) = __lsx_vilvl_d (__t1, __t0); \
1090 (row1) = __lsx_vilvh_d (__t1, __t0); \
1091 (row2) = __lsx_vilvl_d (__t3, __t2); \
1092 (row3) = __lsx_vilvh_d (__t3, __t2); \
1093 } while (0)
1094
1095 SI void strided_load4(const int* v,
1096 Vec<4,int>& a,
1097 Vec<4,int>& b,
1098 Vec<4,int>& c,
1099 Vec<4,int>& d) {
1100 __m128i a_ = __lsx_vld(v, 0);
1101 __m128i b_ = __lsx_vld(v, 16);
1102 __m128i c_ = __lsx_vld(v, 32);
1103 __m128i d_ = __lsx_vld(v, 48);
1104 _LSX_TRANSPOSE4(a_, b_, c_, d_);
1105 a = sk_bit_cast<Vec<4,int>>(a_);
1106 b = sk_bit_cast<Vec<4,int>>(b_);
1107 c = sk_bit_cast<Vec<4,int>>(c_);
1108 d = sk_bit_cast<Vec<4,int>>(d_);
1109 }
1110 #endif
1111
1112 // De-interleaving load of 2 vectors.
1113 //
1114 // WARNING: These are really only supported well on NEON. Consider restructuring your data before
1115 // resorting to these methods.
1116 SIT void strided_load2(const T* v, Vec<1,T>& a, Vec<1,T>& b) {
1117 a.val = v[0];
1118 b.val = v[1];
1119 }
1120 SINT void strided_load2(const T* v, Vec<N,T>& a, Vec<N,T>& b) {
1121 strided_load2(v, a.lo, b.lo);
1122 strided_load2(v + 2*(N/2), a.hi, b.hi);
1123 }
1124 #if SKVX_USE_SIMD && defined(SK_ARM_HAS_NEON)
1125 #define IMPL_LOAD2_TRANSPOSED(N, T, VLD) \
1126 SI void strided_load2(const T* v, Vec<N,T>& a, Vec<N,T>& b) { \
1127 auto mat = VLD(v); \
1128 a = sk_bit_cast<Vec<N,T>>(mat.val[0]); \
1129 b = sk_bit_cast<Vec<N,T>>(mat.val[1]); \
1130 }
1131 IMPL_LOAD2_TRANSPOSED(2, uint32_t, vld2_u32)
1132 IMPL_LOAD2_TRANSPOSED(4, uint16_t, vld2_u16)
1133 IMPL_LOAD2_TRANSPOSED(8, uint8_t, vld2_u8)
1134 IMPL_LOAD2_TRANSPOSED(2, int32_t, vld2_s32)
1135 IMPL_LOAD2_TRANSPOSED(4, int16_t, vld2_s16)
1136 IMPL_LOAD2_TRANSPOSED(8, int8_t, vld2_s8)
1137 IMPL_LOAD2_TRANSPOSED(2, float, vld2_f32)
1138 IMPL_LOAD2_TRANSPOSED(4, uint32_t, vld2q_u32)
1139 IMPL_LOAD2_TRANSPOSED(8, uint16_t, vld2q_u16)
1140 IMPL_LOAD2_TRANSPOSED(16, uint8_t, vld2q_u8)
1141 IMPL_LOAD2_TRANSPOSED(4, int32_t, vld2q_s32)
1142 IMPL_LOAD2_TRANSPOSED(8, int16_t, vld2q_s16)
1143 IMPL_LOAD2_TRANSPOSED(16, int8_t, vld2q_s8)
1144 IMPL_LOAD2_TRANSPOSED(4, float, vld2q_f32)
1145 #undef IMPL_LOAD2_TRANSPOSED
1146 #endif
1147
1148 // Define commonly used aliases
1149 using float2 = Vec< 2, float>;
1150 using float4 = Vec< 4, float>;
1151 using float8 = Vec< 8, float>;
1152
1153 using double2 = Vec< 2, double>;
1154 using double4 = Vec< 4, double>;
1155 using double8 = Vec< 8, double>;
1156
1157 using byte2 = Vec< 2, uint8_t>;
1158 using byte4 = Vec< 4, uint8_t>;
1159 using byte8 = Vec< 8, uint8_t>;
1160 using byte16 = Vec<16, uint8_t>;
1161
1162 using int2 = Vec< 2, int32_t>;
1163 using int4 = Vec< 4, int32_t>;
1164 using int8 = Vec< 8, int32_t>;
1165
1166 using ushort2 = Vec< 2, uint16_t>;
1167 using ushort4 = Vec< 4, uint16_t>;
1168 using ushort8 = Vec< 8, uint16_t>;
1169
1170 using uint2 = Vec< 2, uint32_t>;
1171 using uint4 = Vec< 4, uint32_t>;
1172 using uint8 = Vec< 8, uint32_t>;
1173
1174 using long2 = Vec< 2, int64_t>;
1175 using long4 = Vec< 4, int64_t>;
1176 using long8 = Vec< 8, int64_t>;
1177
1178 // Use with from_half and to_half to convert between floatX, and use these for storage.
1179 using half2 = Vec< 2, uint16_t>;
1180 using half4 = Vec< 4, uint16_t>;
1181 using half8 = Vec< 8, uint16_t>;
1182
1183 } // namespace skvx
1184
1185 #undef SINTU
1186 #undef SINT
1187 #undef SIN
1188 #undef SIT
1189 #undef SI
1190 #undef SKVX_ALWAYS_INLINE
1191 #undef SKVX_USE_SIMD
1192
1193 #endif//SKVX_DEFINED