1// Copyright 2020 Google LLC 2// 3// This source code is licensed under the BSD-style license found in the 4// LICENSE file in the root directory of this source tree. 5 6$assert BATCH_TILE % 8 == 0 7$assert BATCH_TILE >= 8 8$ABC = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ" 9#include <assert.h> 10 11#include <immintrin.h> 12 13#include <xnnpack/clamp.h> 14#include <xnnpack/common.h> 15 16 17static const int32_t mask_table[14] = {-1, -1, -1, -1, -1, -1, -1, 0, 0, 0, 0, 0, 0, 0}; 18 19void xnn_f32_clamp_ukernel__avx_x${BATCH_TILE}( 20 size_t n, 21 const float* x, 22 float* y, 23 const union xnn_f32_minmax_params params[restrict XNN_MIN_ELEMENTS(1)]) 24{ 25 assert(n != 0); 26 assert(n % sizeof(float) == 0); 27 assert(x != NULL); 28 assert(y != NULL); 29 30 const __m256 vy_min = _mm256_broadcast_ps((const __m128*) params->sse.min); 31 const __m256 vy_max = _mm256_broadcast_ps((const __m128*) params->sse.max); 32 33 for (; n >= ${BATCH_TILE} * sizeof(float); n -= ${BATCH_TILE} * sizeof(float)) { 34 __m256 vacc${ABC[0:8]} = _mm256_loadu_ps(x); 35 $for N in range(8, BATCH_TILE, 8): 36 __m256 vacc${ABC[N:N+8]} = _mm256_loadu_ps(x + ${N}); 37 x += ${BATCH_TILE}; 38 39 $for N in range(0, BATCH_TILE, 8): 40 vacc${ABC[N:N+8]} = _mm256_max_ps(vacc${ABC[N:N+8]}, vy_min); 41 42 $for N in range(0, BATCH_TILE, 8): 43 vacc${ABC[N:N+8]} = _mm256_min_ps(vacc${ABC[N:N+8]}, vy_max); 44 45 _mm256_storeu_ps(y, vacc${ABC[0:8]}); 46 $for N in range(8, BATCH_TILE, 8): 47 _mm256_storeu_ps(y + ${N}, vacc${ABC[N:N+8]}); 48 y += ${BATCH_TILE}; 49 } 50 $if BATCH_TILE > 8: 51 for (; n >= 8 * sizeof(float); n -= 8 * sizeof(float)) { 52 __m256 vacc = _mm256_loadu_ps(x); 53 x += 8; 54 55 vacc = _mm256_max_ps(vacc, vy_min); 56 vacc = _mm256_min_ps(vacc, vy_max); 57 58 _mm256_storeu_ps(y, vacc); 59 y += 8; 60 } 61 if XNN_UNLIKELY(n != 0) { 62 assert(n >= 1 * sizeof(float)); 63 assert(n <= 7 * sizeof(float)); 64 __m256i vmask = _mm256_loadu_si256((const __m256i*) ((uintptr_t) &mask_table[7] - n)); 65 66 __m256 vacc = _mm256_maskload_ps(x, vmask); 67 vacc = _mm256_max_ps(vacc, vy_min); 68 vacc = _mm256_min_ps(vacc, vy_max); 69 70 // _mm256_maskstore_ps(y, vmask, vacc) could be used here, but triggers msan failures (probably an msan bug). 71 __m128 vacc_lo = _mm256_castps256_ps128(vacc); 72 if (n & (4 * sizeof(float))) { 73 _mm_storeu_ps(y, vacc_lo); 74 vacc_lo = _mm256_extractf128_ps(vacc, 1); 75 y += 4; 76 } 77 if (n & (2 * sizeof(float))) { 78 _mm_storel_pi((__m64*) y, vacc_lo); 79 vacc_lo = _mm_movehl_ps(vacc_lo, vacc_lo); 80 y += 2; 81 } 82 if (n & (1 * sizeof(float))) { 83 _mm_store_ss(y, vacc_lo); 84 } 85 } 86} 87