xref: /netbsd-src/sys/arch/m68k/fpe/fpu_sqrt.c (revision f648d12d47727113ad5330b0753bb2f2ef8e1045)
1 /*	$NetBSD: fpu_sqrt.c,v 1.4 2003/08/07 16:28:12 agc Exp $ */
2 
3 /*
4  * Copyright (c) 1992, 1993
5  *	The Regents of the University of California.  All rights reserved.
6  *
7  * This software was developed by the Computer Systems Engineering group
8  * at Lawrence Berkeley Laboratory under DARPA contract BG 91-66 and
9  * contributed to Berkeley.
10  *
11  * All advertising materials mentioning features or use of this software
12  * must display the following acknowledgement:
13  *	This product includes software developed by the University of
14  *	California, Lawrence Berkeley Laboratory.
15  *
16  * Redistribution and use in source and binary forms, with or without
17  * modification, are permitted provided that the following conditions
18  * are met:
19  * 1. Redistributions of source code must retain the above copyright
20  *    notice, this list of conditions and the following disclaimer.
21  * 2. Redistributions in binary form must reproduce the above copyright
22  *    notice, this list of conditions and the following disclaimer in the
23  *    documentation and/or other materials provided with the distribution.
24  * 3. Neither the name of the University nor the names of its contributors
25  *    may be used to endorse or promote products derived from this software
26  *    without specific prior written permission.
27  *
28  * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
29  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
30  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
31  * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
32  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
33  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
34  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
35  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
36  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
37  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
38  * SUCH DAMAGE.
39  *
40  *	@(#)fpu_sqrt.c	8.1 (Berkeley) 6/11/93
41  */
42 
43 /*
44  * Perform an FPU square root (return sqrt(x)).
45  */
46 
47 #include <sys/cdefs.h>
48 __KERNEL_RCSID(0, "$NetBSD: fpu_sqrt.c,v 1.4 2003/08/07 16:28:12 agc Exp $");
49 
50 #include <sys/types.h>
51 
52 #include <machine/reg.h>
53 
54 #include "fpu_arith.h"
55 #include "fpu_emulate.h"
56 
57 /*
58  * Our task is to calculate the square root of a floating point number x0.
59  * This number x normally has the form:
60  *
61  *		    exp
62  *	x = mant * 2		(where 1 <= mant < 2 and exp is an integer)
63  *
64  * This can be left as it stands, or the mantissa can be doubled and the
65  * exponent decremented:
66  *
67  *			  exp-1
68  *	x = (2 * mant) * 2	(where 2 <= 2 * mant < 4)
69  *
70  * If the exponent `exp' is even, the square root of the number is best
71  * handled using the first form, and is by definition equal to:
72  *
73  *				exp/2
74  *	sqrt(x) = sqrt(mant) * 2
75  *
76  * If exp is odd, on the other hand, it is convenient to use the second
77  * form, giving:
78  *
79  *				    (exp-1)/2
80  *	sqrt(x) = sqrt(2 * mant) * 2
81  *
82  * In the first case, we have
83  *
84  *	1 <= mant < 2
85  *
86  * and therefore
87  *
88  *	sqrt(1) <= sqrt(mant) < sqrt(2)
89  *
90  * while in the second case we have
91  *
92  *	2 <= 2*mant < 4
93  *
94  * and therefore
95  *
96  *	sqrt(2) <= sqrt(2*mant) < sqrt(4)
97  *
98  * so that in any case, we are sure that
99  *
100  *	sqrt(1) <= sqrt(n * mant) < sqrt(4),	n = 1 or 2
101  *
102  * or
103  *
104  *	1 <= sqrt(n * mant) < 2,		n = 1 or 2.
105  *
106  * This root is therefore a properly formed mantissa for a floating
107  * point number.  The exponent of sqrt(x) is either exp/2 or (exp-1)/2
108  * as above.  This leaves us with the problem of finding the square root
109  * of a fixed-point number in the range [1..4).
110  *
111  * Though it may not be instantly obvious, the following square root
112  * algorithm works for any integer x of an even number of bits, provided
113  * that no overflows occur:
114  *
115  *	let q = 0
116  *	for k = NBITS-1 to 0 step -1 do -- for each digit in the answer...
117  *		x *= 2			-- multiply by radix, for next digit
118  *		if x >= 2q + 2^k then	-- if adding 2^k does not
119  *			x -= 2q + 2^k	-- exceed the correct root,
120  *			q += 2^k	-- add 2^k and adjust x
121  *		fi
122  *	done
123  *	sqrt = q / 2^(NBITS/2)		-- (and any remainder is in x)
124  *
125  * If NBITS is odd (so that k is initially even), we can just add another
126  * zero bit at the top of x.  Doing so means that q is not going to acquire
127  * a 1 bit in the first trip around the loop (since x0 < 2^NBITS).  If the
128  * final value in x is not needed, or can be off by a factor of 2, this is
129  * equivalant to moving the `x *= 2' step to the bottom of the loop:
130  *
131  *	for k = NBITS-1 to 0 step -1 do if ... fi; x *= 2; done
132  *
133  * and the result q will then be sqrt(x0) * 2^floor(NBITS / 2).
134  * (Since the algorithm is destructive on x, we will call x's initial
135  * value, for which q is some power of two times its square root, x0.)
136  *
137  * If we insert a loop invariant y = 2q, we can then rewrite this using
138  * C notation as:
139  *
140  *	q = y = 0; x = x0;
141  *	for (k = NBITS; --k >= 0;) {
142  * #if (NBITS is even)
143  *		x *= 2;
144  * #endif
145  *		t = y + (1 << k);
146  *		if (x >= t) {
147  *			x -= t;
148  *			q += 1 << k;
149  *			y += 1 << (k + 1);
150  *		}
151  * #if (NBITS is odd)
152  *		x *= 2;
153  * #endif
154  *	}
155  *
156  * If x0 is fixed point, rather than an integer, we can simply alter the
157  * scale factor between q and sqrt(x0).  As it happens, we can easily arrange
158  * for the scale factor to be 2**0 or 1, so that sqrt(x0) == q.
159  *
160  * In our case, however, x0 (and therefore x, y, q, and t) are multiword
161  * integers, which adds some complication.  But note that q is built one
162  * bit at a time, from the top down, and is not used itself in the loop
163  * (we use 2q as held in y instead).  This means we can build our answer
164  * in an integer, one word at a time, which saves a bit of work.  Also,
165  * since 1 << k is always a `new' bit in q, 1 << k and 1 << (k+1) are
166  * `new' bits in y and we can set them with an `or' operation rather than
167  * a full-blown multiword add.
168  *
169  * We are almost done, except for one snag.  We must prove that none of our
170  * intermediate calculations can overflow.  We know that x0 is in [1..4)
171  * and therefore the square root in q will be in [1..2), but what about x,
172  * y, and t?
173  *
174  * We know that y = 2q at the beginning of each loop.  (The relation only
175  * fails temporarily while y and q are being updated.)  Since q < 2, y < 4.
176  * The sum in t can, in our case, be as much as y+(1<<1) = y+2 < 6, and.
177  * Furthermore, we can prove with a bit of work that x never exceeds y by
178  * more than 2, so that even after doubling, 0 <= x < 8.  (This is left as
179  * an exercise to the reader, mostly because I have become tired of working
180  * on this comment.)
181  *
182  * If our floating point mantissas (which are of the form 1.frac) occupy
183  * B+1 bits, our largest intermediary needs at most B+3 bits, or two extra.
184  * In fact, we want even one more bit (for a carry, to avoid compares), or
185  * three extra.  There is a comment in fpu_emu.h reminding maintainers of
186  * this, so we have some justification in assuming it.
187  */
188 struct fpn *
189 fpu_sqrt(fe)
190 	struct fpemu *fe;
191 {
192 	register struct fpn *x = &fe->fe_f2;
193 	register u_int bit, q, tt;
194 	register u_int x0, x1, x2;
195 	register u_int y0, y1, y2;
196 	register u_int d0, d1, d2;
197 	register int e;
198 	FPU_DECL_CARRY
199 
200 	/*
201 	 * Take care of special cases first.  In order:
202 	 *
203 	 *	sqrt(NaN) = NaN
204 	 *	sqrt(+0) = +0
205 	 *	sqrt(-0) = -0
206 	 *	sqrt(x < 0) = NaN	(including sqrt(-Inf))
207 	 *	sqrt(+Inf) = +Inf
208 	 *
209 	 * Then all that remains are numbers with mantissas in [1..2).
210 	 */
211 	if (ISNAN(x) || ISZERO(x))
212 		return (x);
213 	if (x->fp_sign)
214 		return (fpu_newnan(fe));
215 	if (ISINF(x))
216 		return (x);
217 
218 	/*
219 	 * Calculate result exponent.  As noted above, this may involve
220 	 * doubling the mantissa.  We will also need to double x each
221 	 * time around the loop, so we define a macro for this here, and
222 	 * we break out the multiword mantissa.
223 	 */
224 #ifdef FPU_SHL1_BY_ADD
225 #define	DOUBLE_X { \
226 	FPU_ADDS(x2, x2, x2); \
227 	FPU_ADDCS(x1, x1, x1); FPU_ADDC(x0, x0, x0); \
228 }
229 #else
230 #define	DOUBLE_X { \
231 	x0 = (x0 << 1) | (x1 >> 31); x1 = (x1 << 1) | (x2 >> 31); \
232 	x2 <<= 1; \
233 }
234 #endif
235 #if (FP_NMANT & 1) != 0
236 # define ODD_DOUBLE	DOUBLE_X
237 # define EVEN_DOUBLE	/* nothing */
238 #else
239 # define ODD_DOUBLE	/* nothing */
240 # define EVEN_DOUBLE	DOUBLE_X
241 #endif
242 	x0 = x->fp_mant[0];
243 	x1 = x->fp_mant[1];
244 	x2 = x->fp_mant[2];
245 	e = x->fp_exp;
246 	if (e & 1)		/* exponent is odd; use sqrt(2mant) */
247 		DOUBLE_X;
248 	/* THE FOLLOWING ASSUMES THAT RIGHT SHIFT DOES SIGN EXTENSION */
249 	x->fp_exp = e >> 1;	/* calculates (e&1 ? (e-1)/2 : e/2 */
250 
251 	/*
252 	 * Now calculate the mantissa root.  Since x is now in [1..4),
253 	 * we know that the first trip around the loop will definitely
254 	 * set the top bit in q, so we can do that manually and start
255 	 * the loop at the next bit down instead.  We must be sure to
256 	 * double x correctly while doing the `known q=1.0'.
257 	 *
258 	 * We do this one mantissa-word at a time, as noted above, to
259 	 * save work.  To avoid `(1 << 31) << 1', we also do the top bit
260 	 * outside of each per-word loop.
261 	 *
262 	 * The calculation `t = y + bit' breaks down into `t0 = y0, ...,
263 	 * t2 = y2, t? |= bit' for the appropriate word.  Since the bit
264 	 * is always a `new' one, this means that three of the `t?'s are
265 	 * just the corresponding `y?'; we use `#define's here for this.
266 	 * The variable `tt' holds the actual `t?' variable.
267 	 */
268 
269 	/* calculate q0 */
270 #define	t0 tt
271 	bit = FP_1;
272 	EVEN_DOUBLE;
273 	/* if (x >= (t0 = y0 | bit)) { */	/* always true */
274 		q = bit;
275 		x0 -= bit;
276 		y0 = bit << 1;
277 	/* } */
278 	ODD_DOUBLE;
279 	while ((bit >>= 1) != 0) {	/* for remaining bits in q0 */
280 		EVEN_DOUBLE;
281 		t0 = y0 | bit;		/* t = y + bit */
282 		if (x0 >= t0) {		/* if x >= t then */
283 			x0 -= t0;	/*	x -= t */
284 			q |= bit;	/*	q += bit */
285 			y0 |= bit << 1;	/*	y += bit << 1 */
286 		}
287 		ODD_DOUBLE;
288 	}
289 	x->fp_mant[0] = q;
290 #undef t0
291 
292 	/* calculate q1.  note (y0&1)==0. */
293 #define t0 y0
294 #define t1 tt
295 	q = 0;
296 	y1 = 0;
297 	bit = 1 << 31;
298 	EVEN_DOUBLE;
299 	t1 = bit;
300 	FPU_SUBS(d1, x1, t1);
301 	FPU_SUBC(d0, x0, t0);		/* d = x - t */
302 	if ((int)d0 >= 0) {		/* if d >= 0 (i.e., x >= t) then */
303 		x0 = d0, x1 = d1;	/*	x -= t */
304 		q = bit;		/*	q += bit */
305 		y0 |= 1;		/*	y += bit << 1 */
306 	}
307 	ODD_DOUBLE;
308 	while ((bit >>= 1) != 0) {	/* for remaining bits in q1 */
309 		EVEN_DOUBLE;		/* as before */
310 		t1 = y1 | bit;
311 		FPU_SUBS(d1, x1, t1);
312 		FPU_SUBC(d0, x0, t0);
313 		if ((int)d0 >= 0) {
314 			x0 = d0, x1 = d1;
315 			q |= bit;
316 			y1 |= bit << 1;
317 		}
318 		ODD_DOUBLE;
319 	}
320 	x->fp_mant[1] = q;
321 #undef t1
322 
323 	/* calculate q2.  note (y1&1)==0; y0 (aka t0) is fixed. */
324 #define t1 y1
325 #define t2 tt
326 	q = 0;
327 	y2 = 0;
328 	bit = 1 << 31;
329 	EVEN_DOUBLE;
330 	t2 = bit;
331 	FPU_SUBS(d2, x2, t2);
332 	FPU_SUBCS(d1, x1, t1);
333 	FPU_SUBC(d0, x0, t0);
334 	if ((int)d0 >= 0) {
335 		x0 = d0, x1 = d1, x2 = d2;
336 		q |= bit;
337 		y1 |= 1;		/* now t1, y1 are set in concrete */
338 	}
339 	ODD_DOUBLE;
340 	while ((bit >>= 1) != 0) {
341 		EVEN_DOUBLE;
342 		t2 = y2 | bit;
343 		FPU_SUBS(d2, x2, t2);
344 		FPU_SUBCS(d1, x1, t1);
345 		FPU_SUBC(d0, x0, t0);
346 		if ((int)d0 >= 0) {
347 			x0 = d0, x1 = d1, x2 = d2;
348 			q |= bit;
349 			y2 |= bit << 1;
350 		}
351 		ODD_DOUBLE;
352 	}
353 	x->fp_mant[2] = q;
354 #undef t2
355 
356 	/*
357 	 * The result, which includes guard and round bits, is exact iff
358 	 * x is now zero; any nonzero bits in x represent sticky bits.
359 	 */
360 	x->fp_sticky = x0 | x1 | x2;
361 	return (x);
362 }
363