// Copyright 2019 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
$ABC = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
#include <assert.h>

#include "xnnpack/common.h"
#include "xnnpack/math.h"
#include "xnnpack/vunary.h"


$MIN_F32 = "__builtin_wasm_min_f32" if WASM else "math_min_f32"
$MAX_F32 = "__builtin_wasm_max_f32" if WASM else "math_max_f32"
void xnn_f32_vhswish_ukernel__${"wasm" if WASM else "scalar"}_u${BATCH_TILE}(
    size_t batch,
    const float* input,
    float* output,
    const struct xnn_f32_default_params params[restrict XNN_MIN_ELEMENTS(1)])
{
  assert(batch != 0);
  assert(batch % sizeof(float) == 0);
  assert(input != NULL);
  assert(output != NULL);

  const float vsixth = 0x1.555556p-3f;
  const float vthree = 3.0f;
  const float vsix = 6.0f;
  const float vzero = 0.0f;

  $if BATCH_TILE > 1:
    for (; batch >= ${BATCH_TILE} * sizeof(float); batch -= ${BATCH_TILE} * sizeof(float)) {
      $for N in range(BATCH_TILE):
        float vx${ABC[N]} = input[${N}];
      input += ${BATCH_TILE};

      $for N in range(BATCH_TILE):
        float vacc${ABC[N]} = vx${ABC[N]} + vthree;
        vx${ABC[N]} *= vsixth;

      $for N in range(BATCH_TILE):
        vacc${ABC[N]} = ${MAX_F32}(vacc${ABC[N]}, vzero);

      $for N in range(BATCH_TILE):
        vacc${ABC[N]} = ${MIN_F32}(vacc${ABC[N]}, vsix);

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

      $for N in range(BATCH_TILE):
        output[${N}] = vacc${ABC[N]};
      output += ${BATCH_TILE};
    }
    if XNN_UNLIKELY(batch != 0) {
      $if BATCH_TILE > 2:
        do {
          float vx = *input++;
          float vacc = vx + vthree;
          vx *= vsixth;
          vacc = ${MAX_F32}(vacc, vzero);
          vacc = ${MIN_F32}(vacc, vsix);
          vacc *= vx;
          *output++ = vacc;
          batch -= sizeof(float);
        } while (batch != 0);
      $else:
        float vx = *input;
        float vacc = vx + vthree;
        vx *= vsixth;
        vacc = ${MAX_F32}(vacc, vzero);
        vacc = ${MIN_F32}(vacc, vsix);
        vacc *= vx;
        *output = vacc;
    }
  $else:
    for (; batch >= sizeof(float); batch -= sizeof(float)) {
      float vx = *input++;
      float vacc = vx + vthree;
      vx *= vsixth;
      vacc = ${MAX_F32}(vacc, vzero);
      vacc = ${MIN_F32}(vacc, vsix);
      vacc *= vx;
      *output++ = vacc;
    }
}
