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

#include <wasm_simd128.h>

#include "xnnpack/gemm.h"
#include "xnnpack/math.h"


$DATATYPE_SPEC = {"QC8": "qs8_qc8w", "QD8": "qd8_f32_qc8w", "QC4": "qd8_f32_qc4w", "QS8": "qs8", "QU8": "qu8"}[DATATYPE]
$LOAD_SUFFIX = {"LD128": "_ld128", "LD64": "_ld64", "EXTENDED": ""}[VARIANT]
$GEMM_SUFFIX = "_xw" if VARIANT == "EXTENDED" else ""
$REQUANTIZATION_SPEC = "_" + REQUANTIZATION.lower() if REQUANTIZATION else ""
$PARAMS_STRUCT = REQUANTIZATION.lower() + "_scalar"
$PARAMS_TYPE = {"QC8": "union xnn_qs8_qc8w_conv_minmax_params", "QD8": "union xnn_f32_minmax_params", "QC4": "struct xnn_f32_qc4w_minmax_params", "QS8": "union xnn_qs8_conv_minmax_params", "QU8": "union xnn_qu8_conv_minmax_params"}[DATATYPE]
$XINT8_T = "uint8_t" if DATATYPE == "QU8" else "int8_t"
$OUT_T = "float" if DATATYPE in ["QD8", "QC4"] else XINT8_T
$WASM_X16X8_LOAD8X8 = "wasm_u16x8_load8x8" if DATATYPE == "QU8" else "wasm_i16x8_load8x8"
$WASM_X8X16_NARROW_I16X8 = "wasm_u8x16_narrow_i16x8" if DATATYPE == "QU8" else "wasm_i8x16_narrow_i16x8"
$WASM_X8X16_MIN = "wasm_u8x16_min" if DATATYPE == "QU8" else "wasm_i8x16_min"
void xnn_${DATATYPE_SPEC}_gemm${GEMM_SUFFIX}_minmax${REQUANTIZATION_SPEC}_ukernel_${MR}x4c8__wasmsimd_dot16x2${LOAD_SUFFIX}(
    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", "QC4"]:
      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(${XINT8_T}));
  const ${XINT8_T}* a0 = a;
  ${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);
    ${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", "QC4"]:
    const v128_t vmin = wasm_v128_load32_splat(&params->scalar.min);
    const v128_t vmax = wasm_v128_load32_splat(&params->scalar.max);
    XNN_FORCE_REALIZATION(vmin);
    XNN_FORCE_REALIZATION(vmax);
  $else:
    $if DATATYPE != "QC8":
      const v128_t vscale = wasm_v128_load32_splat(&params->${PARAMS_STRUCT}.scale);
      XNN_FORCE_REALIZATION(vscale);

    const v128_t vmagic_bias = wasm_f32x4_const_splat(12582912.0f);
    const int32_t output_min_less_zero_point = (int32_t) params->${PARAMS_STRUCT}.output_min - (int32_t) params->${PARAMS_STRUCT}.output_zero_point;
    const v128_t vmagic_min = wasm_i32x4_splat((int32_t) float_as_uint32(12582912.0f + output_min_less_zero_point));
    const v128_t vmagic_bias_less_output_zero_point = wasm_i32x4_splat(INT32_C(0x4B400000) - (int32_t) params->${PARAMS_STRUCT}.output_zero_point);
    const v128_t voutput_max = wasm_i8x16_splat(params->${PARAMS_STRUCT}.output_max);
    XNN_FORCE_REALIZATION(vmagic_bias);
    XNN_FORCE_REALIZATION(vmagic_min);
    XNN_FORCE_REALIZATION(vmagic_bias_less_output_zero_point);
    XNN_FORCE_REALIZATION(voutput_max);

  $if DATATYPE == "QU8":
    const v128_t vb_zero_point = wasm_i16x8_splat(params->${PARAMS_STRUCT}.kernel_zero_point);
    XNN_FORCE_REALIZATION(vb_zero_point);
  $if DATATYPE == "QC4":
    const v128_t vmask = wasm_i8x16_const_splat(0xF0);
  do {
    $if DATATYPE in ["QD8", "QC4"]:
      const v128_t vksum0123 = wasm_v128_load(w);
      $for M in range(MR):
        const v128_t vinput_zero_point${M} = wasm_v128_load32_splat(&quantization_params[${M}].zero_point);
      $for M in range(MR):
        const v128_t vinit${M}x0123 = wasm_i32x4_mul(vksum0123, vinput_zero_point${M});

      const v128_t vzero = wasm_i32x4_const_splat(0);
      $for M in range(MR):
        v128_t vacc${M}x0 = wasm_v32x4_shuffle(vinit${M}x0123, vzero, 0, 5, 6, 7);
        v128_t vacc${M}x1 = wasm_v32x4_shuffle(vinit${M}x0123, vzero, 4, 1, 6, 7);
        v128_t vacc${M}x2 = wasm_v32x4_shuffle(vinit${M}x0123, vzero, 4, 5, 2, 7);
        v128_t vacc${M}x3 = wasm_v32x4_shuffle(vinit${M}x0123, vzero, 4, 5, 6, 3);
    $else:
      v128_t vacc0x0 = wasm_v128_load32_zero(w);
      $for N in range(1, 4):
        v128_t vacc0x${N} = wasm_v128_load32_zero((const int32_t*) w + ${N});
      $for M in range(1, MR):
        $for N in range(4):
          v128_t vacc${M}x${N} = vacc0x${N};
    w = (const int32_t*) w + 4;

    size_t k = kc;
    $if DATATYPE == "QC4":
      while (k >= 16 * sizeof(${XINT8_T})) {
        $for M in range(MR):
          v128_t vxa${M};
        $for N in range(0, 8):
          $if N % 4 == 0:
            $for M in range(MR):
              vxa${M} = ${WASM_X16X8_LOAD8X8}(a${M});
              a${M} += 8;
          $if N == 0:
            const v128_t vb${N} = wasm_v128_load(w);
            const v128_t vb${N+2} = wasm_v128_load((const ${XINT8_T}*) w + 16);
            const v128_t vbm${N} = wasm_i8x16_shl(vb${N}, 4);
            const v128_t vbm${N+2} = wasm_i8x16_shl(vb${N+2}, 4);
            const v128_t vxb${N} = wasm_i16x8_extend_low_i8x16(vbm${N});
            const v128_t vxb${N+1} = wasm_i16x8_extend_high_i8x16(vbm${N});
            const v128_t vxb${N+2} = wasm_i16x8_extend_low_i8x16(vbm${N+2});
            const v128_t vxb${N+3} = wasm_i16x8_extend_high_i8x16(vbm${N+2});
          $if N == 4:
            const v128_t vbm${N} = wasm_v128_and(vb${N-4}, vmask);
            const v128_t vbm${N+2} = wasm_v128_and(vb${N-2}, vmask);
            const v128_t vxb${N} = wasm_i16x8_extend_low_i8x16(vbm${N});
            const v128_t vxb${N+1} = wasm_i16x8_extend_high_i8x16(vbm${N});
            const v128_t vxb${N+2} = wasm_i16x8_extend_low_i8x16(vbm${N+2});
            const v128_t vxb${N+3} = wasm_i16x8_extend_high_i8x16(vbm${N+2});
          $for M in range(MR):
            vacc${M}x${N % 4} = wasm_i32x4_add(vacc${M}x${N % 4}, wasm_i32x4_dot_i16x8(vxa${M}, vxb${N}));
        w = (const ${XINT8_T}*) w + 32;
        k -= 16 * sizeof(${XINT8_T});
      }

    while (k >= 8 * sizeof(${XINT8_T})) {
      $for M in range(MR):
        const v128_t vxa${M} = ${WASM_X16X8_LOAD8X8}(a${M});
        a${M} += 8;

      $if VARIANT == "LD128":
        $for N in range(0, 4, 2):
          $if N == 0:
            const v128_t vb${N}${N+1} = wasm_v128_load(w);
          $else:
            const v128_t vb${N}${N+1} = wasm_v128_load((const ${XINT8_T}*) w + ${N * 8});
          $if DATATYPE == "QU8":
            const v128_t vxb${N} = wasm_i16x8_sub(wasm_u16x8_extend_low_u8x16(vb${N}${N+1}), vb_zero_point);
            const v128_t vxb${N+1} = wasm_i16x8_sub(wasm_u16x8_extend_high_u8x16(vb${N}${N+1}), vb_zero_point);
          $else:
            const v128_t vxb${N} = wasm_i16x8_extend_low_i8x16(vb${N}${N+1});
            const v128_t vxb${N+1} = wasm_i16x8_extend_high_i8x16(vb${N}${N+1});

          $for M in range(MR):
            vacc${M}x${N} = wasm_i32x4_add(vacc${M}x${N}, wasm_i32x4_dot_i16x8(vxa${M}, vxb${N}));
            vacc${M}x${N+1} = wasm_i32x4_add(vacc${M}x${N+1}, wasm_i32x4_dot_i16x8(vxa${M}, vxb${N+1}));
      $else:
        $for N in range(4):
          $if VARIANT == "LD64":
            $if DATATYPE == "QC4":
              $if N == 0:
                const v128_t vb${N} = wasm_v128_load(w);
                const v128_t vb${N+2} = wasm_v128_load((const ${XINT8_T}*) w + 16);
                const v128_t vbm${N} = wasm_i8x16_shl(vb${N}, 4);
                const v128_t vbm${N+2} = wasm_i8x16_shl(vb${N+2}, 4);
                const v128_t vxb${N} = wasm_i16x8_extend_low_i8x16(vbm${N});
                const v128_t vxb${N+1} = wasm_i16x8_extend_high_i8x16(vbm${N});
                const v128_t vxb${N+2} = wasm_i16x8_extend_low_i8x16(vbm${N+2});
                const v128_t vxb${N+3} = wasm_i16x8_extend_high_i8x16(vbm${N+2});
            $elif DATATYPE == "QU8":
              $if N == 0:
                const v128_t vxb${N} = wasm_i16x8_sub(wasm_u16x8_load8x8(w), vb_zero_point);
              $else:
                const v128_t vxb${N} = wasm_i16x8_sub(wasm_u16x8_load8x8((const int8_t*) w + ${N * 8}), vb_zero_point);
            $else:
              $if N == 0:
                const v128_t vxb${N} = wasm_i16x8_load8x8(w);
              $else:
                const v128_t vxb${N} = wasm_i16x8_load8x8((const int8_t*) w + ${N * 8});
          $elif VARIANT == "EXTENDED":
            $if N == 0:
              const v128_t vxb${N} = wasm_v128_load(w);
            $else:
              const v128_t vxb${N} = wasm_v128_load((const int16_t*) w + ${N * 8});

          $for M in range(MR):
            vacc${M}x${N} = wasm_i32x4_add(vacc${M}x${N}, wasm_i32x4_dot_i16x8(vxa${M}, vxb${N}));

      $if VARIANT == "EXTENDED":
        w = (const int16_t*) w + 32;
      $elif DATATYPE == "QC4":
        w = (const ${XINT8_T}*) w + 32;  // only low nibble used
      $else:
        w = (const ${XINT8_T}*) w + 32;
      k -= 8 * sizeof(${XINT8_T});
    };

    $for M in range(MR):
      const v128_t vacc${M}x02 = wasm_i32x4_add(wasm_v32x4_shuffle(vacc${M}x0, vacc${M}x2, 0, 4, 1, 5), wasm_v32x4_shuffle(vacc${M}x0, vacc${M}x2, 2, 6, 3, 7));
      const v128_t vacc${M}x13 = wasm_i32x4_add(wasm_v32x4_shuffle(vacc${M}x1, vacc${M}x3, 0, 4, 1, 5), wasm_v32x4_shuffle(vacc${M}x1, vacc${M}x3, 2, 6, 3, 7));

    $for M in range(MR):
      v128_t vacc${M}x0123 = wasm_i32x4_add(wasm_v32x4_shuffle(vacc${M}x02, vacc${M}x13, 0, 4, 1, 5), wasm_v32x4_shuffle(vacc${M}x02, vacc${M}x13, 2, 6, 3, 7));

    $if DATATYPE == "QC4":
      $for M in range(MR):
        vacc${M}x0123 = wasm_i32x4_shr(vacc${M}x0123, 4);
    $for M in range(MR):
      vacc${M}x0123 = wasm_f32x4_convert_i32x4(vacc${M}x0123);

    $if DATATYPE in ["QD8", "QC4"]:
      $for M in range(MR):
        const v128_t vinput_scale${M} = wasm_v128_load32_splat(&quantization_params[${M}].inv_scale);

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

      const v128_t vfilter_output_scale0123 = wasm_v128_load(w);
      $for M in range(MR):
        vacc${M}x0123 = wasm_f32x4_mul(vacc${M}x0123, vfilter_output_scale0123);
      w = (const float*) w + 4;

      const v128_t vbias0123 = wasm_v128_load(w);
      $for M in range(MR):
        vacc${M}x0123 = wasm_f32x4_add(vacc${M}x0123, vbias0123);
      w = (const float*) w + 4;

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

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

      if XNN_LIKELY(nc >= 4) {
        $for M in range(MR):
          wasm_v128_store(c${M}, vacc${M}x0123);

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

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

        nc -= 4;
      } else {
        if (nc & 2) {
          $for M in range(MR):
            wasm_v128_store64_lane(c${M}, vacc${M}x0123, 0);
            vacc${M}x0123 = wasm_v64x2_shuffle(vacc${M}x0123, vacc${M}x0123, 1, 1);
            c${M} += 2;
        }
        if (nc & 1) {
          $for M in range(MR):
            wasm_v128_store32_lane(c${M}, vacc${M}x0123, 0);
        }
        nc = 0;
      }
    $else:
      $if DATATYPE == "QC8":
        const v128_t vscale0123 = wasm_v128_load(w);
        w = (const float*) w + 4;
        $for M in range(MR):
          vacc${M}x0123 = wasm_f32x4_mul(vacc${M}x0123, vscale0123);
      $else:
        $for M in range(MR):
          vacc${M}x0123 = wasm_f32x4_mul(vacc${M}x0123, vscale);

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

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

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

      $for M in range(0, MR, 2):
        v128_t vacc${M}${min(M+1, MR-1)}x0123 = wasm_i16x8_narrow_i32x4(vacc${M}x0123, vacc${min(M+1, MR-1)}x0123);

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

      vacc = ${WASM_X8X16_MIN}(vacc, voutput_max);

      if XNN_LIKELY(nc >= 4) {
        $for M in range(MR):
          wasm_v128_store32_lane(c${M}, vacc, ${M});

        $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):
            wasm_v128_store16_lane(c${M}, vacc, ${2 * M});
            c${M} += 2;

          vacc = wasm_u32x4_shr(vacc, 16);
        }
        if (nc & 1) {
          $for M in range(MR):
            wasm_v128_store8_lane(c${M}, vacc, ${4 * M});
        }

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