// Copyright 2021 Google LLC
//
// This source code is licensed under the BSD-style license found in the
// LICENSE file in the root directory of this source tree.

$assert BATCH_TILE % 8 == 0
$assert BATCH_TILE >= 8
$ABC = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
#include <assert.h>

#include <immintrin.h>

#include <xnnpack/common.h>
#include <xnnpack/unaligned.h>
#include <xnnpack/vcvt.h>


$XINT8_T = {"QS8": "int8_t", "QU8": "uint8_t"}[DATATYPE]
$_MM_CVTEPX8_EPI32 = {"QS8": "_mm_cvtepi8_epi32", "QU8": "_mm_cvtepu8_epi32"}[DATATYPE]
void xnn_${DATATYPE.lower()}_f32_vcvt_ukernel__sse41_x${BATCH_TILE}(
    size_t n,
    const ${XINT8_T}* x,
    float* y,
    const union xnn_${DATATYPE.lower()}_f32_cvt_params params[restrict XNN_MIN_ELEMENTS(1)]) XNN_OOB_READS
{
  assert(n != 0);
  assert(n % sizeof(${XINT8_T}) == 0);
  assert(x != NULL);
  assert(y != NULL);

  const __m128i vminus_zero_point = _mm_load_si128((const __m128i*) params->sse4.minus_zero_point);
  const __m128 vscale = _mm_load_ps(params->sse4.scale);
  $if BATCH_TILE > 4:
    for (; n >= ${BATCH_TILE} * sizeof(${XINT8_T}); n -= ${BATCH_TILE} * sizeof(${XINT8_T})) {
      __m128i vx${ABC[0:4]} = ${_MM_CVTEPX8_EPI32}(_mm_cvtsi32_si128((int) unaligned_load_s32(x)));
      $for N in range(4, BATCH_TILE, 4):
        __m128i vx${ABC[N:N+4]} = ${_MM_CVTEPX8_EPI32}(_mm_cvtsi32_si128((int) unaligned_load_s32(x + ${N})));
      x += ${BATCH_TILE};

      $for N in range(0, BATCH_TILE, 4):
        vx${ABC[N:N+4]} = _mm_add_epi32(vx${ABC[N:N+4]}, vminus_zero_point);

      $for N in range(0, BATCH_TILE, 4):
        __m128 vy${ABC[N:N+4]} = _mm_cvtepi32_ps(vx${ABC[N:N+4]});

      $for N in range(0, BATCH_TILE, 4):
        vy${ABC[N:N+4]} = _mm_mul_ps(vy${ABC[N:N+4]}, vscale);

      _mm_storeu_ps(y, vy${ABC[0:4]});
      $for N in range(4, BATCH_TILE, 4):
        _mm_storeu_ps(y + ${N}, vy${ABC[N:N+4]});
      y += ${BATCH_TILE};
    }
  for (; n >= 4 * sizeof(${XINT8_T}); n -= 4 * sizeof(${XINT8_T})) {
    __m128i vx = ${_MM_CVTEPX8_EPI32}(_mm_cvtsi32_si128((int) unaligned_load_s32(x)));
    vx = _mm_add_epi32(vx, vminus_zero_point);
    x += 4;

    __m128 vy = _mm_cvtepi32_ps(vx);
    vy = _mm_mul_ps(vy, vscale);

    _mm_storeu_ps(y, vy);
    y += 4;
  }
  if XNN_UNLIKELY(n != 0) {
    assert(n >= 1 * sizeof(${XINT8_T}));
    assert(n <= 3 * sizeof(${XINT8_T}));

    __m128i vx = ${_MM_CVTEPX8_EPI32}(_mm_cvtsi32_si128((int) unaligned_load_s32(x)));
    vx = _mm_add_epi32(vx, vminus_zero_point);

    __m128 vy = _mm_cvtepi32_ps(vx);
    vy = _mm_mul_ps(vy, vscale);

    if (n & (2 * sizeof(${XINT8_T}))) {
      _mm_storel_pi((__m64*) y, vy);
      vy = _mm_movehl_ps(vy, vy);
      y += 2;
    }
    if (n & (1 * sizeof(${XINT8_T}))) {
      _mm_store_ss(y, vy);
    }
  }
}
