// Copyright 2024 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.

$ABC = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
$assert REQUANTIZATION == "FP32" or not REQUANTIZATION
$assert DATATYPE in ["QC4_F32"]
$assert SSE in [3, 4]
#include <assert.h>

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

#include "xnnpack/gemm.h"
#include "xnnpack/intrinsics-polyfill.h"
#include "xnnpack/math.h"
#include "xnnpack/unaligned.h"
$if PREFETCH:
  #include "xnnpack/prefetch.h"


$DATATYPE_SPEC = {"QC8": "qs8_qc8w", "QU8": "qu8", "QD8_F16" : "qd8_f16_qc8w", "QD8_F32": "qd8_f32_qc8w", "QC4_F16": "qd8_f16_qc4w", "QC4_F32": "qd8_f32_qc4w"}[DATATYPE]
$REQUANTIZATION_SPEC = "_" + REQUANTIZATION.lower() if REQUANTIZATION else ""
$PARAMS_STRUCT = REQUANTIZATION.lower() + "_scalar" if REQUANTIZATION else "scalar"
$PARAMS_TYPE = {"QC8": "union xnn_qs8_qc8w_conv_minmax_params", "QU8": "union xnn_qu8_conv_minmax_params", "QD8_F16": "union xnn_f16_minmax_params", "QD8_F32": "union xnn_f32_minmax_params", "QC4_F16": "struct xnn_f16_qc4w_minmax_params", "QC4_F32": "struct xnn_f32_qc4w_minmax_params"}[DATATYPE]
$XINT8_T = "uint8_t" if DATATYPE == "QU8" else "int8_t"
$OUT_T = {"QC8": "int8_t", "QD8_F16": "xnn_float16", "QD8_F32": "float", "QC4_F16": "xnn_float16", "QC4_F32": "float", "QU8": "uint8_t"}[DATATYPE]
$_MM_PACKXS_EPI16 = "_mm_packus_epi16" if DATATYPE == "QU8" else "_mm_packs_epi16"
$_MM_MAX_EPX8 = "_mm_max_epu8" if DATATYPE == "QU8" else "_mm_max_epi8"
$_MM_CVTXEPI32_EPI8 = "_mm_cvtusepi32_epi8" if DATATYPE == "QU8" else "_mm_cvtsepi32_epi8"
$_MM_DPBUSD_EPI32 = "_mm_dpbusd_epi32_madd" if VARIANT == "MADD" else   "_mm_dpbusd_avx_epi32" if AVX == 2 else "_mm_dpbusd_epi32"
$ISA = "sse41" if SSE == 4 else "ssse3"
void xnn_${DATATYPE_SPEC}_gemm_minmax${REQUANTIZATION_SPEC}_ukernel_${MR}x4c8__${ISA}${"_madd" if VARIANT == "MADD" else ""}${"_prfm" if PREFETCH else ""}(
    size_t mr,
    size_t nc,
    size_t kc,
    const ${XINT8_T}* restrict a,
    size_t a_stride,
    const void* restrict w,
    ${OUT_T}* restrict c,
    size_t cm_stride,
    size_t cn_stride,
    $if DATATYPE in ["QD8_F16", "QD8_F32", "QC4_F16", "QC4_F32"]:
      const ${PARAMS_TYPE} params[restrict XNN_MIN_ELEMENTS(1)],
      const struct xnn_qd8_quantization_params quantization_params[restrict XNN_MIN_ELEMENTS(1)]) XNN_OOB_READS
    $else:
      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(kc % sizeof(${XINT8_T}) == 0);
  assert(a != NULL);
  assert(w != NULL);
  assert(c != NULL);

  kc = round_up_po2(kc, 8 * sizeof(int8_t));
  const ${XINT8_T}* a0 = a;
  $if DATATYPE in ["QD8_F16", "QC4_F16"]:
    uint16_t* c0 = (uint16_t*) c;
  $else:
    ${OUT_T}* c0 = c;
  $for M in range(1, MR):
    const ${XINT8_T}* a${M} = (const ${XINT8_T}*) ((uintptr_t) a${M-1} + a_stride);
    $if DATATYPE in ["QD8_F16", "QC4_F16"]:
      uint16_t* c${M} = (uint16_t*) ((uintptr_t) c${M-1} + cm_stride);
    $else:
      ${OUT_T}* c${M} = (${OUT_T}*) ((uintptr_t) c${M-1} + cm_stride);
    $if M % 2 == 0:
      if XNN_UNPREDICTABLE(mr <= ${M}) {
        a${M} = a${M-1};
        c${M} = c${M-1};
      }
    $elif M + 1 == MR:
      if XNN_UNPREDICTABLE(mr != ${M+1}) {
        a${M} = a${M-1};
        c${M} = c${M-1};
      }
    $else:
      if XNN_UNPREDICTABLE(mr < ${M+1}) {
        a${M} = a${M-1};
        c${M} = c${M-1};
      }

  $if DATATYPE in ["QD8_F16", "QD8_F32", "QC4_F16", "QC4_F32"]:
    $for M in range(MR):
      const __m128i vinput_zero_point${M} = _mm_set1_epi32((int) quantization_params[${M}].zero_point);
    $if "F16" in DATATYPE:
      const __m128 voutput_min = _mm_cvtph_ps(_mm_set1_epi16(*(const uint16_t*) &params->scalar.min));
      const __m128 voutput_max = _mm_cvtph_ps(_mm_set1_epi16(*(const uint16_t*) &params->scalar.max));
    $else:
      const __m128 voutput_min = _mm_set1_ps(params->scalar.min);
      const __m128 voutput_max = _mm_set1_ps(params->scalar.max);
    $if DATATYPE in ["QC4_F16", "QC4_F32"]:
      $if VARIANT == "MADD":
        const __m128i vmask = _mm_set1_epi8(0x0F);
      $else:
        const __m128i vmask = _mm_set1_epi8(0xF0);
      XNN_FORCE_REALIZATION(vmask);
      $if GFNI:
        const __m128i vshl4 = _mm_set1_epi64x(0x01020408);
        XNN_FORCE_REALIZATION(vshl4);
  $else:
    const __m128i vsign_mask = _mm_set1_epi8(0x80);
    XNN_FORCE_REALIZATION(vsign_mask);
    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_epi32(params->${PARAMS_STRUCT}.output_zero_point);
    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);
  do {
    $if DATATYPE in ["QD8_F16", "QD8_F32", "QC4_F16", "QC4_F32"]:
      const __m128i vksum0123 = _mm_load_si128(w);
      $if SSE == 4:
        $for M in range(MR):
          const __m128i vsum${M}x0123 = _mm_mullo_epi32(vksum0123, vinput_zero_point${M});
          __m128i vacc${M}x01 = _mm_unpacklo_epi32(vsum${M}x0123, _mm_setzero_si128());
          __m128i vacc${M}x23 = _mm_unpackhi_epi32(vsum${M}x0123, _mm_setzero_si128());
      $else:
        const __m128i vksum13 = _mm_shuffle_epi32(vksum0123, 0xF5);
        $for M in range(MR):
          const __m128i vsum${M}x02 = _mm_mul_epu32(vksum0123, vinput_zero_point${M});
          const __m128i vsum${M}x13 = _mm_mul_epu32(vksum13, vinput_zero_point${M});
          const __m128i vsum${M}x01 = _mm_unpacklo_epi32(vsum${M}x02, vsum${M}x13);
          const __m128i vsum${M}x23 = _mm_unpackhi_epi32(vsum${M}x02, vsum${M}x13);
          __m128i vacc${M}x01 = _mm_unpacklo_epi32(vsum${M}x01, _mm_setzero_si128());
          __m128i vacc${M}x23 = _mm_unpacklo_epi32(vsum${M}x23, _mm_setzero_si128());
    $else:
      __m128i vacc0x01 = _mm_unpacklo_epi32(vsum${M}x0123, _mm_setzero_si128());
      __m128i vacc0x23 = _mm_unpackhi_epi32(vsum${M}x0123, _mm_setzero_si128());
      $for M in range(1, MR):
        __m128i vacc${M}x01 = vacc0x01;
        __m128i vacc${M}x23 = vacc0x23;
    $if MR < 3:
      $for M in range(MR):
        __m128i vacc1x${M}x01 = _mm_setzero_si128();
        __m128i vacc1x${M}x23 = _mm_setzero_si128();
    w = (const int32_t*) w + 4;

    size_t k = kc;
    while (k >= 16 * sizeof(int8_t)) {
      $for M in range(MR):
        $if DATATYPE in ["QD8_F16", "QD8_F32", "QC4_F16", "QC4_F32"]:
          const __m128i va${M}x01234567 = _mm_set1_epi64x((int64_t) unaligned_load_u64(a${M}));
          const __m128i va${M}x89ABCDEF = _mm_set1_epi64x((int64_t) unaligned_load_u64(a${M} + 8));
        $else:
          const __m128i va${M}x01234567 = _mm_xor_si128(_mm_set1_epi64x((int64_t) unaligned_load_u64(a${M})), vsign_mask);
          const __m128i va${M}x89ABCDEF = _mm_xor_si128(_mm_set1_epi64x((int64_t) unaligned_load_u64(a${M} + 8)), vsign_mask);
        a${M} += 16;

      $if DATATYPE in ["QC4_F16", "QC4_F32"]:
        const __m128i vbb01234567x0123 = _mm_load_si128(w);
        const __m128i vbb89ABCDEFx0123 = _mm_load_si128((const __m128i*) ((const ${XINT8_T}*) w + 16));
        $if GFNI:
          const __m128i vb01234567x01 = _mm_gf2p8affine_epi64_epi8(vbb01234567x0123, vshl4, 0);
          const __m128i vb89ABCDEFx01 = _mm_gf2p8affine_epi64_epi8(vbb89ABCDEFx0123, vshl4, 0);
          const __m128i vb01234567x23 = _mm_and_si128(vbb01234567x0123, vmask);
          const __m128i vb89ABCDEFx23 = _mm_and_si128(vbb89ABCDEFx0123, vmask);
        $elif VARIANT == "MADD":
          const __m128i vbs01234567x01 = _mm_srli_epi32(vbb01234567x0123, 4);
          const __m128i vbs89ABCDEFx01 = _mm_srli_epi32(vbb89ABCDEFx0123, 4);
          const __m128i vb01234567x01 = _mm_and_si128(vbb01234567x0123, vmask);
          const __m128i vb89ABCDEFx01 = _mm_and_si128(vbb89ABCDEFx0123, vmask);
          const __m128i vb01234567x23 = _mm_and_si128(vbs01234567x01, vmask);
          const __m128i vb89ABCDEFx23 = _mm_and_si128(vbs89ABCDEFx01, vmask);
        $else:
          const __m128i vbs01234567x01 = _mm_slli_epi32(vbb01234567x0123, 4);
          const __m128i vbs89ABCDEFx01 = _mm_slli_epi32(vbb89ABCDEFx0123, 4);
          const __m128i vb01234567x23 = _mm_and_si128(vbb01234567x0123, vmask);
          const __m128i vb89ABCDEFx23 = _mm_and_si128(vbb89ABCDEFx0123, vmask);
          const __m128i vb01234567x01 = _mm_and_si128(vbs01234567x01, vmask);
          const __m128i vb89ABCDEFx01 = _mm_and_si128(vbs89ABCDEFx01, vmask);
      $else:
        const __m128i vb01234567x01 = _mm_load_si128(w);
        const __m128i vb89ABCDEFx01 = _mm_load_si128((const __m128i*) ((const ${XINT8_T}*) w + 16));
        const __m128i vb01234567x23 = _mm_load_si128((const __m128i*) ((const ${XINT8_T}*) w + 32));
        const __m128i vb89ABCDEFx23 = _mm_load_si128((const __m128i*) ((const ${XINT8_T}*) w + 48));
        $if PREFETCH:
          xnn_prefetch_to_l1((const ${XINT8_T}*) w + 896);

      $for M in range(MR):
        vacc${M}x01 = ${_MM_DPBUSD_EPI32}(vacc${M}x01, va${M}x01234567, vb01234567x01);
        vacc${M}x23 = ${_MM_DPBUSD_EPI32}(vacc${M}x23, va${M}x01234567, vb89ABCDEFx01);
      $if PREFETCH:
        xnn_prefetch_to_l1((const ${XINT8_T}*) w + 960);
      $for M in range(MR):
        $if MR < 3:
          vacc1x${M}x01 = ${_MM_DPBUSD_EPI32}(vacc1x${M}x01, va${M}x89ABCDEF, vb01234567x23);
          vacc1x${M}x23 = ${_MM_DPBUSD_EPI32}(vacc1x${M}x23, va${M}x89ABCDEF, vb89ABCDEFx23);
        $else:
          vacc${M}x01 = ${_MM_DPBUSD_EPI32}(vacc${M}x01, va${M}x89ABCDEF, vb01234567x23);
          vacc${M}x23 = ${_MM_DPBUSD_EPI32}(vacc${M}x23, va${M}x89ABCDEF, vb89ABCDEFx23);

      $if DATATYPE in ["QC4_F16", "QC4_F32"]:
        w = (const ${XINT8_T}*) w + 32;
      $else:
        w = (const ${XINT8_T}*) w + 64;
      k -= 16 * sizeof(${XINT8_T});
    }

    if (k != 0) {
      $for M in range(MR):
        $if DATATYPE in ["QD8_F16", "QD8_F32", "QC4_F16", "QC4_F32"]:
          const __m128i va${M}x01234567 = _mm_set1_epi64x((int64_t) unaligned_load_u64(a${M}));
        $else:
          const __m128i va${M}x89ABCDEF = _mm_xor_si128(_mm_set1_epi64x((int64_t) unaligned_load_u64(a${M} + 8)), vsign_mask);
        a${M} += 8;

      $if DATATYPE in ["QC4_F16", "QC4_F32"]:
        const __m128i vbb01234567x0123 = _mm_load_si128(w);
        const __m128i vbb89ABCDEFx0123 = _mm_load_si128((const __m128i*) ((const ${XINT8_T}*) w + 16));
        $if GFNI:
          const __m128i vb01234567x01 = _mm_gf2p8affine_epi64_epi8(vbb01234567x0123, vshl4, 0);
          const __m128i vb89ABCDEFx01 = _mm_gf2p8affine_epi64_epi8(vbb89ABCDEFx0123, vshl4, 0);
        $elif VARIANT == "MADD":
          const __m128i vb01234567x01 = _mm_and_si128(vbb01234567x0123, vmask);
          const __m128i vb89ABCDEFx01 = _mm_and_si128(vbb89ABCDEFx0123, vmask);
        $else:
          const __m128i vb01234567x01 = _mm_slli_epi32(vbb01234567x0123, 4);
          const __m128i vb89ABCDEFx01 = _mm_slli_epi32(vbb89ABCDEFx0123, 4);
      $else:
        const __m128i vb01234567x01 = _mm_load_si128(w);
        const __m128i vb89ABCDEFx01 = _mm_load_si128((const __m128i*) ((const ${XINT8_T}*) w + 16));

      $for M in range(MR):
        vacc${M}x01 = ${_MM_DPBUSD_EPI32}(vacc${M}x01, va${M}x01234567, vb01234567x01);
        vacc${M}x23 = ${_MM_DPBUSD_EPI32}(vacc${M}x23, va${M}x01234567, vb89ABCDEFx01);
      $if PREFETCH:
        xnn_prefetch_to_l1((const ${XINT8_T}*) w + 960);

      w = (const ${XINT8_T}*) w + 32;
      k -= 8 * sizeof(${XINT8_T});
    }
    $if MR < 3:
      $for M in range(MR):
        vacc${M}x01 = _mm_add_epi32(vacc${M}x01, vacc1x${M}x01);
        vacc${M}x23 = _mm_add_epi32(vacc${M}x23, vacc1x${M}x23);

    // Add adjacent pairs
    $for M in range(MR):
      __m128i vacc${M}x0123 = _mm_hadd_epi32(vacc${M}x01, vacc${M}x23);

    $if DATATYPE in ["QC4_F16", "QC4_F32"] and VARIANT != "MADD":
      $for M in range(MR):
        vacc${M}x0123 = _mm_srai_epi32(vacc${M}x0123, 4);
    $for M in range(MR):
      __m128 vout${M}x0123 = _mm_cvtepi32_ps(vacc${M}x0123);

    $if DATATYPE in ["QD8_F16", "QD8_F32", "QC4_F16", "QC4_F32"]:
      $for M in range(MR):
        vout${M}x0123 = _mm_mul_ps(vout${M}x0123, _mm_set1_ps(quantization_params[${M}].inv_scale));

      const __m128 vfilter_output_scale0123 = _mm_load_ps((const float*) w);
      const __m128 vbias0123 = _mm_load_ps((const float*) w + 4);
      w = (const float*) w + 8;

      $for M in range(MR):
        vout${M}x0123 = _mm_add_ps(_mm_mul_ps(vout${M}x0123, vfilter_output_scale0123), vbias0123);

      $for M in range(MR):
        vout${M}x0123 = _mm_max_ps(vout${M}x0123, voutput_min);

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

      $if DATATYPE in ["QC4_F16", "QD8_F16"]:
        $for M in range(MR):
          __m128i vfp16out${M}x0123 = _mm_cvtps_ph(vout${M}x0123, _MM_FROUND_TO_NEAREST_INT);
        if XNN_LIKELY(nc >= 4) {
          $for M in range(MR):
            _mm_storeu_si128((__m128i*) c${M}, vfp16out${M}x0123);
            a${M} = (const ${XINT8_T}*) ((uintptr_t) a${M} - kc);
            c${M} = (uint16_t*) ((uintptr_t) c${M} + cn_stride);
          nc -= 4;
        } else {
          $if SSE >= 3:
            if (nc & 2) {
              $for M in range(MR):
                _mm_storeu_si32(c${M}, vfp16out${M}x0123);
                c${M} += 2;
                vfp16out${M}x0123 = _mm_srli_epi64(vfp16out${M}x0123, 32);
            }
            if (nc & 1) {
              $for M in range(MR):
                *c${M} = (uint16_t) _mm_extract_epi16(vfp16out${M}x0123, 0);
            }
          $else:
            // Prepare mask for valid 16-bit elements (depends on nc).
            const __mmask8 vmask = _cvtu32_mask8((UINT32_C(1) << nc) - 1);
            $for M in range(MR):
              _mm_mask_storeu_epi16(c${M}, vmask, vfp16out${M}x0123);
          nc = 0;
        }
      $else:
        if XNN_LIKELY(nc >= 4) {
          $for M in range(MR):
            _mm_storeu_ps(c${M}, vout${M}x0123);
            a${M} = (const int8_t*) ((uintptr_t) a${M} - kc);
            c${M} = (float*) ((uintptr_t) c${M} + cn_stride);
          nc -= 4;
        } else {
          $if SSE >= 3:
            if (nc & 2) {
              $for M in range(MR):
                _mm_storel_pi((__m64*) c${M}, vout${M}x0123);
                c${M} += 2;
                vout${M}x0123 = _mm_movehl_ps(vout${M}x0123, vout${M}x0123);
            }
            if (nc & 1) {
              $for M in range(MR):
                _mm_store_ss(c${M}, vout${M}x0123);
            }
          $else:
            // Prepare mask for valid 32-bit elements (depends on nc).
            const __mmask16 vmask = _cvtu32_mask16((UINT32_C(1) << nc) - 1);
            $for M in range(MR):
              _mm_mask_storeu_ps(c${M}, vmask, vout${M}x0123);
          nc = 0;
        }
    $else:
      const __m128 vscale0123 = _mm_load_ps(w);
      w = (const float*) w + 4;
      $for M in range(MR):
        vout${M}x0123 = _mm_mul_ps(vout${M}x0123, vscale0123);

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

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

      $for M in range(MR):
        vacc${M}x0123 = _mm_add_epi32(vacc${M}x0123, voutput_zero_point);

      $if SSE >= 3:
        $for M in range(MR):
          vacc${M}x0123 = _mm_packs_epi32(vacc${M}x0123, vacc${M}x0123);
          __m128i voutb${M}x0123 = _mm_packs_epi16(vacc${M}x0123, vacc${M}x0123);
      $else:
        $for M in range(MR):
          __m128i voutb${M}x0123 = ${_MM_CVTXEPI32_EPI8}(vacc${M}x0123);

      $for M in range(MR):
        voutb${M}x0123 = ${_MM_MAX_EPX8}(voutb${M}x0123, voutput_min);

      if (nc >= 4) {
        $for M in range(MR):
          _mm_storeu_ps(c${M}, voutb${M}x0123);
          c${M} = (${OUT_T}*) ((uintptr_t) c${M} + cn_stride);
          a${M} = (const ${XINT8_T}*) ((uintptr_t) a${M} - kc);

        nc -= 4;
      } else {
        $if SSE >= 3:
          if (nc & 2) {
            $for M in range(MR):
              unaligned_store_u16(c${M}, (uint16_t) _mm_extract_epi16(voutb${M}x0123, 0));
              c${M} += 2;
            $for M in range(MR):
              voutb${M}x0123 = _mm_srli_epi32(voutb${M}x0123, 16);
          }
          if (nc & 1) {
            $for M in range(MR):
              *c${M} = (${XINT8_T}) _mm_extract_epi8(voutb${M}x0123, 0);
          }
        $else:
          // Prepare mask for valid 8-bit elements (depends on nc).
          const __mmask16 vmask = _cvtu32_mask16((UINT32_C(1) << nc) - UINT32_C(1));
          $for M in range(MR):
            _mm_mask_storeu_epi8(c${M}, vmask, voutb${M}x0123);
        nc = 0;
      }
  } while (nc != 0);
}
