// Copyright 2022 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 ["QS8", "QU8"]
$assert BATCH_TILE >= 1
$ABC = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
#include <assert.h>

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


$XINT8_T = {"QS8": "int8_t", "QU8": "uint8_t"}[DATATYPE]
$OUTPUT_MIN = {"QS8": -128, "QU8": 0}[DATATYPE]
$OUTPUT_MAX = {"QS8": 127, "QU8": 255}[DATATYPE]
void xnn_${DATATYPE.lower()}_vcvt_ukernel__scalar_u${BATCH_TILE}(
    size_t batch,
    const ${XINT8_T}* input,
    ${XINT8_T}* output,
    const struct xnn_${DATATYPE.lower()}_cvt_params params[restrict XNN_MIN_ELEMENTS(1)])
{
  assert(batch != 0);
  assert(batch % sizeof(${XINT8_T}) == 0);
  assert(input != NULL);
  assert(output != NULL);

  const int32_t vbias = 
      (int32_t) (((uint32_t) (int32_t) params->scalar.output_zero_point) << 8) -
      (int32_t) params->scalar.multiplier * (int32_t) params->scalar.input_zero_point + 
      INT32_C(0x80);
  const int32_t vmultiplier = params->scalar.multiplier;
  $if BATCH_TILE == 1:
    do {
      int32_t vacc = *input++;
      vacc = vbias + vacc * vmultiplier;

      int32_t vout = math_asr_s32(vacc, 8);
      vout = math_max_s32(vout, ${OUTPUT_MIN});
      vout = math_min_s32(vout, ${OUTPUT_MAX});
      *output++ = (${XINT8_T}) vout;

      batch -= sizeof(${XINT8_T});
    } while (batch != 0);
  $else:
    for (; batch >= ${BATCH_TILE} * sizeof(${XINT8_T}); batch -= ${BATCH_TILE} * sizeof(${XINT8_T})) {
      $for N in range(BATCH_TILE):
        int32_t vacc${ABC[N]} = input[${N}];
      input += ${BATCH_TILE};

      $for N in range(BATCH_TILE):
        vacc${ABC[N]} = vbias + vacc${ABC[N]} * vmultiplier;

      $for N in range(BATCH_TILE):
        int32_t vout${ABC[N]} = math_asr_s32(vacc${ABC[N]}, 8);

      $for N in range(BATCH_TILE):
        vout${ABC[N]} = math_max_s32(vout${ABC[N]}, ${OUTPUT_MIN});

      $for N in range(BATCH_TILE):
        vout${ABC[N]} = math_min_s32(vout${ABC[N]}, ${OUTPUT_MAX});

      $for N in range(BATCH_TILE):
        output[${N}] = (${XINT8_T}) vout${ABC[N]};
      output += ${BATCH_TILE};
    }
    if XNN_UNLIKELY(batch != 0) {
      $if BATCH_TILE == 2:
        int32_t vacc = *input;
        vacc = vbias + vacc * vmultiplier;

        int32_t vout = math_asr_s32(vacc, 8);
        vout = math_max_s32(vout, ${OUTPUT_MIN});
        vout = math_min_s32(vout, ${OUTPUT_MAX});
        *output = (${XINT8_T}) vout;
      $else:
        do {
          int32_t vacc = *input++;
          vacc = vbias + vacc * vmultiplier;

          int32_t vout = math_asr_s32(vacc, 8);
          vout = math_max_s32(vout, ${OUTPUT_MIN});
          vout = math_min_s32(vout, ${OUTPUT_MAX});
          *output++ = (${XINT8_T}) vout;

          batch -= sizeof(${XINT8_T});
        } while (batch != 0);
    }
}
