// 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 BATCH_TILE >= 1
#include <assert.h>
#include <stddef.h>
#include <stdint.h>

#include <xnnpack/math.h>
#include <xnnpack/rmaxabs.h>


void xnn_s16_rmaxabs_ukernel__scalar_x${BATCH_TILE}(
    size_t batch,
    const int16_t* input,
    uint16_t* output) {

  assert(batch > 0);
  assert(input != NULL);
  assert(output != NULL);

  $for N in range(BATCH_TILE):
    uint32_t vmax${N} = 0;

  $if BATCH_TILE > 1:
    for (; batch >= ${BATCH_TILE}; batch -= ${BATCH_TILE}) {
      $for N in range(BATCH_TILE):
        const int32_t vi${N} = (int32_t) input[${N}];
      input += ${BATCH_TILE};

      $for N in range(BATCH_TILE):
        const uint32_t vabs${N} = math_abs_s32(vi${N});

      $for N in range(BATCH_TILE):
        vmax${N} = math_max_u32(vmax${N}, vabs${N});
    }

    $BATCH_SLICE = 1
    $while BATCH_SLICE < BATCH_TILE:
      $for S in range(0, BATCH_TILE, BATCH_SLICE * 2):
        $if S + BATCH_SLICE < BATCH_TILE:
          vmax${S} = math_max_u32(vmax${S}, vmax${S + BATCH_SLICE});
      $BATCH_SLICE *= 2

  if (batch != 0) {
    do {
      const int32_t vi = (int32_t) *input++;
      const uint32_t vabs = math_abs_s32(vi);
      vmax0 = math_max_u32(vmax0, vabs);
    } while (--batch != 0);
  }
  *output = (uint16_t) vmax0;
}
