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

#include <assert.h>

#include "xnnpack/math.h"
#include "xnnpack/ppmm.h"


void xnn_f32_ppmm_minmax_ukernel_${MR}x${NR}__scalar(
  size_t mr,
  size_t nc,
  size_t kc,
  const float* restrict a,
  const float* restrict w,
  float* restrict c,
  size_t cm_stride,
  size_t cn_stride,
  const union xnn_f32_minmax_params params[restrict XNN_MIN_ELEMENTS(1)])
{
  assert(mr != 0);
  assert(mr <= ${MR});
  assert(nc != 0);
  assert(kc != 0);
  assert(kc % sizeof(float) == 0);

  float* c0 = c;
  $for M in range(1, MR):
    float* c${M} = (float*) ((uintptr_t) c${M-1} + cm_stride);
    $if M % 2 == 0:
      if XNN_UNPREDICTABLE(mr <= ${M}) {
        c${M} = c${M-1};
      }
    $elif M + 1 == MR:
      if XNN_UNPREDICTABLE(mr != ${M+1}) {
        c${M} = c${M-1};
      }
    $else:
      if XNN_UNPREDICTABLE(mr < ${M+1}) {
        c${M} = c${M-1};
      }

  do {
    $for N in range(NR):
      float vacc0x${N} = w[${N}];
    $for M in range(1, MR):
      $for N in range(NR):
        float vacc${M}x${N} = vacc0x${N};
    w += ${NR};

    size_t k = kc;
    do {
      $for M in range(MR):
        const float va${M} = a[${M}];
      a += ${MR};

      $for N in range(NR):
        const float vb${N} = w[${N}];
      w += ${NR};

      $for N in range(NR):
        $for M in range(MR):
          vacc${M}x${N} += va${M} * vb${N};

      k -= sizeof(float);
    } while (k != 0);

    const float vmax = params->scalar.max;
    $for N in range(NR):
      $for M in range(MR):
        vacc${M}x${N} = math_min_f32(vacc${M}x${N}, vmax);

    const float vmin = params->scalar.min;
    $for N in range(NR):
      $for M in range(MR):
        vacc${M}x${N} = math_max_f32(vacc${M}x${N}, vmin);

    if XNN_LIKELY(nc >= ${NR}) {
      $for M in reversed(range(MR)):
        $for N in range(NR):
          c${M}[${N}] = vacc${M}x${N};

      a = (const float*) ((uintptr_t) a - kc * ${MR});

      $for M in reversed(range(MR)):
        c${M} = (float*) ((uintptr_t) c${M} + cn_stride);

      nc -= ${NR};
    } else {
      $for LOG2N in reversed(range(NR.bit_length())):
        $if NR != 1 << LOG2N:
          if (nc & ${1 << LOG2N}) {
            $if LOG2N != 0:
              $for M in reversed(range(MR)):
                $for N in range(1 << LOG2N):
                  c${M}[${N}] = vacc${M}x${N};

              $for M in reversed(range(MR)):
                $for N in range(NR - (1 << LOG2N) - 1):
                  vacc${M}x${N} = vacc${M}x${N + (1 << LOG2N)};

              $for M in reversed(range(MR)):
                c${M} += ${1 << LOG2N};
            $else:
              $for M in reversed(range(MR)):
                *c${M} = vacc${M}x0;
          }

      nc = 0;
    }
  } while (nc != 0);
}
