// Copyright 2023 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"]
$assert DATATYPE == "QD8" or REQUANTIZATION == "FP32"
$assert DATATYPE != "QD8" or not REQUANTIZATION
$assert MR <= 4
$assert NR == 4 or NR == 8
$assert (SDOT == 0 and (DATATYPE in ["QC8", "QD8"])) or SDOT == 1
#include <assert.h>

#include <wasm_simd128.h>

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

$ABC = "012345678"
$DATATYPE_SPEC = {"QC8": "qs8_qc8w", "QD8": "qd8_f32_qc8w", "QS8": "qs8"}[DATATYPE]
$REQUANTIZATION_SPEC = "_" + REQUANTIZATION.lower() if REQUANTIZATION else ""
$PARAMS_TYPE = {"QC8": "union xnn_qs8_qc8w_conv_minmax_params", "QD8": "union xnn_f32_minmax_params", "QS8": "union xnn_qs8_conv_minmax_params"}[DATATYPE]
$OUT_T = "float" if DATATYPE == "QD8" else "int8_t"
void xnn_${DATATYPE_SPEC}_gemm_minmax${REQUANTIZATION_SPEC}_ukernel_${MR}x${NR}c16__wasm${"sdot" if SDOT else "usdot"}(
    size_t mr,
    size_t nc,
    size_t kc,
    const int8_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 == "QD8":
      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(int8_t) == 0);
  assert(a != NULL);
  assert(w != NULL);
  assert(c != NULL);

  kc = round_up_po2(kc, 16 * sizeof(int8_t));
  const int8_t* a0 = a;
  ${OUT_T}* c0 = c;
  $for M in range(1, MR):
    const int8_t* a${M} = (const int8_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 == "QD8":
    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->fp32_scalar.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->fp32_scalar.output_min - (int32_t) params->fp32_scalar.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->fp32_scalar.output_zero_point);
    const v128_t voutput_max = wasm_i8x16_splat(params->fp32_scalar.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 not SDOT:
    const v128_t vsign_mask = wasm_u8x16_const_splat(UINT8_C(0x80));
  do {
    $if DATATYPE == "QD8":
      v128_t vksum0 = wasm_v128_load32_zero(w);
      $for N in range(1, NR):
        v128_t vksum${N} = wasm_v128_load32_zero((const int32_t*) w + ${N});
      $for M in range(MR):
        $if SDOT:
          const v128_t vinput_zero_point${M} = wasm_v128_load32_splat(&quantization_params[${M}].zero_point);
        $else:
          const v128_t vinput_zero_point${M} = wasm_i32x4_splat((int32_t) quantization_params[${M}].zero_point + 128);
      $for M in range(MR):
        $for N in range(NR):
          v128_t vacc${M}x${N} = wasm_i32x4_mul(vksum${N}, vinput_zero_point${M});
    $else:
      v128_t vacc0x0 = wasm_v128_load32_zero(w);
      $for N in range(1, NR):
        v128_t vacc0x${N} = wasm_v128_load32_zero((const int32_t*) w + ${N});
      $for M in range(1, MR):
        $for N in range(NR):
          v128_t vacc${M}x${N} = vacc0x${N};
    w = (const int32_t*) w + ${NR};

    size_t k = kc;
    do {
      $for M in range(MR):
        $if SDOT:
          const v128_t va${M} = wasm_v128_load(a${M});
        $else:
          const v128_t va${M} = wasm_v128_xor(wasm_v128_load(a${M}), vsign_mask);
        a${M} += 16;

      $for N in range(NR):
        $if N == 0:
          const v128_t vb${N} = wasm_v128_load(w);
        $else:
          const v128_t vb${N} = wasm_v128_load((const int8_t*) w + ${N * 16});

        $for M in range(MR):
          vacc${M}x${N} = wasm_i32x4_relaxed_dot_i8x16_i7x16_add(vb${N}, va${M}, vacc${M}x${N});

      w = (const int8_t*) w + ${NR * 16};
      k -= 16 * sizeof(int8_t);
    } while (k != 0);

    $for M in range(MR):
      $for N in range(0, NR, 4):
        const v128_t vacc${M}x${N}${N+2} = wasm_i32x4_add(wasm_v32x4_shuffle(vacc${M}x${N}, vacc${M}x${N+2}, 0, 4, 1, 5), wasm_v32x4_shuffle(vacc${M}x${N}, vacc${M}x${N+2}, 2, 6, 3, 7));
        const v128_t vacc${M}x${N+1}${N+3} = wasm_i32x4_add(wasm_v32x4_shuffle(vacc${M}x${N+1}, vacc${M}x${N+3}, 0, 4, 1, 5), wasm_v32x4_shuffle(vacc${M}x${N+1}, vacc${M}x${N+3}, 2, 6, 3, 7));

    $for M in range(MR):
      $for N in range(0, NR, 4):
        v128_t vacc${M}x${ABC[N:N+4]} = wasm_i32x4_add(wasm_v32x4_shuffle(vacc${M}x${N}${N+2}, vacc${M}x${N+1}${N+3}, 0, 4, 1, 5), wasm_v32x4_shuffle(vacc${M}x${N}${N+2}, vacc${M}x${N+1}${N+3}, 2, 6, 3, 7));

    $for M in range(MR):
      $for N in range(0, NR, 4):
        vacc${M}x${ABC[N:N+4]} = wasm_f32x4_convert_i32x4(vacc${M}x${ABC[N:N+4]});

    $if DATATYPE == "QD8":
      $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):
        $for N in range(0, NR, 4):
          vacc${M}x${ABC[N:N+4]} = wasm_f32x4_mul(vacc${M}x${ABC[N:N+4]}, vinput_scale${M});

      $for N in range(0, NR, 4):
        const v128_t vfilter_output_scale${ABC[N:N+4]} = wasm_v128_load(w);
        w = (const float*) w + 4;
      $for M in range(MR):
        $for N in range(0, NR, 4):
          vacc${M}x${ABC[N:N+4]} = wasm_f32x4_mul(vacc${M}x${ABC[N:N+4]}, vfilter_output_scale${ABC[N:N+4]});

      $for N in range(0, NR, 4):
        const v128_t vbias${ABC[N:N+4]} = wasm_v128_load(w);
        w = (const float*) w + 4;
      $for M in range(MR):
        $for N in range(0, NR, 4):
          vacc${M}x${ABC[N:N+4]} = wasm_f32x4_add(vacc${M}x${ABC[N:N+4]}, vbias${ABC[N:N+4]});

      $for M in range(MR):
        $for N in range(0, NR, 4):
          vacc${M}x${ABC[N:N+4]} = wasm_f32x4_pmax(vacc${M}x${ABC[N:N+4]}, vmin);

      $for M in range(MR):
        $for N in range(0, NR, 4):
          vacc${M}x${ABC[N:N+4]} = wasm_f32x4_pmin(vacc${M}x${ABC[N:N+4]}, vmax);

      if XNN_LIKELY(nc >= ${NR}) {
        $for M in range(MR):
          wasm_v128_store(c${M}, vacc${M}x${ABC[0:4]});
          $for N in range(4, NR, 4):
            wasm_v128_store(c${M} + ${N}, vacc${M}x${ABC[N:N+4]});

        $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 -= ${NR};
      } else {
        $if NR == 8:
          if (nc & 4) {
            $for M in range(MR):
              wasm_v128_store(c${M}, vacc${M}x0123);
              vacc${M}x0123 = vacc${M}x4567;
              c${M} += 4;
          }
        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":
        $for N in range(0, NR, 4):
            const v128_t vscale${ABC[N:N+4]} = wasm_v128_load(w);
            w = (const float*) w + 4;
        $for M in range(MR):
          $for N in range(0, NR, 4):
            vacc${M}x${ABC[N:N+4]} = wasm_f32x4_mul(vacc${M}x${ABC[N:N+4]}, vscale${ABC[N:N+4]});
      $else:
        $for M in range(MR):
          vacc${M}x0123 = wasm_f32x4_mul(vacc${M}x0123, vscale);

      $for M in range(MR):
        $for N in range(0, NR, 4):
          vacc${M}x${ABC[N:N+4]} = wasm_f32x4_add(vacc${M}x${ABC[N:N+4]}, vmagic_bias);

      $for M in range(MR):
        $for N in range(0, NR, 4):
          vacc${M}x${ABC[N:N+4]} = wasm_i32x4_max(vacc${M}x${ABC[N:N+4]}, vmagic_min);

      $for M in range(MR):
        $for N in range(0, NR, 4):
          vacc${M}x${ABC[N:N+4]} = wasm_i32x4_sub(vacc${M}x${ABC[N:N+4]}, vmagic_bias_less_output_zero_point);

      $if NR == 4:
        $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);
      $else:
        $for M in range(MR):
          v128_t vacc${M}x01234567 = wasm_i16x8_narrow_i32x4(vacc${M}x0123, vacc${M}x4567);

      $if NR == 4:
        $if MR > 2:
          v128_t vacc = wasm_i8x16_narrow_i16x8(vacc0${min(1, MR-1)}x0123, vacc${min(2, MR-1)}${min(3, MR-1)}x0123);
        $else:
          v128_t vacc = wasm_i8x16_narrow_i16x8(vacc0${min(1, MR-1)}x0123, vacc0${min(1, MR-1)}x0123);
      $else:
        $if MR > 2:
          v128_t vacc0x01234567_1x01234567 = wasm_i8x16_narrow_i16x8(vacc0x01234567, vacc1x01234567);
          v128_t vacc2x01234567_${min(3, MR-1)}x01234567 = wasm_i8x16_narrow_i16x8(vacc2x01234567, vacc${min(3, MR-1)}x01234567);
        $else:
          v128_t vacc0x01234567_${min(1, MR-1)}x01234567 = wasm_i8x16_narrow_i16x8(vacc0x01234567, vacc${min(1, MR-1)}x01234567);

      $if NR == 4:
        vacc = wasm_i8x16_min(vacc, voutput_max);
      $else:
        $if MR > 2:
          vacc0x01234567_1x01234567 = wasm_i8x16_min(vacc0x01234567_1x01234567, voutput_max);
          vacc2x01234567_${min(3, MR-1)}x01234567 = wasm_i8x16_min(vacc2x01234567_${min(3, MR-1)}x01234567, voutput_max);
        $else:
          vacc0x01234567_${min(1, MR-1)}x01234567 = wasm_i8x16_min(vacc0x01234567_${min(1, MR-1)}x01234567, voutput_max);

      if XNN_LIKELY(nc >= ${NR}) {
        $if NR == 4:
          $for M in range(MR):
            wasm_v128_store32_lane(c${M}, vacc, ${M});
        $else:
          $for M in range(MR):
            wasm_v128_store64_lane(c${M}, vacc${(M>>1)*2}x01234567_${min(MR-1, (M>>1)*2+1)}x01234567, ${M%2});

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

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

        nc -= ${NR};
      } else {
        $if NR == 8:
          if (nc & 4) {
            $for M in range(MR):
              wasm_v128_store32_lane(c${M}, vacc${(M>>1)*2}x01234567_${min(MR-1, (M>>1)*2+1)}x01234567, ${M%2*2});
              c${M} += 4;

            $for M in range(0, MR, 2):
              vacc${(M>>1)*2}x01234567_${min(MR-1, (M>>1)*2+1)}x01234567 = wasm_u64x2_shr(vacc${(M>>1)*2}x01234567_${min(MR-1, (M>>1)*2+1)}x01234567, 32);
          }
        if (nc & 2) {
          $if NR == 4:
            $for M in range(MR):
              wasm_v128_store16_lane(c${M}, vacc, ${2 * M});
              c${M} += 2;

            vacc = wasm_u32x4_shr(vacc, 16);
          $else:
            $for M in range(MR):
              wasm_v128_store16_lane(c${M}, vacc${(M>>1)*2}x01234567_${min(MR-1, (M>>1)*2+1)}x01234567, ${M%2*4});
              c${M} += 2;

            $for M in range(0, MR, 2):
              vacc${(M>>1)*2}x01234567_${min(MR-1, (M>>1)*2+1)}x01234567 = wasm_u32x4_shr(vacc${(M>>1)*2}x01234567_${min(MR-1, (M>>1)*2+1)}x01234567, 16);
        }
        if (nc & 1) {
          $for M in range(MR):
            $if NR == 4:
              wasm_v128_store8_lane(c${M}, vacc, ${4 * M});
            $else:
              wasm_v128_store8_lane(c${M}, vacc${(M>>1)*2}x01234567_${min(MR-1, (M>>1)*2+1)}x01234567, ${M%2*8});
        }

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