// 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.

$ABC = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
#include <assert.h>

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


$CHANNELS = 4
void xnn_f32_rdsum_ukernel_${ACCUMULATORS}p${ACCUMULATORS}x__scalar_c4(
    size_t rows,
    size_t channels,
    const float* input,
    size_t input_stride,
    const float* zero,
    float* output,
    const struct xnn_f32_scale_params params[restrict XNN_MIN_ELEMENTS(1)])
{
  assert(rows != 0);
  assert(channels != 0);
  assert(input != NULL);
  assert(output != NULL);

  const float vscale = params->scalar.scale;

  size_t input_increment = ${ACCUMULATORS} * input_stride;
  for (; channels >= ${CHANNELS}; channels -= ${CHANNELS}) {
    const float* i0 = input;
    $for i in range(1, ACCUMULATORS):
      const float* i${i} = (const float*) ((uintptr_t) i${i - 1} + input_stride);
    $for i in range(CHANNELS):
      float vacc${i} = 0.f;

    for (int r = rows; r > 0; r -= ${ACCUMULATORS}) {
      $for N in range(1, ACCUMULATORS, 2):
        if XNN_UNPREDICTABLE(r < ${N+1}) {
          i${N} = zero;
        }
        if XNN_UNPREDICTABLE(r <= ${N+1}) {
          i${N+1} = zero;
        }
      $for j in range(ACCUMULATORS):
        $for c in range(CHANNELS):
          vacc${c} += i${j}[${c}];
      $for N in range(0, ACCUMULATORS):
        i${N} = (const float*) ((uintptr_t) i${N} + input_increment);
    }
    $for i in range(CHANNELS):
      vacc${i} = vacc${i} * vscale;

    $for i in range(0, CHANNELS):
      *output++ += vacc${i};

    input = (const float*) ((uintptr_t) input + ${CHANNELS} * sizeof(float));
  }
  if (channels != 0) {
    size_t input_increment = ${ACCUMULATORS} * input_stride;
    const float* i0 = input;
    $for i in range(1, ACCUMULATORS):
      const float* i${i} = (const float*) ((uintptr_t) i${i - 1} + input_stride);
    $for i in range(CHANNELS - 1):
      float vacc${i} = 0.f;

    for (int r = rows; r > 0; r -= ${ACCUMULATORS}) {
      $for N in range(1, ACCUMULATORS, 2):
        if XNN_UNPREDICTABLE(r < ${N+1}) {
          i${N} = zero;
        }
        if XNN_UNPREDICTABLE(r <= ${N+1}) {
          i${N+1} = zero;
        }
      $for j in range(0, ACCUMULATORS):
        $for c in range(0, CHANNELS-1):
          vacc${c} += i${j}[${c}];
      $for N in range(0, ACCUMULATORS):
        i${N} = (const float*) ((uintptr_t) i${N} + input_increment);
    }
    $for i in range(CHANNELS-1):
      vacc${i} = vacc${i} * vscale;

    if (channels & 2) {
      *output++ += vacc0;
      *output++ += vacc1;
      vacc0 = vacc2;
    }
    if (channels & 1) {
      *output++ += vacc0;
    }
  }
}
