// 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 REQUANTIZATION in ["FP32", "RNDNU"]
$assert DATATYPE in ["QC8", "QS8", "QU8"]
$assert DATATYPE != "QC8" or REQUANTIZATION == "FP32"
$ABC = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
$assert CHANNEL_TILE % 8 == 0
$assert CHANNEL_TILE >= 8
$assert KERNEL_TILE >= 2
#include <assert.h>

#include <arm_neon.h>

#include <xnnpack/dwconv.h>
$if REQUANTIZATION == "FP32" and ARMV8:
  #include <xnnpack/intrinsics-polyfill.h>


$PARAMS_STRUCT = REQUANTIZATION.lower() + "_" + ("neonv8" if ARMV8 else "neon")
$PARAMS_UNION = "xnn_%s_conv_minmax_params" % DATATYPE.lower()
$XINT8_T = "uint8_t" if DATATYPE == "QU8" else "int8_t"
$XINT8X8_T = "uint8x8_t" if DATATYPE == "QU8" else "int8x8_t"
$XINT8X16_T = "uint8x16_t" if DATATYPE == "QU8" else "int8x16_t"
$VGET_LOW_X8 = "vget_low_u8" if DATATYPE == "QU8" else "vget_low_s8"
$VCOMBINE_X8 = "vcombine_u8" if DATATYPE == "QU8" else "vcombine_s8"
$VREINTERPRET_U32_X8 = "vreinterpret_u32_u8" if DATATYPE == "QU8" else "vreinterpret_u32_s8"
$VREINTERPRET_U16_X8 = "vreinterpret_u16_u8" if DATATYPE == "QU8" else "vreinterpret_u16_s8"
$VLD1_X8 = "vld1_u8" if DATATYPE == "QU8" else "vld1_s8"
$VLD1_DUP_X8 = "vld1_dup_u8" if DATATYPE == "QU8" else "vld1_dup_s8"
$VLD1Q_DUP_X8 = "vld1q_dup_u8" if DATATYPE == "QU8" else "vld1q_dup_s8"
$VST1_X8 = "vst1_u8" if DATATYPE == "QU8" else "vst1_s8"
$VST1Q_X8 = "vst1q_u8" if DATATYPE == "QU8" else "vst1q_s8"
$VST1_LANE_X8 = "vst1_lane_u8" if DATATYPE == "QU8" else "vst1_lane_s8"
$VST1Q_LANE_X8 = "vst1q_lane_u8" if DATATYPE == "QU8" else "vst1q_lane_s8"
$VMIN_X8 = "vmin_u8" if DATATYPE == "QU8" else "vmin_s8"
$VMAX_X8 = "vmax_u8" if DATATYPE == "QU8" else "vmax_s8"
$VMINQ_X8 = "vminq_u8" if DATATYPE == "QU8" else "vminq_s8"
$VMAXQ_X8 = "vmaxq_u8" if DATATYPE == "QU8" else "vmaxq_s8"
$VEXT_X8 = "vext_u8" if DATATYPE == "QU8" else "vext_s8"
$VQMOVXN_S16 = "vqmovun_s16" if DATATYPE == "QU8" else "vqmovn_s16"
$VQMOVXN_HIGH_S16 = "vqmovun_high_s16" if DATATYPE == "QU8" else "vqmovn_high_s16"
$ISA = "neonv8" if ARMV8 else "neon"
void xnn_${DATATYPE.lower()}_dwconv_minmax_${REQUANTIZATION.lower()}_ukernel_up${CHANNEL_TILE}x${KERNEL_TILE}__${ISA}_mul16(
    size_t channels,
    size_t output_width,
    const ${XINT8_T}** input,
    const void* weights,
    ${XINT8_T}* output,
    size_t input_stride,
    size_t output_increment,
    size_t input_offset,
    const ${XINT8_T}* zero,
    const union ${PARAMS_UNION} params[restrict XNN_MIN_ELEMENTS(1)]) XNN_OOB_READS
{
  assert(channels != 0);
  assert(output_width != 0);

  $if DATATYPE == "QU8":
    const uint8x8_t vkernel_zero_point = vld1_dup_u8(params->${PARAMS_STRUCT}.kernel_zero_point);
  $if REQUANTIZATION == "RNDNU":
    const int32x4_t vright_pre_shift = vld1q_dup_s32(&params->${PARAMS_STRUCT}.right_pre_shift);
    const int32x4_t vmultiplier = vld1q_dup_s32(&params->${PARAMS_STRUCT}.multiplier);
    const int32x4_t vright_post_shift = vld1q_dup_s32(&params->${PARAMS_STRUCT}.right_post_shift);
  $elif REQUANTIZATION == "FP32":
    $if DATATYPE != "QC8":
      const float32x4_t vscale = vld1q_dup_f32(&params->${PARAMS_STRUCT}.scale);
    $if not ARMV8:
      const float32x4_t vmagic_bias = vld1q_dup_f32(&params->${PARAMS_STRUCT}.magic_bias);
      const int32x4_t vmagic_bias_less_output_zero_point = vld1q_dup_s32(&params->${PARAMS_STRUCT}.magic_bias_less_output_zero_point);
  $if REQUANTIZATION != "FP32" or ARMV8:
    const int16x8_t voutput_zero_point = vld1q_dup_s16(&params->${PARAMS_STRUCT}.output_zero_point);
  $if CHANNEL_TILE == 8:
    const ${XINT8X8_T} voutput_min = ${VLD1_DUP_X8}(&params->${PARAMS_STRUCT}.output_min);
    const ${XINT8X8_T} voutput_max = ${VLD1_DUP_X8}(&params->${PARAMS_STRUCT}.output_max);
  $else:
    const ${XINT8X16_T} voutput_min = ${VLD1Q_DUP_X8}(&params->${PARAMS_STRUCT}.output_min);
    const ${XINT8X16_T} voutput_max = ${VLD1Q_DUP_X8}(&params->${PARAMS_STRUCT}.output_max);
  do {
    $for K in range(KERNEL_TILE):
      const ${XINT8_T}* i${K} = input[${K}];
      assert(i${K} != NULL);
      if XNN_UNPREDICTABLE(i${K} != zero) {
        i${K} = (const ${XINT8_T}*) ((uintptr_t) i${K} + input_offset);
      }
    input = (const ${XINT8_T}**) ((uintptr_t) input + input_stride);

    size_t c = channels;
    const void* w = weights;
    for (; c >= ${CHANNEL_TILE}; c -= ${CHANNEL_TILE}) {
      $for C in range(0, CHANNEL_TILE, 4):
        int32x4_t vacc${ABC[C:C+4]} = vld1q_s32(w); w = (const void*) ((const int32_t*) w + 4);

      $for K in range(KERNEL_TILE):

        $for C in range(0, CHANNEL_TILE, 8):
          $if DATATYPE == "QU8":
            const int16x8_t vi${K}x${ABC[C:C+8]} = vreinterpretq_s16_u16(vmovl_u8(vld1_u8(i${K}))); i${K} += 8;
            const int16x8_t vk${K}x${ABC[C:C+8]} = vreinterpretq_s16_u16(vsubl_u8(vld1_u8(w), vkernel_zero_point)); w = (const void*) ((const ${XINT8_T}*) w + 8);
          $else:
            const int16x8_t vi${K}x${ABC[C:C+8]} = vmovl_s8(vld1_s8(i${K})); i${K} += 8;
            const int16x8_t vk${K}x${ABC[C:C+8]} = vmovl_s8(vld1_s8(w)); w = (const void*) ((const ${XINT8_T}*) w + 8);

        $for C in range(0, CHANNEL_TILE, 8):
          vacc${ABC[C:C+4]} = vmlal_s16(vacc${ABC[C:C+4]}, vget_low_s16(vi${K}x${ABC[C:C+8]}), vget_low_s16(vk${K}x${ABC[C:C+8]}));
          vacc${ABC[C+4:C+8]} = vmlal_s16(vacc${ABC[C+4:C+8]}, vget_high_s16(vi${K}x${ABC[C:C+8]}), vget_high_s16(vk${K}x${ABC[C:C+8]}));

      $if REQUANTIZATION == "RNDNU":
        $for C in range(0, CHANNEL_TILE, 4):
          vacc${ABC[C:C+4]} = vqshlq_s32(vacc${ABC[C:C+4]}, vright_pre_shift);

        $for C in range(0, CHANNEL_TILE, 4):
          vacc${ABC[C:C+4]} = vqdmulhq_s32(vacc${ABC[C:C+4]}, vmultiplier);

        $for C in range(0, CHANNEL_TILE, 4):
          vacc${ABC[C:C+4]} = vrshlq_s32(vacc${ABC[C:C+4]}, vright_post_shift);
      $elif REQUANTIZATION == "FP32":
        $for C in range(0, CHANNEL_TILE, 4):
          float32x4_t vfpacc${ABC[C:C+4]} = vcvtq_f32_s32(vacc${ABC[C:C+4]});

        $if DATATYPE == "QC8":
          $for C in range(0, CHANNEL_TILE, 4):
            const float32x4_t vscale${ABC[C:C+4]} = vld1q_f32((const float*) w); w = (const void*) ((const float*) w + 4);

          $for C in range(0, CHANNEL_TILE, 4):
            vfpacc${ABC[C:C+4]} = vmulq_f32(vfpacc${ABC[C:C+4]}, vscale${ABC[C:C+4]});
        $else:
          $for C in range(0, CHANNEL_TILE, 4):
            vfpacc${ABC[C:C+4]} = vmulq_f32(vfpacc${ABC[C:C+4]}, vscale);

        $if ARMV8:
          $for C in range(0, CHANNEL_TILE, 4):
            vacc${ABC[C:C+4]} = vcvtnq_s32_f32(vfpacc${ABC[C:C+4]});
        $else:
          $for C in range(0, CHANNEL_TILE, 4):
            vacc${ABC[C:C+4]} = vreinterpretq_s32_f32(vaddq_f32(vfpacc${ABC[C:C+4]}, vmagic_bias));

          $for C in range(0, CHANNEL_TILE, 4):
            vacc${ABC[C:C+4]} = vqsubq_s32(vacc${ABC[C:C+4]}, vmagic_bias_less_output_zero_point);

#if XNN_ARCH_ARM64
      $for C in range(0, CHANNEL_TILE, 8):
        int16x8_t vacc${ABC[C:C+8]} = vqmovn_high_s32(vqmovn_s32(vacc${ABC[C:C+4]}), vacc${ABC[C+4:C+8]});

      $if REQUANTIZATION != "FP32" or ARMV8:
        $for C in range(0, CHANNEL_TILE, 8):
          vacc${ABC[C:C+8]} = vqaddq_s16(vacc${ABC[C:C+8]}, voutput_zero_point);

      $for C in range(0, CHANNEL_TILE, 16):
        $if C + 8 < CHANNEL_TILE:
          ${XINT8X16_T} vout${ABC[C:C+16]} = ${VQMOVXN_HIGH_S16}(${VQMOVXN_S16}(vacc${ABC[C:C+8]}), vacc${ABC[C+8:C+16]});
        $else:
          ${XINT8X8_T} vout${ABC[C:C+8]} = ${VQMOVXN_S16}(vacc${ABC[C:C+8]});
#else  // !XNN_ARCH_ARM64
      $for C in range(0, CHANNEL_TILE, 8):
        int16x8_t vacc${ABC[C:C+8]} = vcombine_s16(vqmovn_s32(vacc${ABC[C:C+4]}), vqmovn_s32(vacc${ABC[C+4:C+8]}));

      $if REQUANTIZATION != "FP32" or ARMV8:
        $for C in range(0, CHANNEL_TILE, 8):
          vacc${ABC[C:C+8]} = vqaddq_s16(vacc${ABC[C:C+8]}, voutput_zero_point);

      $for C in range(0, CHANNEL_TILE, 16):
        $if C + 8 < CHANNEL_TILE:
          ${XINT8X16_T} vout${ABC[C:C+16]} = ${VCOMBINE_X8}(${VQMOVXN_S16}(vacc${ABC[C:C+8]}), ${VQMOVXN_S16}(vacc${ABC[C+8:C+16]}));
        $else:
          ${XINT8X8_T} vout${ABC[C:C+8]} = ${VQMOVXN_S16}(vacc${ABC[C:C+8]});
#endif  // !XNN_ARCH_ARM64

      $for C in range(0, CHANNEL_TILE, 16):
        $if C + 8 < CHANNEL_TILE:
          vout${ABC[C:C+16]} = ${VMAXQ_X8}(vout${ABC[C:C+16]}, voutput_min);
        $else:
          $if CHANNEL_TILE == 8:
            vout${ABC[C:C+8]} = ${VMAX_X8}(vout${ABC[C:C+8]}, voutput_min);
          $else:
            vout${ABC[C:C+8]} = ${VMAX_X8}(vout${ABC[C:C+8]}, ${VGET_LOW_X8}(voutput_min));

      $for C in range(0, CHANNEL_TILE, 16):
        $if C + 8 < CHANNEL_TILE:
          vout${ABC[C:C+16]} = ${VMINQ_X8}(vout${ABC[C:C+16]}, voutput_max);
        $else:
          $if CHANNEL_TILE == 8:
            vout${ABC[C:C+8]} = ${VMIN_X8}(vout${ABC[C:C+8]}, voutput_max);
          $else:
            vout${ABC[C:C+8]} = ${VMIN_X8}(vout${ABC[C:C+8]}, ${VGET_LOW_X8}(voutput_max));

      $for C in range(0, CHANNEL_TILE, 16):
        $if C + 8 < CHANNEL_TILE:
          ${VST1Q_X8}(output, vout${ABC[C:C+16]}); output += 16;
        $else:
          ${VST1_X8}(output, vout${ABC[C:C+8]}); output += 8;
    }
    if XNN_UNLIKELY(c != 0) {
      $if CHANNEL_TILE > 8:
        const ${XINT8_T}* k = (const ${XINT8_T}*) ((const int32_t*) w + ${CHANNEL_TILE});
      ${"do " if CHANNEL_TILE > 8 else ""}{
        int32x4_t vacc${ABC[0:4]} = vld1q_s32(w); w = (const void*) ((const int32_t*) w + 4);
        int32x4_t vacc${ABC[4:8]} = vld1q_s32(w); w = (const void*) ((const int32_t*) w + 4);

        $for K in range(KERNEL_TILE):
          $if CHANNEL_TILE > 8:
            $if DATATYPE == "QU8":
              const int16x8_t vi${K}x${ABC[0:8]} = vreinterpretq_s16_u16(vmovl_u8(vld1_u8(i${K}))); i${K} += 8;
            $else:
              const int16x8_t vi${K}x${ABC[0:8]} = vmovl_s8(vld1_s8(i${K})); i${K} += 8;
          $else:
            $if DATATYPE == "QU8":
              const int16x8_t vi${K}x${ABC[0:8]} = vreinterpretq_s16_u16(vmovl_u8(vld1_u8(i${K})));
            $else:
              const int16x8_t vi${K}x${ABC[0:8]} = vmovl_s8(vld1_s8(i${K}));
          $if CHANNEL_TILE > 8:
            $if K == 0:
              $if DATATYPE == "QU8":
                const int16x8_t vk${K}x${ABC[0:8]} = vreinterpretq_s16_u16(vsubl_u8(vld1_u8(k), vkernel_zero_point)); k += 8;
              $else:
                const int16x8_t vk${K}x${ABC[0:8]} = vmovl_s8(vld1_s8(k)); k += 8;
            $else:
              $if DATATYPE == "QU8":
                const int16x8_t vk${K}x${ABC[0:8]} = vreinterpretq_s16_u16(vsubl_u8(vld1_u8((const void*) (k + ${K * CHANNEL_TILE - 8})), vkernel_zero_point));
              $else:
                const int16x8_t vk${K}x${ABC[0:8]} = vmovl_s8(vld1_s8((const void*) (k + ${K * CHANNEL_TILE - 8})));
          $else:
            $if K == 0:
              $if DATATYPE == "QU8":
                const int16x8_t vk${K}x${ABC[0:8]} = vreinterpretq_s16_u16(vsubl_u8(vld1_u8(w), vkernel_zero_point));
              $else:
                const int16x8_t vk${K}x${ABC[0:8]} = vmovl_s8(vld1_s8(w));
            $else:
              $if DATATYPE == "QU8":
                const int16x8_t vk${K}x${ABC[0:8]} = vreinterpretq_s16_u16(vsubl_u8(vld1_u8((const void*) ((const ${XINT8_T}*) w + ${K * CHANNEL_TILE})), vkernel_zero_point));
              $else:
                const int16x8_t vk${K}x${ABC[0:8]} = vmovl_s8(vld1_s8((const void*) ((const ${XINT8_T}*) w + ${K * CHANNEL_TILE})));

          vacc${ABC[0:4]} = vmlal_s16(vacc${ABC[0:4]}, vget_low_s16(vi${K}x${ABC[0:8]}), vget_low_s16(vk${K}x${ABC[0:8]}));
          vacc${ABC[4:8]} = vmlal_s16(vacc${ABC[4:8]}, vget_high_s16(vi${K}x${ABC[0:8]}), vget_high_s16(vk${K}x${ABC[0:8]}));

        $if REQUANTIZATION == "RNDNU":
          vacc${ABC[0:4]} = vqshlq_s32(vacc${ABC[0:4]}, vright_pre_shift);
          vacc${ABC[4:8]} = vqshlq_s32(vacc${ABC[4:8]}, vright_pre_shift);

          vacc${ABC[0:4]} = vqdmulhq_s32(vacc${ABC[0:4]}, vmultiplier);
          vacc${ABC[4:8]} = vqdmulhq_s32(vacc${ABC[4:8]}, vmultiplier);

          vacc${ABC[0:4]} = vrshlq_s32(vacc${ABC[0:4]}, vright_post_shift);
          vacc${ABC[4:8]} = vrshlq_s32(vacc${ABC[4:8]}, vright_post_shift);
        $elif REQUANTIZATION == "FP32":
          float32x4_t vfpacc${ABC[0:4]} = vcvtq_f32_s32(vacc${ABC[0:4]});
          float32x4_t vfpacc${ABC[4:8]} = vcvtq_f32_s32(vacc${ABC[4:8]});

          $if DATATYPE == "QC8":
            const float32x4_t vscale${ABC[0:4]} = vld1q_f32((const float*) ((uintptr_t) w + ${CHANNEL_TILE - 8} * sizeof(int32_t) + ${CHANNEL_TILE * KERNEL_TILE} * sizeof(${XINT8_T})));
            const float32x4_t vscale${ABC[4:8]} = vld1q_f32((const float*) ((uintptr_t) w + ${CHANNEL_TILE - 8} * sizeof(int32_t) + ${CHANNEL_TILE * KERNEL_TILE} * sizeof(${XINT8_T}) + 4 * sizeof(float)));
            vfpacc${ABC[0:4]} = vmulq_f32(vfpacc${ABC[0:4]}, vscale${ABC[0:4]});
            vfpacc${ABC[4:8]} = vmulq_f32(vfpacc${ABC[4:8]}, vscale${ABC[4:8]});
          $else:
            vfpacc${ABC[0:4]} = vmulq_f32(vfpacc${ABC[0:4]}, vscale);
            vfpacc${ABC[4:8]} = vmulq_f32(vfpacc${ABC[4:8]}, vscale);

          $if ARMV8:
            vacc${ABC[0:4]} = vcvtnq_s32_f32(vfpacc${ABC[0:4]});
            vacc${ABC[4:8]} = vcvtnq_s32_f32(vfpacc${ABC[4:8]});
          $else:
            vacc${ABC[0:4]} = vreinterpretq_s32_f32(vaddq_f32(vfpacc${ABC[0:4]}, vmagic_bias));
            vacc${ABC[4:8]} = vreinterpretq_s32_f32(vaddq_f32(vfpacc${ABC[4:8]}, vmagic_bias));

            vacc${ABC[0:4]} = vqsubq_s32(vacc${ABC[0:4]}, vmagic_bias_less_output_zero_point);
            vacc${ABC[4:8]} = vqsubq_s32(vacc${ABC[4:8]}, vmagic_bias_less_output_zero_point);

#if XNN_ARCH_ARM64
        int16x8_t vacc${ABC[0:8]} = vqmovn_high_s32(vqmovn_s32(vacc${ABC[0:4]}), vacc${ABC[4:8]});
#else
        int16x8_t vacc${ABC[0:8]} = vcombine_s16(vqmovn_s32(vacc${ABC[0:4]}), vqmovn_s32(vacc${ABC[4:8]}));
#endif
        $if REQUANTIZATION != "FP32" or ARMV8:
          vacc${ABC[0:8]} = vqaddq_s16(vacc${ABC[0:8]}, voutput_zero_point);

        ${XINT8X8_T} vout${ABC[0:8]} = ${VQMOVXN_S16}(vacc${ABC[0:8]});
        $if CHANNEL_TILE == 8:
          vout${ABC[0:8]} = ${VMAX_X8}(vout${ABC[0:8]}, voutput_min);
          vout${ABC[0:8]} = ${VMIN_X8}(vout${ABC[0:8]}, voutput_max);
        $else:
          vout${ABC[0:8]} = ${VMAX_X8}(vout${ABC[0:8]}, ${VGET_LOW_X8}(voutput_min));
          vout${ABC[0:8]} = ${VMIN_X8}(vout${ABC[0:8]}, ${VGET_LOW_X8}(voutput_max));

        $if CHANNEL_TILE > 8:
          if XNN_LIKELY(c >= 8) {
            ${VST1_X8}(output, vout${ABC[0:8]}); output += 8;
            c -= 8;
          } else {
            if (c & 4) {
              vst1_lane_u32((void*) output, ${VREINTERPRET_U32_X8}(vout${ABC[0:8]}), 0); output += 4;
              vout${ABC[0:8]} = ${VEXT_X8}(vout${ABC[0:8]}, vout${ABC[0:8]}, 4);
            }
            if (c & 2) {
              vst1_lane_u16((void*) output, ${VREINTERPRET_U16_X8}(vout${ABC[0:8]}), 0); output += 2;
              vout${ABC[0:8]} = ${VEXT_X8}(vout${ABC[0:8]}, vout${ABC[0:8]}, 2);
            }
            if (c & 1) {
              ${VST1_LANE_X8}(output, vout${ABC[0:8]}, 0); output += 1;
            }
            c = 0;
          }
        $else:
          if (c & 4) {
            vst1_lane_u32((void*) output, ${VREINTERPRET_U32_X8}(vout${ABC[0:8]}), 0); output += 4;
            vout${ABC[0:8]} = ${VEXT_X8}(vout${ABC[0:8]}, vout${ABC[0:8]}, 4);
          }
          if (c & 2) {
            vst1_lane_u16((void*) output, ${VREINTERPRET_U16_X8}(vout${ABC[0:8]}), 0); output += 2;
            vout${ABC[0:8]} = ${VEXT_X8}(vout${ABC[0:8]}, vout${ABC[0:8]}, 2);
          }
          if (c & 1) {
            ${VST1_LANE_X8}(output, vout${ABC[0:8]}, 0); output += 1;
          }
      }${" while (c != 0);" if CHANNEL_TILE > 8 else ""}
    }

    output = (${XINT8_T}*) ((uintptr_t) output + output_increment);
  } while (--output_width != 0);
}
