xref: /aosp_15_r20/external/XNNPACK/src/f16-vclamp/f16c.c.in (revision 4bdc94577ba0e567308109d787f7fec7b531ce36)
1// Copyright 2022 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$assert BATCH_TILE % 8 == 0
7$assert BATCH_TILE >= 8
8$ABC = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
9#include <assert.h>
10
11#include <immintrin.h>
12
13#include <xnnpack/common.h>
14#include <xnnpack/intrinsics-polyfill.h>
15#include <xnnpack/vunary.h>
16
17
18void xnn_f16_vclamp_ukernel__f16c_x${BATCH_TILE}(
19    size_t n,
20    const void* restrict x_ptr,
21    void* restrict y_ptr,
22    const union xnn_f16_minmax_params params[restrict XNN_MIN_ELEMENTS(1)]) XNN_OOB_READS
23{
24  assert(n != 0);
25  assert(n % sizeof(uint16_t) == 0);
26  assert(x_ptr != NULL);
27  assert(y_ptr != NULL);
28
29  const uint16_t* x = (const uint16_t*) x_ptr;
30  uint16_t* y = (uint16_t*) y_ptr;
31
32  const __m256 vy_min = _mm256_load_ps(params->avx.min);
33  const __m256 vy_max = _mm256_load_ps(params->avx.max);
34
35  $if BATCH_TILE > 8:
36    for (; n >= ${BATCH_TILE} * sizeof(uint16_t); n -= ${BATCH_TILE} * sizeof(uint16_t)) {
37      __m256 vacc${ABC[0:8]} = _mm256_cvtph_ps(_mm_loadu_si128((const __m128i*) x));
38      $for N in range(8, BATCH_TILE, 8):
39        __m256 vacc${ABC[N:N+8]} = _mm256_cvtph_ps(_mm_loadu_si128((const __m128i*) (x + ${N})));
40      x += ${BATCH_TILE};
41
42      $for N in range(0, BATCH_TILE, 8):
43        vacc${ABC[N:N+8]} = _mm256_max_ps(vacc${ABC[N:N+8]}, vy_min);
44
45      $for N in range(0, BATCH_TILE, 8):
46        vacc${ABC[N:N+8]} = _mm256_min_ps(vacc${ABC[N:N+8]}, vy_max);
47
48      _mm_storeu_si128((__m128i*) y, _mm256_cvtps_ph(vacc${ABC[0:8]}, _MM_FROUND_NO_EXC));
49      $for N in range(8, BATCH_TILE, 8):
50        _mm_storeu_si128((__m128i*) (y + ${N}), _mm256_cvtps_ph(vacc${ABC[N:N+8]}, _MM_FROUND_NO_EXC));
51      y += ${BATCH_TILE};
52    }
53  for (; n >= 8 * sizeof(uint16_t); n -= 8 * sizeof(uint16_t)) {
54    __m256 vacc = _mm256_cvtph_ps(_mm_loadu_si128((const __m128i*) x));
55    x += 8;
56    vacc = _mm256_max_ps(vacc, vy_min);
57    vacc = _mm256_min_ps(vacc, vy_max);
58    _mm_storeu_si128((__m128i*) y, _mm256_cvtps_ph(vacc, _MM_FROUND_NO_EXC));
59    y += 8;
60  }
61  if XNN_UNLIKELY(n != 0) {
62    __m256 vacc = _mm256_cvtph_ps(_mm_loadu_si128((const __m128i*) x));
63    vacc = _mm256_max_ps(vacc, vy_min);
64    vacc = _mm256_min_ps(vacc, vy_max);
65
66    __m128i vh = _mm256_cvtps_ph(vacc, _MM_FROUND_NO_EXC);
67    if (n & (4 * sizeof(uint16_t))) {
68      _mm_storel_epi64((__m128i*) y, vh);
69      vh = _mm_unpackhi_epi64(vh, vh);
70      y += 4;
71    }
72    if (n & (2 * sizeof(uint16_t))) {
73      _mm_storeu_si32(y, vh);
74      vh = _mm_srli_epi64(vh, 32);
75      y += 2;
76    }
77    if (n & (1 * sizeof(uint16_t))) {
78      *y = _mm_extract_epi16(vh, 0);
79    }
80  }
81}
82