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 #include <assert.h>
7 #include <stddef.h>
8
9 #include <arm_neon.h>
10
11 #include <xnnpack/math.h>
12 #include <xnnpack/math-stubs.h>
13
14
xnn_math_f32_sqrt__neonfma_nr1rsqrts1fma1adj(size_t n,const float * input,float * output)15 void xnn_math_f32_sqrt__neonfma_nr1rsqrts1fma1adj(
16 size_t n,
17 const float* input,
18 float* output)
19 {
20 assert(n % (4 * sizeof(float)) == 0);
21
22 const float32x4_t vhalf = vmovq_n_f32(0.5f);
23 for (; n != 0; n -= 4 * sizeof(float)) {
24 const float32x4_t vx = vld1q_f32(input); input += 4;
25
26 // Initial approximation
27 float32x4_t vrsqrtx = vrsqrteq_f32(vx);
28
29 // Netwon-Raphson iteration: rsqrt_x <- rsqrt_x * ((3 - x * (rsqrt_x * rsqrt_x)) / 2)
30 // Note: vrsqrtsq_f32(x, y) := (3 - x * y) / 2
31 vrsqrtx = vmulq_f32(vrsqrtx, vrsqrtsq_f32(vx, vmulq_f32(vrsqrtx, vrsqrtx)));
32
33 float32x4_t vsqrtx = vmulq_f32(vrsqrtx, vx);
34 float32x4_t vhalfrsqrtx = vmulq_f32(vrsqrtx, vhalf);
35
36 // Netwon-Raphson iteration:
37 // residual <- 0.5 - sqrtx * halfrsqrtx
38 // halfrsqrtx <- halfrsqrtx + halfrsqrtx * residual
39 // sqrtx <- sqrtx + sqrtx * residual
40 float32x4_t vresidual = vfmsq_f32(vhalf, vsqrtx, vhalfrsqrtx);
41 vhalfrsqrtx = vfmaq_f32(vhalfrsqrtx, vresidual, vhalfrsqrtx);
42 vsqrtx = vfmaq_f32(vsqrtx, vresidual, vsqrtx);
43
44 // Final adjustment:
45 // adjustment <- x - sqrtx * sqrtx
46 // sqrtx <- sqrtx + halfrsqrtx * adjustment
47 const float32x4_t vadjustment = vfmsq_f32(vx, vsqrtx, vsqrtx);
48 vsqrtx = vfmaq_f32(vsqrtx, vhalfrsqrtx, vadjustment);
49
50 const float32x4_t vy = vsqrtx;
51
52 vst1q_f32(output, vy); output += 4;
53 }
54 }
55