// 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
$assert OP in ["MAX", "MIN", "MINMAX"]
$USE_REDUCE = 0
#include <assert.h>

#include <immintrin.h>

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


$ACC_SUFFIX = "" if ACCUMULATORS == 1 else "_acc%d" % ACCUMULATORS
$EMIT_MIN = "MIN" in OP
$EMIT_MAX = "MAX" in OP
void xnn_f16_r${OP.lower()}_ukernel__avx512fp16_u${BATCH_TILE}${ACC_SUFFIX}(
    size_t batch,
    const xnn_float16* input,
    xnn_float16* output,
    const struct xnn_f16_default_params params[restrict XNN_MIN_ELEMENTS(1)])
{
  assert(batch != 0);
  assert(batch % sizeof(uint16_t) == 0);
  assert(input != NULL);
  assert(output != NULL);

#if defined(__AVX512FP16__)
  const uint16_t* i = (const uint16_t*) input;
  $if EMIT_MIN:
    __m512h vmin0 = _mm512_castsi512_ph(_mm512_set1_epi16(*i));
    $if EMIT_MAX:
      __m512h vmax0 = vmin0;
  $elif EMIT_MAX:
    __m512h vmax0 = _mm512_castsi512_ph(_mm512_set1_epi16(*i));
  $for A in range(1, ACCUMULATORS):
    $if EMIT_MIN:
      __m512h vmin${A} = vmin0;
    $if EMIT_MAX:
      __m512h vmax${A} = vmax0;
  $if BATCH_TILE > 32:
    for (; batch >= ${BATCH_TILE} * sizeof(uint16_t); batch -= ${BATCH_TILE} * sizeof(uint16_t)) {
      const __m512h vt0 = _mm512_loadu_ph(i);
      $for N in range(1, SIMD_TILE):
        const __m512h vt${N} = _mm512_loadu_ph((i + ${N * 32}));
      i += ${BATCH_TILE};

      $for N in range(SIMD_TILE):
        $if EMIT_MIN:
          vmin${N % ACCUMULATORS} = _mm512_min_ph(vmin${N % ACCUMULATORS}, vt${N});
        $if EMIT_MAX:
          vmax${N % ACCUMULATORS} = _mm512_max_ph(vmax${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:
            $if EMIT_MIN:
              vmin${A} = _mm512_min_ph(vmin${A}, vmin${A + ACC_SLICE});
            $if EMIT_MAX:
              vmax${A} = _mm512_max_ph(vmax${A}, vmax${A + ACC_SLICE});
        $ACC_SLICE *= 2
  for (; batch >= 32 * sizeof(uint16_t); batch -= 32 * sizeof(uint16_t)) {
    const __m512h vt = _mm512_loadu_ph(i);
    i += 32;

    $if EMIT_MIN:
      vmin0 = _mm512_min_ph(vmin0, vt);
    $if EMIT_MAX:
      vmax0 = _mm512_max_ph(vmax0, vt);
  }
  if XNN_UNLIKELY(batch != 0) {
    assert(batch >= 1 * sizeof(uint16_t));
    assert(batch <= 31 * sizeof(uint16_t));

    // Prepare mask for valid elements (depends on batch).
    batch >>= XNN_LOG2_SIZEOF_HALF;
    const __mmask32 vmask = _cvtu32_mask32((uint32_t) ((UINT32_C(1) << batch) - UINT32_C(1)));

    const __m512h vt = _mm512_castsi512_ph(_mm512_maskz_loadu_epi16(vmask, i));

    $if EMIT_MIN:
      vmin0 = _mm512_mask_min_ph(vmin0, vmask, vmin0, vt);
    $if EMIT_MAX:
      vmax0 = _mm512_mask_max_ph(vmax0, vmask, vmax0, vt);
  }
  $if USE_REDUCE:
    $if EMIT_MIN:
      *((uint16_t*) output) = _mm512_reduce_min_ph(vmin0)
      $if EMIT_MAX:
        *((uint16_t*) output + 1) = _mm512_reduce_max_ph(vmax0);
    $elif EMIT_MAX:
      *((uint16_t*) output) = _mm512_reduce_max_ph(vmax0);
  $else:
    $if EMIT_MIN:
      __m256h vmin256 = _mm256_min_ph(_mm512_castph512_ph256(vmin0), _mm256_castpd_ph(_mm512_extractf64x4_pd(_mm512_castph_pd(vmin0), 1)));
    $if EMIT_MAX:
      __m256h vmax256 = _mm256_max_ph(_mm512_castph512_ph256(vmax0), _mm256_castpd_ph(_mm512_extractf64x4_pd(_mm512_castph_pd(vmax0), 1)));
    $if EMIT_MIN:
      __m128h vmin = _mm_min_ph(_mm256_castph256_ph128(vmin256), _mm_castps_ph(_mm256_extractf128_ps(_mm256_castph_ps(vmin256), 1)));
    $if EMIT_MAX:
      __m128h vmax = _mm_max_ph(_mm256_castph256_ph128(vmax256), _mm_castps_ph(_mm256_extractf128_ps(_mm256_castph_ps(vmax256), 1)));
    $if EMIT_MIN:
      vmin = _mm_min_ph(vmin, _mm_castps_ph(_mm_movehl_ps(_mm_castph_ps(vmin), _mm_castph_ps(vmin))));
    $if EMIT_MAX:
      vmax = _mm_max_ph(vmax, _mm_castps_ph(_mm_movehl_ps(_mm_castph_ps(vmax), _mm_castph_ps(vmax))));
    $if EMIT_MIN:
      vmin = _mm_min_ph(vmin, _mm_castps_ph(_mm_movehdup_ps(_mm_castph_ps(vmin))));
    $if EMIT_MAX:
      vmax = _mm_max_ph(vmax, _mm_castps_ph(_mm_movehdup_ps(_mm_castph_ps(vmax))));
    $if EMIT_MIN:
      vmin = _mm_min_sh(vmin, _mm_castsi128_ph(_mm_srli_epi32(_mm_castph_si128(vmin), 16)));
    $if EMIT_MAX:
      vmax = _mm_max_sh(vmax, _mm_castsi128_ph(_mm_srli_epi32(_mm_castph_si128(vmax), 16)));

    $if EMIT_MIN:
      *((uint16_t*) output) = (uint16_t) _mm_extract_epi16(_mm_castph_si128(vmin), 0);
      $if EMIT_MAX:
        *((uint16_t*) output + 1) = (uint16_t) _mm_extract_epi16(_mm_castph_si128(vmax), 0);
    $elif EMIT_MAX:
      *((uint16_t*) output) = (uint16_t) _mm_extract_epi16(_mm_castph_si128(vmax), 0);
#endif  // defined(__AVX512FP16__)
}
