xref: /aosp_15_r20/external/XNNPACK/src/math/cvt-f16-f32-wasmsimd-int16.c (revision 4bdc94577ba0e567308109d787f7fec7b531ce36)
1 // Copyright 2021 Google LLC
2 //
3 // This source code is licensed under the BSD-style license found in the
4 // LICENSE file in the root directory of this source tree.
5 
6 #include <assert.h>
7 #include <stddef.h>
8 #include <stdint.h>
9 
10 #include <wasm_simd128.h>
11 
12 #include <xnnpack/math-stubs.h>
13 
14 
xnn_math_f16_f32_cvt__wasmsimd_int16(size_t n,const void * input,float * output)15 void xnn_math_f16_f32_cvt__wasmsimd_int16(
16     size_t n,
17     const void* input,
18     float* output)
19 {
20   assert(n % (8 * sizeof(float)) == 0);
21 
22   const v128_t vsign_mask = wasm_i16x8_const_splat(0x8000);
23   const v128_t vexp_offset = wasm_i16x8_const_splat(0x7000);
24   const v128_t vexp_scale = wasm_f32x4_const_splat(0x1.0p-112f);
25   const v128_t vmagic_mask = wasm_i16x8_const_splat(0x3F00);
26   const v128_t vmagic_bias = wasm_f32x4_const_splat(0.5f);
27   const v128_t vdenorm_cutoff = wasm_i16x8_const_splat(0x0400);
28 
29   const uint16_t* i = (const uint16_t*) input;
30   for (; n != 0; n -= 8 * sizeof(float)) {
31     const v128_t vh = wasm_v128_load(i);
32     i += 8;
33 
34     const v128_t vsign = wasm_v128_and(vh, vsign_mask);
35 
36     const v128_t vnonsign = wasm_v128_xor(vh, vsign);
37 
38     const v128_t vprenorm_lo = wasm_i16x8_shl(vnonsign, 13);
39     const v128_t vprenorm_hi = wasm_i16x8_add(wasm_u16x8_shr(vnonsign, 3), vexp_offset);
40 
41     const v128_t vnorm_lo = wasm_f32x4_mul(wasm_v16x8_shuffle(vprenorm_lo, vprenorm_hi, 0,  8, 1,  9, 2, 10, 3, 11), vexp_scale);
42     const v128_t vnorm_hi = wasm_f32x4_mul(wasm_v16x8_shuffle(vprenorm_lo, vprenorm_hi, 4, 12, 5, 13, 6, 14, 7, 15), vexp_scale);
43 
44     const v128_t vdenorm_lo = wasm_f32x4_sub(wasm_v16x8_shuffle(vnonsign, vmagic_mask, 0,  8, 1,  9, 2, 10, 3, 11), vmagic_bias);
45     const v128_t vdenorm_hi = wasm_f32x4_sub(wasm_v16x8_shuffle(vnonsign, vmagic_mask, 4, 12, 5, 13, 6, 14, 7, 15), vmagic_bias);
46 
47     const v128_t vmask = wasm_i16x8_gt(vnonsign, vdenorm_cutoff);
48     const v128_t vmask_lo = wasm_i32x4_extend_low_i16x8(vmask);
49     const v128_t vmask_hi = wasm_i32x4_extend_high_i16x8(vmask);
50 
51     const v128_t vzero = wasm_i16x8_const_splat(0);
52     const v128_t vf_lo = wasm_v128_or(wasm_v16x8_shuffle(vzero, vsign, 0,  8, 1,  9, 2, 10, 3, 11),
53       wasm_v128_bitselect(vnorm_lo, vdenorm_lo, vmask_lo));
54     const v128_t vf_hi = wasm_v128_or(wasm_v16x8_shuffle(vzero, vsign, 4, 12, 5, 13, 6, 14, 7, 15),
55       wasm_v128_bitselect(vnorm_hi, vdenorm_hi, vmask_hi));
56 
57     wasm_v128_store(output, vf_lo);
58     wasm_v128_store(output + 4, vf_hi);
59     output += 8;
60   }
61 }
62