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

$if XOP:
  #if defined(__GNUC__) || defined(__clang__)
    #include <x86intrin.h>
  #else
    #include <immintrin.h>
    #include <ammintrin.h>
  #endif
$else:
  $SSE_HEADER = {2: "emmintrin.h", 4: "smmintrin.h"}[SSE]
  #include <${SSE_HEADER}>

#include <xnnpack/gemm.h>
#include <xnnpack/math.h>
#include <xnnpack/unaligned.h>



$LOAD_SUFFIX = {"LD128": "_ld128", "LD64": "_ld64", "EXTENDED": ""}[VARIANT]
$GEMM_SUFFIX = "_xw" if VARIANT == "EXTENDED" else ""
$PARAMS_STRUCT = REQUANTIZATION.lower() + "_" + ("sse4" if SSE == 4 and DATATYPE != "QU8" else "sse2")
$PARAMS_UNION = "xnn_%s_conv_minmax_params" % DATATYPE.lower()
$XINT8_T = "uint8_t" if DATATYPE == "QU8" else "int8_t"
$ISA = "xop" if XOP else "avx" if AVX else {2: "sse2", 4: "sse41"}[SSE]
void xnn_${DATATYPE.lower()}_gemm${GEMM_SUFFIX}_minmax_fp32_ukernel_${MR}x4c2__${ISA}${LOAD_SUFFIX}(
    size_t mr,
    size_t nc,
    size_t kc,
    const ${XINT8_T}* restrict a,
    size_t a_stride,
    const void* restrict w,
    ${XINT8_T}* restrict c,
    size_t cm_stride,
    size_t cn_stride,
    const union ${PARAMS_UNION} 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, 2 * sizeof(${XINT8_T}));
  const ${XINT8_T}* a0 = a;
  ${XINT8_T}* c0 = c;
  $for M in range(1, MR):
    const ${XINT8_T}* a${M} = (const ${XINT8_T}*) ((uintptr_t) a${M-1} + a_stride);
    ${XINT8_T}* c${M} = (${XINT8_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};
      }

  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 k = kc;
    $if DATATYPE == "QU8":
      const __m128i vb_zero_point = _mm_load_si128((const __m128i*) params->${PARAMS_STRUCT}.kernel_zero_point);
      $if SSE < 4 or VARIANT == "LD128":
        const __m128i vzero = _mm_setzero_si128();
    while (k >= 8 * sizeof(${XINT8_T})) {
      $for M in range(MR):
        const __m128i va${M} = _mm_loadl_epi64((const __m128i*) a${M});
        $if DATATYPE == "QU8":
          $if SSE == 4:
            const __m128i vxa${M} = _mm_cvtepu8_epi16(va${M});
          $else:
            const __m128i vxa${M} = _mm_unpacklo_epi8(va${M}, vzero);
        $else:
          $if SSE == 4:
            const __m128i vxa${M} = _mm_cvtepi8_epi16(va${M});
          $else:
            const __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):
            $if XOP:
              vacc${M}x0123 = _mm_maddd_epi16(
                _mm_shuffle_epi32(vxa${M}, _MM_SHUFFLE(${K}, ${K}, ${K}, ${K})), vxb${K}, vacc${M}x0123);
            $else:
              vacc${M}x0123 = _mm_add_epi32(vacc${M}x0123,
                _mm_madd_epi16(_mm_shuffle_epi32(vxa${M}, _MM_SHUFFLE(${K}, ${K}, ${K}, ${K})), vxb${K}));

          $for M in range(MR):
            $if XOP:
              vacc${M}x0123 = _mm_maddd_epi16(
                _mm_shuffle_epi32(vxa${M}, _MM_SHUFFLE(${K+1}, ${K+1}, ${K+1}, ${K+1})), vxb${K+1}, vacc${M}x0123);
            $else:
              vacc${M}x0123 = _mm_add_epi32(vacc${M}x0123,
                _mm_madd_epi16(_mm_shuffle_epi32(vxa${M}, _MM_SHUFFLE(${K+1}, ${K+1}, ${K+1}, ${K+1})), vxb${K+1}));
      $else:
        $for K in range(4):
          $if VARIANT == "LD64":
            $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);
          $elif VARIANT == "EXTENDED":
            $if K == 0:
              const __m128i vxb${K} = _mm_load_si128((const __m128i*) w);
            $else:
              const __m128i vxb${K} = _mm_load_si128((const __m128i*) ((const int16_t*) w + ${K * 8}));

          $for M in range(MR):
            $if XOP:
              vacc${M}x0123 = _mm_maddd_epi16(
                _mm_shuffle_epi32(vxa${M}, _MM_SHUFFLE(${K}, ${K}, ${K}, ${K})), vxb${K}, vacc${M}x0123);
            $else:
              vacc${M}x0123 = _mm_add_epi32(vacc${M}x0123,
                _mm_madd_epi16(_mm_shuffle_epi32(vxa${M}, _MM_SHUFFLE(${K}, ${K}, ${K}, ${K})), vxb${K}));

      $if VARIANT == "EXTENDED":
        w = (const void*) ((const int16_t*) w + 32);
      $else:
        w = (const void*) ((const ${XINT8_T}*) w + 32);
      k -= 8 * sizeof(${XINT8_T});
    }
    if (k != 0) {
      $for M in range(MR):
        const __m128i va${M} = _mm_loadl_epi64((const __m128i*) a${M});
        $if DATATYPE == "QU8":
          $if SSE == 4:
            const __m128i vxa${M} = _mm_cvtepu8_epi16(va${M});
          $else:
            const __m128i vxa${M} = _mm_unpacklo_epi8(va${M}, vzero);
        $else:
          $if SSE == 4:
            const __m128i vxa${M} = _mm_cvtepi8_epi16(va${M});
          $else:
            const __m128i vxa${M} = _mm_srai_epi16(_mm_unpacklo_epi8(va${M}, va${M}), 8);
        a${M} = (const ${XINT8_T}*) ((uintptr_t) a${M} + k);

      $if VARIANT == "EXTENDED":
        const __m128i vxb0 = _mm_load_si128((const __m128i*) w);
        w = (const void*) ((const int16_t*) w + 8);
      $else:
        const __m128i vb0 = _mm_loadl_epi64((const __m128i*) w);
        $if DATATYPE == "QU8":
          $if SSE == 4:
            const __m128i vxb0 = _mm_sub_epi16(_mm_cvtepu8_epi16(vb0), vb_zero_point);
          $else:
            const __m128i vxb0 = _mm_sub_epi16(_mm_unpacklo_epi8(vb0, vzero), vb_zero_point);
        $else:
          $if SSE == 4:
            const __m128i vxb0 = _mm_cvtepi8_epi16(vb0);
          $else:
            const __m128i vxb0 = _mm_srai_epi16(_mm_unpacklo_epi8(vb0, vb0), 8);
        w = (const void*) ((const ${XINT8_T}*) w + 8);

      $for M in range(MR):
        $if XOP:
          vacc${M}x0123 = _mm_maddd_epi16(
            _mm_shuffle_epi32(vxa${M}, _MM_SHUFFLE(0, 0, 0, 0)), vxb0, vacc${M}x0123);
        $else:
          vacc${M}x0123 = _mm_add_epi32(vacc${M}x0123,
            _mm_madd_epi16(_mm_shuffle_epi32(vxa${M}, _MM_SHUFFLE(0, 0, 0, 0)), vxb0));

      if (k > 2 * sizeof(${XINT8_T})) {
        $if VARIANT == "EXTENDED":
          const __m128i vxb1 = _mm_load_si128((const __m128i*) w);
          w = (const void*) ((const int16_t*) w + 8);
        $else:
          const __m128i vb1 = _mm_loadl_epi64((const __m128i*) w);
          $if DATATYPE == "QU8":
            $if SSE == 4:
              const __m128i vxb1 = _mm_sub_epi16(_mm_cvtepu8_epi16(vb1), vb_zero_point);
            $else:
              const __m128i vxb1 = _mm_sub_epi16(_mm_unpacklo_epi8(vb1, vzero), vb_zero_point);
          $else:
            $if SSE == 4:
              const __m128i vxb1 = _mm_cvtepi8_epi16(vb1);
            $else:
              const __m128i vxb1 = _mm_srai_epi16(_mm_unpacklo_epi8(vb1, vb1), 8);
          w = (const void*) ((const ${XINT8_T}*) w + 8);

        $for M in range(MR):
          $if XOP:
            vacc${M}x0123 = _mm_maddd_epi16(
              _mm_shuffle_epi32(vxa${M}, _MM_SHUFFLE(1, 1, 1, 1)), vxb1, vacc${M}x0123);
          $else:
            vacc${M}x0123 = _mm_add_epi32(vacc${M}x0123,
              _mm_madd_epi16(_mm_shuffle_epi32(vxa${M}, _MM_SHUFFLE(1, 1, 1, 1)), vxb1));

        if (k > 4 * sizeof(${XINT8_T})) {
          $if VARIANT == "EXTENDED":
            const __m128i vxb2 = _mm_load_si128((const __m128i*) w);
            w = (const void*) ((const int16_t*) w + 8);
          $else:
            const __m128i vb2 = _mm_loadl_epi64((const __m128i*) w);
            $if DATATYPE == "QU8":
              $if SSE == 4:
                const __m128i vxb2 = _mm_sub_epi16(_mm_cvtepu8_epi16(vb2), vb_zero_point);
              $else:
                const __m128i vxb2 = _mm_sub_epi16(_mm_unpacklo_epi8(vb2, vzero), vb_zero_point);
            $else:
              $if SSE == 4:
                const __m128i vxb2 = _mm_cvtepi8_epi16(vb2);
              $else:
                const __m128i vxb2 = _mm_srai_epi16(_mm_unpacklo_epi8(vb2, vb2), 8);
            w = (const void*) ((const ${XINT8_T}*) w + 8);

          $for M in range(MR):
            $if XOP:
              vacc${M}x0123 = _mm_maddd_epi16(
                _mm_shuffle_epi32(vxa${M}, _MM_SHUFFLE(2, 2, 2, 2)), vxb2, vacc${M}x0123);
            $else:
              vacc${M}x0123 = _mm_add_epi32(vacc${M}x0123,
                _mm_madd_epi16(_mm_shuffle_epi32(vxa${M}, _MM_SHUFFLE(2, 2, 2, 2)), vxb2));
        }
      }
    }

    $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 void*) ((const float*) w + 4);
      $for M in range(MR):
        vscaled${M}x0123 = _mm_mul_ps(vscaled${M}x0123, vscale0123);
    $else:
      const __m128 vscale = _mm_load_ps(params->${PARAMS_STRUCT}.scale);
      $for M in range(MR):
        vscaled${M}x0123 = _mm_mul_ps(vscaled${M}x0123, vscale);

    const __m128 voutput_max_less_zero_point = _mm_load_ps(params->${PARAMS_STRUCT}.output_max_less_zero_point);
    $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);

    const __m128i voutput_zero_point = _mm_load_si128((const __m128i*) params->${PARAMS_STRUCT}.output_zero_point);
    $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, _mm_load_si128((const __m128i*) params->${PARAMS_STRUCT}.output_min));
    $else:
      $if SSE < 4:
        const __m128i voutput_min = _mm_load_si128((const __m128i*) params->${PARAMS_STRUCT}.output_min);
        $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, _mm_load_si128((const __m128i*) params->${PARAMS_STRUCT}.output_min));

    if (nc >= 4) {
      unaligned_store_u32(c0, (uint32_t) _mm_cvtsi128_si32(vout));
      $for M in range(1, MR):
        $if SSE == 4:
          unaligned_store_u32(c${M}, (uint32_t) _mm_extract_epi32(vout, ${M}));
        $else:
          vout = _mm_shuffle_epi32(vout, _MM_SHUFFLE(0, 3, 2, 1));
          unaligned_store_u32(c${M}, (uint32_t) _mm_cvtsi128_si32(vout));

      $for M in range(MR):
        c${M} = (${XINT8_T}*) ((uintptr_t) c${M} + cn_stride);

      $for M in range(MR):
        a${M} = (const ${XINT8_T}*) ((uintptr_t) a${M} - kc);

      nc -= 4;
    } else {
      if (nc & 2) {
        $for M in 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 range(MR):
            *c${M} = (${XINT8_T}) _mm_extract_epi8(vout, ${M * 4});
        $else:
          *c0 = (${XINT8_T}) _mm_cvtsi128_si32(vout);
          $for M in range(1, MR):
            *c${M} = (${XINT8_T}) _mm_extract_epi16(vout, ${M * 2});
      }

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