// Copyright 2022 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 SSE in [2, 4]
$assert not AVX or SSE == 4
$assert REQUANTIZATION == "FP32"
$assert DATATYPE in ["QC8", "QS8", "QU8"]
$assert VARIANT in ["LD64", "LD128"]
$assert MR <= 4
#include <assert.h>

$SSE_HEADER = {2: "emmintrin.h", 4: "smmintrin.h"}[SSE]
#include <${SSE_HEADER}>

#include "xnnpack/igemm.h"
#include "xnnpack/math.h"
#include "xnnpack/unaligned.h"


$DATATYPE_SPEC = {"QC8": "qs8_qc8w", "QS8": "qs8", "QU8": "qu8"}[DATATYPE]
$PARAMS_STRUCT = REQUANTIZATION.lower() + "_scalar"
$PARAMS_TYPE = "union xnn_qs8_qc8w_conv_minmax_params" if DATATYPE == "QC8" else "union xnn_%s_conv_minmax_params" % DATATYPE.lower()
$XINT8_T = "uint8_t" if DATATYPE == "QU8" else "int8_t"
$ISA = "avx" if AVX else {2: "sse2", 3: "ssse3", 4: "sse41"}[SSE]
void xnn_${DATATYPE_SPEC}_igemm_minmax_fp32_ukernel_${MR}x4c2s4__${ISA}_${VARIANT.lower()}(
    size_t mr,
    size_t nc,
    size_t kc,
    size_t ks,
    const ${XINT8_T}** restrict a,
    const void* restrict w,
    ${XINT8_T}* restrict c,
    size_t cm_stride,
    size_t cn_stride,
    size_t a_offset,
    const ${XINT8_T}* zero,
    const ${PARAMS_TYPE} params[restrict XNN_MIN_ELEMENTS(1)]) XNN_OOB_READS
{
  assert(mr != 0);
  assert(mr <= ${MR});
  assert(nc != 0);
  assert(kc != 0);
  assert(ks != 0);
  assert(ks % (${MR} * sizeof(void*)) == 0);
  assert(a_offset % sizeof(${XINT8_T}) == 0);
  assert(a != NULL);
  assert(w != NULL);
  assert(c != NULL);

  kc = round_up_po2(kc, 8 * sizeof(${XINT8_T}));
  ${XINT8_T}* c0 = c;
  $for M in range(1, MR):
    ${XINT8_T}* c${M} = (${XINT8_T}*) ((uintptr_t) c${M-1} + cm_stride);
    $if M % 2 == 0:
      if XNN_UNPREDICTABLE(mr <= ${M}) {
        c${M} = c${M-1};
      }
    $elif M + 1 == MR:
      if XNN_UNPREDICTABLE(mr != ${M+1}) {
        c${M} = c${M-1};
      }
    $else:
      if XNN_UNPREDICTABLE(mr < ${M+1}) {
        c${M} = c${M-1};
      }

  $if DATATYPE != "QC8":
    const __m128 vscale = _mm_set1_ps(params->${PARAMS_STRUCT}.scale);
    XNN_FORCE_REALIZATION(vscale);
  const __m128 voutput_max_less_zero_point = _mm_set1_ps((int32_t) params->${PARAMS_STRUCT}.output_max - (int32_t) params->${PARAMS_STRUCT}.output_zero_point);
  const __m128i voutput_zero_point = _mm_set1_epi16(params->${PARAMS_STRUCT}.output_zero_point);
  $if DATATYPE == "QU8":
    const __m128i voutput_min = _mm_set1_epi8(params->${PARAMS_STRUCT}.output_min);
  $else:
    $if SSE < 4:
      const __m128i voutput_min = _mm_set1_epi16(params->${PARAMS_STRUCT}.output_min);
    $if SSE == 4:
      const __m128i voutput_min = _mm_set1_epi8(params->${PARAMS_STRUCT}.output_min);
  XNN_FORCE_REALIZATION(voutput_max_less_zero_point);
  XNN_FORCE_REALIZATION(voutput_zero_point);
  XNN_FORCE_REALIZATION(voutput_min);

  $if DATATYPE == "QU8":
    const __m128i vb_zero_point = _mm_set1_epi16(params->${PARAMS_STRUCT}.kernel_zero_point);
    XNN_FORCE_REALIZATION(vb_zero_point);

  do {
    __m128i vacc0x0123 = _mm_loadu_si128((const __m128i*) w);
    $for M in range(1, MR):
      __m128i vacc${M}x0123 = vacc0x0123;
    w = (const void*) ((const int32_t*) w + 4);

    size_t p = ks;
    do {
      $for M in range(MR):
        const ${XINT8_T}* restrict a${M} = a[${M}];
        if XNN_UNPREDICTABLE(a${M} != zero) {
          a${M} = (const ${XINT8_T}*) ((uintptr_t) a${M} + a_offset);
        }
      a += ${MR};

      size_t k = kc;
      $if DATATYPE == "QU8":
        $if SSE < 4 or VARIANT == "LD128":
          const __m128i vzero = _mm_setzero_si128();
      do {
        $for M in range(MR):
          const __m128i va${M} = _mm_loadl_epi64((const __m128i*) a${M});
          $if DATATYPE == "QU8":
            $if SSE == 4:
              __m128i vxa${M} = _mm_cvtepu8_epi16(va${M});
            $else:
              __m128i vxa${M} = _mm_unpacklo_epi8(va${M}, vzero);
          $else:
            $if SSE == 4:
              __m128i vxa${M} = _mm_cvtepi8_epi16(va${M});
            $else:
              __m128i vxa${M} = _mm_srai_epi16(_mm_unpacklo_epi8(va${M}, va${M}), 8);
          a${M} += 8;

        $if VARIANT == "LD128":
          $for K in range(0, 4, 2):
            $if K == 0:
              const __m128i vb${K}${K+1} = _mm_loadu_si128((const __m128i*) w);
            $else:
              const __m128i vb${K}${K+1} = _mm_loadu_si128((const __m128i*) ((const ${XINT8_T}*) w + ${K * 8}));
            $if DATATYPE == "QU8":
              const __m128i vxb${K} = _mm_sub_epi16(_mm_unpacklo_epi8(vb${K}${K+1}, vzero), vb_zero_point);
              const __m128i vxb${K+1} = _mm_sub_epi16(_mm_unpackhi_epi8(vb${K}${K+1}, vzero), vb_zero_point);
            $elif SSE == 4:
              const __m128i vxb${K} = _mm_cvtepi8_epi16(vb${K}${K+1});
              const __m128i vxb${K+1} = _mm_srai_epi16(_mm_unpackhi_epi8(vb${K}${K+1}, vb${K}${K+1}), 8);
            $else:
              const __m128i vsb${K}${K+1} = _mm_cmpgt_epi8(_mm_setzero_si128(), vb${K}${K+1});
              const __m128i vxb${K} = _mm_unpacklo_epi8(vb${K}${K+1}, vsb${K}${K+1});
              const __m128i vxb${K+1} = _mm_unpackhi_epi8(vb${K}${K+1}, vsb${K}${K+1});

            $for M in range(MR):
              vacc${M}x0123 = _mm_add_epi32(vacc${M}x0123, _mm_madd_epi16(vxa${M}, vxb${K}));
              vxa${M} = _mm_shuffle_epi32(vxa${M}, _MM_SHUFFLE(0, 3, 2, 1));

            $for M in range(MR):
              vacc${M}x0123 = _mm_add_epi32(vacc${M}x0123, _mm_madd_epi16(vxa${M}, vxb${K+1}));
              $if K + 2 != 4:
                vxa${M} = _mm_shuffle_epi32(vxa${M}, _MM_SHUFFLE(0, 3, 2, 1));
        $else:
          $for K in range(4):
            $if K == 0:
              const __m128i vb${K} = _mm_loadl_epi64((const __m128i*) w);
            $else:
              const __m128i vb${K} = _mm_loadl_epi64((const __m128i*) ((const ${XINT8_T}*) w + ${K * 8}));
            $if DATATYPE == "QU8":
              $if SSE == 4:
                const __m128i vxb${K} = _mm_sub_epi16(_mm_cvtepu8_epi16(vb${K}), vb_zero_point);
              $else:
                const __m128i vxb${K} = _mm_sub_epi16(_mm_unpacklo_epi8(vb${K}, vzero), vb_zero_point);
            $else:
              $if SSE == 4:
                const __m128i vxb${K} = _mm_cvtepi8_epi16(vb${K});
              $else:
                const __m128i vxb${K} = _mm_srai_epi16(_mm_unpacklo_epi8(vb${K}, vb${K}), 8);

            $for M in range(MR):
              vacc${M}x0123 = _mm_add_epi32(vacc${M}x0123, _mm_madd_epi16(vxa${M}, vxb${K}));
              $if K + 1 != 4:
                vxa${M} = _mm_shuffle_epi32(vxa${M}, _MM_SHUFFLE(0, 3, 2, 1));

        w = (const void*) ((const ${XINT8_T}*) w + 32);
        k -= 8 * sizeof(${XINT8_T});
      } while (k != 0);
      p -= ${MR} * sizeof(void*);
    } while (p != 0);

    $for M in range(MR):
      __m128 vscaled${M}x0123 = _mm_cvtepi32_ps(vacc${M}x0123);

    $if DATATYPE == "QC8":
      const __m128 vscale0123 = _mm_loadu_ps((const float*) w);
      w = (const float*) w + 4;
      $for M in range(MR):
        vscaled${M}x0123 = _mm_mul_ps(vscaled${M}x0123, vscale0123);
    $else:
      $for M in range(MR):
        vscaled${M}x0123 = _mm_mul_ps(vscaled${M}x0123, vscale);

    $for M in range(MR):
      vscaled${M}x0123 = _mm_min_ps(vscaled${M}x0123, voutput_max_less_zero_point);

    $for M in range(MR):
      vacc${M}x0123 = _mm_cvtps_epi32(vscaled${M}x0123);

    $for M in range(0, MR, 2):
      __m128i vacc${M}${min(M+1, MR-1)}x0123 = _mm_adds_epi16(_mm_packs_epi32(vacc${M}x0123, vacc${min(M+1, MR-1)}x0123), voutput_zero_point);

    $if DATATYPE == "QU8":
      $if MR > 2:
        __m128i vout = _mm_packus_epi16(vacc0${min(1, MR-1)}x0123, vacc${min(2, MR-1)}${min(3, MR-1)}x0123);
      $else:
        __m128i vout = _mm_packus_epi16(vacc0${min(1, MR-1)}x0123, vacc0${min(1, MR-1)}x0123);

      vout = _mm_max_epu8(vout, voutput_min);
    $else:
      $if SSE < 4:
        $for M in range(0, MR, 2):
          vacc${M}${min(M+1, MR-1)}x0123 = _mm_max_epi16(vacc${M}${min(M+1, MR-1)}x0123, voutput_min);

      $if MR > 2:
        __m128i vout = _mm_packs_epi16(vacc0${min(1, MR-1)}x0123, vacc${min(2, MR-1)}${min(3, MR-1)}x0123);
      $else:
        __m128i vout = _mm_packs_epi16(vacc0${min(1, MR-1)}x0123, vacc0${min(1, MR-1)}x0123);

      $if SSE == 4:
        vout = _mm_max_epi8(vout, voutput_min);

    if (nc >= 4) {
      $for M in reversed(range(1, MR)):
        $if SSE == 4:
          unaligned_store_u32(c${M}, (uint32_t) _mm_extract_epi32(vout, ${M}));
        $else:
          unaligned_store_u32(c${M}, (uint32_t) _mm_cvtsi128_si32(_mm_shuffle_epi32(vout, _MM_SHUFFLE(${M}, ${M}, ${M}, ${M}))));
        c${M} = (${XINT8_T}*) ((uintptr_t) c${M} + cn_stride);
      unaligned_store_u32(c0, (uint32_t) _mm_cvtsi128_si32(vout));
      c0 = (${XINT8_T}*) ((uintptr_t) c0 + cn_stride);

      a = (const ${XINT8_T}**restrict) ((uintptr_t) a - ks);

      nc -= 4;
    } else {
      if (nc & 2) {
        $for M in reversed(range(MR)):
          unaligned_store_u16(c${M}, (uint16_t) _mm_extract_epi16(vout, ${M * 2}));
          c${M} += 2;
        vout = _mm_srli_epi32(vout, 16);
      }
      if (nc & 1) {
        $if SSE == 4:
          $for M in reversed(range(MR)):
            *c${M} = (${XINT8_T}) _mm_extract_epi8(vout, ${M * 4});
        $else:
          $for M in reversed(range(1, MR)):
            *c${M} = (${XINT8_T}) _mm_extract_epi16(vout, ${M * 2});
          *c0 = (${XINT8_T}) _mm_cvtsi128_si32(vout);
      }

      nc = 0;
    }
  } while (nc != 0);
}
