// Copyright 2024 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 % 32 == 0
$assert BATCH_TILE >= 32
$SIMD_TILE = BATCH_TILE // 32
$assert ACCUMULATORS <= SIMD_TILE

#include <assert.h>

#include "xnnpack/simd/f32-hvx.h"

#include "xnnpack/common.h"
#include "xnnpack/reduce.h"


$ACC_SUFFIX = "" if ACCUMULATORS == 1 else "_acc%d" % ACCUMULATORS
void xnn_f32_rsum_ukernel__hvx_u${BATCH_TILE}${ACC_SUFFIX}(
    size_t batch,
    const float* input,
    float* output,
    const struct xnn_f32_scale_params params[restrict XNN_MIN_ELEMENTS(1)]) XNN_OOB_READS
{
  assert(batch != 0);
  assert(batch % sizeof(float) == 0);
  assert(input != NULL);
  assert(output != NULL);

  $for A in range(ACCUMULATORS):
    xnn_simd_f32_t vacc${A} = xnn_zero_f32();
  $if BATCH_TILE > 32:
    for (; batch >= ${BATCH_TILE} * sizeof(float); batch -= ${BATCH_TILE} * sizeof(float)) {
      const xnn_simd_f32_t vt0 = xnn_loadu_f32(input);
      $for N in range(1, SIMD_TILE):
        const xnn_simd_f32_t vt${N} = xnn_loadu_f32(input + ${N * 32});
      input += ${BATCH_TILE};

      $for N in range(SIMD_TILE):
        vacc${N % ACCUMULATORS} = xnn_add_f32(vacc${N % ACCUMULATORS}, vt${N});
    }
    $if ACCUMULATORS > 1:
      $ACC_SLICE = 1
      $while ACC_SLICE < ACCUMULATORS:
        $for A in range(0, ACCUMULATORS, ACC_SLICE * 2):
          $if A + ACC_SLICE < ACCUMULATORS:
            vacc${A} = xnn_add_f32(vacc${A}, vacc${A + ACC_SLICE});
        $ACC_SLICE *= 2
  for (; batch >= 32 * sizeof(float); batch -= 32 * sizeof(float)) {
    const xnn_simd_f32_t vt = xnn_loadu_f32(input);
    input += 32;

    vacc0 = xnn_add_f32(vacc0, vt);
  }

  if XNN_UNLIKELY(batch) {
    const xnn_simd_f32_t vt = xnn_loadu_f32(input);
    HVX_VectorPred mask = Q6_Q_vsetq_R(batch);

    vacc0 = xnn_add_f32(vacc0, Q6_V_vmux_QVV(mask, vt, xnn_zero_f32()));
  }

  vacc0 = xnn_add_f32(vacc0, Q6_V_vror_VR(vacc0, 64));
  vacc0 = xnn_add_f32(vacc0, Q6_V_vror_VR(vacc0, 32));
  vacc0 = xnn_add_f32(vacc0, Q6_V_vror_VR(vacc0, 16));
  vacc0 = xnn_add_f32(vacc0, Q6_V_vror_VR(vacc0, 8));
  vacc0 = xnn_add_f32(vacc0, Q6_V_vror_VR(vacc0, 4));

  float partial_sum = *((float*) &vacc0);

  const float vscale = params->scalar.scale;
  *output += partial_sum * vscale;
}
