// 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.
#include <assert.h>
#include <math.h>

#include <smmintrin.h>

#include "xnnpack/common.h"
#include "xnnpack/intrinsics-polyfill.h"
#include "xnnpack/math.h"
#include "xnnpack/reduce.h"
#include "xnnpack/unaligned.h"


$UNROLL = CHANNELS >> 2
$MIN_F32 = "__builtin_wasm_min_f32" if WASM else "math_min_f32"
$MAX_F32 = "__builtin_wasm_max_f32" if WASM else "math_max_f32"
$PARAMS_STRUCT = "fp32_sse4"
void xnn_qs8_rdsum_ukernel_${ACCUMULATORS}p${ACCUMULATORS}x__sse41_c${CHANNELS}(
    size_t rows,
    size_t channels,
    const int8_t* input,
    size_t input_stride,
    const int8_t* zero,
    int32_t* output,
    const struct xnn_qs8_rsum_params params[restrict XNN_MIN_ELEMENTS(1)]) XNN_OOB_READS
{
  assert(rows != 0);
  assert(channels != 0);
  assert(input != NULL);
  assert(output != NULL);

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

    $for C in range(0, CHANNELS, 4):
      __m128i vacc${C} = _mm_setzero_si128();

    // 256 int8s may be summed into an int16 before overflowing
    // To prevent handling the tails of the inner 256 loop, we round 256 down to
    // the nearest integer multiple of ACCUMULATORS.
    $OVERFLOW = (256 // ACCUMULATORS) * ACCUMULATORS
    int r = rows;
    while (r > 0) {
      $for C in range(0, CHANNELS, 8):
        __m128i vacc16_${C} = _mm_setzero_si128();
      for (int current_batch = min(r, ${OVERFLOW}); current_batch > 0; current_batch -= ${ACCUMULATORS}) {
        $for N in range(1, ACCUMULATORS, 2):
          if XNN_UNPREDICTABLE(current_batch < ${N+1}) {
            i${N} = zero;
          }
          if XNN_UNPREDICTABLE(current_batch <= ${N+1}) {
            i${N+1} = zero;
          }
        $for C in range(0, CHANNELS, 8):
          __m128i vin${C};
        $for ACC in range(ACCUMULATORS):
          $for C in range(0, CHANNELS, 8):
            vin${C} = _mm_cvtepi8_epi16(_mm_loadl_epi64((const __m128i*)&i${ACC}[${C}]));
          $for C in range(0, CHANNELS, 8):
            vacc16_${C} = _mm_add_epi16(vacc16_${C}, vin${C});
        $for N in range(0, ACCUMULATORS):
          i${N} = (const int8_t*) ((uintptr_t) i${N} + input_increment);
      }
      $for C in range(0, CHANNELS, 8):
        vacc${C} = _mm_add_epi32(vacc${C}, _mm_cvtepi16_epi32(vacc16_${C}));
        vacc${C+4} = _mm_add_epi32(vacc${C+4}, _mm_cvtepi16_epi32(_mm_srli_si128(vacc16_${C}, 8)));
      r = doz(r, ${OVERFLOW});
    }

    $for C in range(0, CHANNELS, 4):
      __m128i vo${C} = _mm_loadu_si128((const __m128i*) ((uintptr_t) output + ${C} * sizeof(int32_t)));
    $for C in range(0, CHANNELS, 4):
      vo${C} = _mm_add_epi32(vo${C}, vacc${C});
    $for C in range(0, CHANNELS, 4):
      _mm_storeu_si128((__m128i*) output, vo${C}); output += 4;

    input = (const int8_t*) ((uintptr_t) input + ${CHANNELS} * sizeof(int8_t));
  }
  if (channels != 0) {
    input_increment = ${ACCUMULATORS} * input_stride;
    // 256 int8s may be summed into an int16 before overflowing.
    do {
      int num_batches = floor((rows + ${OVERFLOW - 1}) / ${OVERFLOW});
      int r = rows;
      const int8_t* i0 = input;
      $for ACC in range(1, ACCUMULATORS):
        const int8_t* i${ACC} = (const int8_t*) ((uintptr_t) input + ${ACC} * input_stride);

      __m128i vacc0 = _mm_setzero_si128();
      __m128i vacc1 = _mm_setzero_si128();

      for (; num_batches > 0; --num_batches) {
        __m128i vacc16 = _mm_setzero_si128();
        for (int current_batch = min(r, ${OVERFLOW}); current_batch > 0; current_batch -= ${ACCUMULATORS}) {
          $for N in range(1, ACCUMULATORS, 2):
            if XNN_UNPREDICTABLE(current_batch < ${N+1}) {
              i${N} = zero;
            }
            if XNN_UNPREDICTABLE(current_batch <= ${N+1}) {
              i${N+1} = zero;
            }

          $for ACC in range(ACCUMULATORS):
            __m128i vin${ACC} = _mm_cvtepi8_epi16(_mm_loadl_epi64((const __m128i*)&i${ACC}[0]));
          $for ACC in range(ACCUMULATORS):
            vacc16 = _mm_add_epi16(vacc16, vin${ACC});
          $for N in range(ACCUMULATORS):
            i${N} = (const int8_t*) ((uintptr_t) i${N} + input_increment);
        }
        vacc0 = _mm_add_epi32(vacc0, _mm_cvtepi16_epi32(vacc16));
        vacc1 = _mm_add_epi32(vacc1, _mm_cvtepi16_epi32(_mm_srli_si128(vacc16, 8)));
        r = doz(r, ${OVERFLOW});
      }

      if XNN_LIKELY(channels >= 8) {
        __m128i vo0 = _mm_loadu_si128((const __m128i*) output);
        __m128i vo1 = _mm_loadu_si128((const __m128i*) ((uintptr_t) output + 4 * sizeof(int32_t)));
        vo0 = _mm_add_epi32(vo0, vacc0);
        vo1 = _mm_add_epi32(vo1, vacc1);
        _mm_storeu_si128((__m128i*) output, vo0); output += 4;
        _mm_storeu_si128((__m128i*) output, vo1); output += 4;
        channels -= 8;
        input = (const int8_t*) ((uintptr_t) input + 8 * sizeof(int8_t));
      } else {
        if (channels & 4) {
          __m128i vo = _mm_loadu_si128((const __m128i*) output);
          vo = _mm_add_epi32(vo, vacc0);
          _mm_storeu_si128((__m128i*) output, vo); output += 4;
          vacc0 = vacc1;
        }
        if (channels & 2) {
          __m128i vo = _mm_loadl_epi64((const __m128i*) output);
          vo = _mm_add_epi32(vo, vacc0);
          _mm_storel_epi64((__m128i*) output, vo); output += 2;
          vacc0 = _mm_srli_si128(vacc0, 8);
        }
        if (channels & 1) {
          __m128i vo = _mm_cvtsi32_si128(unaligned_load_s32(output));
          vo = _mm_add_epi32(vo, vacc0);
          _mm_storeu_si32(output, vo);
        }
        channels = 0;
      }
    } while (channels != 0);
  }
}
