1 /*-
2  * Copyright (c) 2005-2011 David Schultz <das@FreeBSD.ORG>
3  * All rights reserved.
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted provided that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
15  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
16  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
18  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
22  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
23  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
24  * SUCH DAMAGE.
25  */
26 
27 //__FBSDID("$FreeBSD: src/lib/msun/src/s_fmal.c,v 1.7 2011/10/21 06:30:43 das Exp $");
28 
29 /*
30  * Denorms usually have an exponent biased by 1 so that they flow
31  * smoothly into the smallest normal value with an exponent of
32  * 1. However, m68k 80-bit long doubles includes exponent of zero for
33  * normal values, so denorms use the same value, eliminating the
34  * bias. That is set in s_fmal.c.
35  */
36 
37 #ifndef FLOAT_DENORM_BIAS
38 #define FLOAT_DENORM_BIAS   1
39 #endif
40 
41 /*
42  * A struct dd represents a floating-point number with twice the precision
43  * of a FLOAT_T.  We maintain the invariant that "hi" stores the high-order
44  * bits of the result.
45  */
46 struct dd {
47 	FLOAT_T hi;
48 	FLOAT_T lo;
49 };
50 
51 /*
52  * Compute a+b exactly, returning the exact result in a struct dd.  We assume
53  * that both a and b are finite, but make no assumptions about their relative
54  * magnitudes.
55  */
56 static inline struct dd
dd_add(FLOAT_T a,FLOAT_T b)57 dd_add(FLOAT_T a, FLOAT_T b)
58 {
59 	struct dd ret;
60 	FLOAT_T s;
61 
62 	ret.hi = a + b;
63 	s = ret.hi - a;
64 	ret.lo = (a - (ret.hi - s)) + (b - s);
65 	return (ret);
66 }
67 
68 /*
69  * Compute a+b, with a small tweak:  The least significant bit of the
70  * result is adjusted into a sticky bit summarizing all the bits that
71  * were lost to rounding.  This adjustment negates the effects of double
72  * rounding when the result is added to another number with a higher
73  * exponent.  For an explanation of round and sticky bits, see any reference
74  * on FPU design, e.g.,
75  *
76  *     J. Coonen.  An Implementation Guide to a Proposed Standard for
77  *     Floating-Point Arithmetic.  Computer, vol. 13, no. 1, Jan 1980.
78  */
79 static inline FLOAT_T
add_adjusted(FLOAT_T a,FLOAT_T b)80 add_adjusted(FLOAT_T a, FLOAT_T b)
81 {
82 	struct dd sum;
83 
84 	sum = dd_add(a, b);
85 	if (sum.lo != 0) {
86 		if (!odd_mant(sum.hi))
87 			sum.hi = NEXTAFTER(sum.hi, (FLOAT_T)INFINITY * sum.lo);
88 	}
89 	return (sum.hi);
90 }
91 
92 /*
93  * Compute ldexp(a+b, scale) with a single rounding error. It is assumed
94  * that the result will be subnormal, and care is taken to ensure that
95  * double rounding does not occur.
96  */
97 static inline FLOAT_T
add_and_denormalize(FLOAT_T a,FLOAT_T b,int scale)98 add_and_denormalize(FLOAT_T a, FLOAT_T b, int scale)
99 {
100 	struct dd sum;
101 	int bits_lost;
102 
103 	sum = dd_add(a, b);
104 
105 	/*
106 	 * If we are losing at least two bits of accuracy to denormalization,
107 	 * then the first lost bit becomes a round bit, and we adjust the
108 	 * lowest bit of sum.hi to make it a sticky bit summarizing all the
109 	 * bits in sum.lo. With the sticky bit adjusted, the hardware will
110 	 * break any ties in the correct direction.
111 	 *
112 	 * If we are losing only one bit to denormalization, however, we must
113 	 * break the ties manually.
114 	 */
115 	if (sum.lo != 0) {
116 		bits_lost = -EXPONENT(sum.hi) - scale + FLOAT_DENORM_BIAS;
117 		if ((bits_lost != 1) ^ (int)odd_mant(sum.hi))
118                         sum.hi = NEXTAFTER(sum.hi, (FLOAT_T)INFINITY * sum.lo);
119 	}
120 	return (LDEXP(sum.hi, scale));
121 }
122 
123 /*
124  * Compute a*b exactly, returning the exact result in a struct dd.  We assume
125  * that both a and b are normalized, so no underflow or overflow will occur.
126  * The current rounding mode must be round-to-nearest.
127  */
128 static inline struct dd
dd_mul(FLOAT_T a,FLOAT_T b)129 dd_mul(FLOAT_T a, FLOAT_T b)
130 {
131 	static const FLOAT_T split = SPLIT;
132 	struct dd ret;
133 	FLOAT_T ha, hb, la, lb, p, q;
134 
135 	p = a * split;
136 	ha = a - p;
137 	ha += p;
138 	la = a - ha;
139 
140 	p = b * split;
141 	hb = b - p;
142 	hb += p;
143 	lb = b - hb;
144 
145 	p = ha * hb;
146 	q = ha * lb + la * hb;
147 
148 	ret.hi = p + q;
149 	ret.lo = p - ret.hi + q + la * lb;
150 	return (ret);
151 }
152 
153 #ifdef _WANT_MATH_ERRNO
154 static FLOAT_T
_scalbn_no_errno(FLOAT_T x,int n)155 _scalbn_no_errno(FLOAT_T x, int n)
156 {
157         int save_errno = errno;
158         x = SCALBN(x, n);
159         errno = save_errno;
160         return x;
161 }
162 #else
163 #define _scalbn_no_errno(a,b) SCALBN(a,b)
164 #endif
165 
166 #ifdef __clang__
167 #pragma STDC FP_CONTRACT OFF
168 #endif
169 
170 #if defined(FE_UPWARD) || defined(FE_DOWNWARD) || defined(FE_TOWARDZERO)
171 #define HAS_ROUNDING
172 #endif
173 
174 /*
175  * Fused multiply-add: Compute x * y + z with a single rounding error.
176  *
177  * We use scaling to avoid overflow/underflow, along with the
178  * canonical precision-doubling technique adapted from:
179  *
180  *	Dekker, T.  A Floating-Point Technique for Extending the
181  *	Available Precision.  Numer. Math. 18, 224-242 (1971).
182  */
183 FLOAT_T
FMA(FLOAT_T x,FLOAT_T y,FLOAT_T z)184 FMA(FLOAT_T x, FLOAT_T y, FLOAT_T z)
185 {
186 	FLOAT_T xs, ys, zs, adj;
187 	struct dd xy, r;
188 	int ex, ey, ez;
189 	int spread;
190 
191 	/*
192 	 * Handle special cases. The order of operations and the particular
193 	 * return values here are crucial in handling special cases involving
194 	 * infinities, NaNs, overflows, and signed zeroes correctly.
195 	 */
196         if (!isfinite(z) && isfinite(x) && isfinite(y))
197                 return z + z;
198 	if (!isfinite(x) || !isfinite(y) || !isfinite(z))
199 		return (x * y + z);
200 	if (x == (FLOAT_T) 0.0 || y == (FLOAT_T) 0.0)
201 		return (x * y + z);
202 	if (z == (FLOAT_T) 0.0)
203 		return (x * y);
204 
205 	xs = FREXP(x, &ex);
206 	ys = FREXP(y, &ey);
207 	zs = FREXP(z, &ez);
208 #ifdef HAS_ROUNDING
209 	int oround = fegetround();
210 #endif
211 	spread = ex + ey - ez;
212 
213 	/*
214 	 * If x * y and z are many orders of magnitude apart, the scaling
215 	 * will overflow, so we handle these cases specially.  Rounding
216 	 * modes other than FE_TONEAREST are painful.
217 	 */
218 	if (spread < -FLOAT_MANT_DIG) {
219 #ifdef FE_INEXACT
220 		feraiseexcept(FE_INEXACT);
221 #endif
222 #ifdef FE_UNDERFLOW
223 		if (!isnormal(z))
224 			feraiseexcept(FE_UNDERFLOW);
225 #endif
226 #ifdef HAS_ROUNDING
227 		switch (oround) {
228 		default:
229                         break;
230 #ifdef FE_TOWARDZERO
231 		case FE_TOWARDZERO:
232 			if ((x > (FLOAT_T) 0.0) ^ (y < (FLOAT_T) 0.0) ^ (z < (FLOAT_T) 0.0))
233 				break;
234 			else
235 				return (NEXTAFTER(z, 0));
236 #endif
237 #ifdef FE_DOWNWARD
238 		case FE_DOWNWARD:
239 			if ((x > (FLOAT_T) 0.0) ^ (y < (FLOAT_T) 0.0))
240 				break;
241 			else
242 				return (NEXTAFTER(z, -(FLOAT_T)INFINITY));
243 #endif
244 #ifdef FE_UPWARD
245                 case FE_UPWARD:
246 			if ((x > (FLOAT_T) 0.0) ^ (y < (FLOAT_T) 0.0))
247 				return (NEXTAFTER(z, (FLOAT_T)INFINITY));
248                         break;
249 #endif
250 		}
251 #endif
252                 return (z);
253 	}
254 	if (spread <= FLOAT_MANT_DIG * 2)
255 		zs = _scalbn_no_errno(zs, -spread);
256 	else
257 		zs = COPYSIGN(FLOAT_MIN, zs);
258 
259 #ifdef HAS_ROUNDING
260 	fesetround(FE_TONEAREST);
261 #endif
262 
263 	/*
264 	 * Basic approach for round-to-nearest:
265 	 *
266 	 *     (xy.hi, xy.lo) = x * y		(exact)
267 	 *     (r.hi, r.lo)   = xy.hi + z	(exact)
268 	 *     adj = xy.lo + r.lo		(inexact; low bit is sticky)
269 	 *     result = r.hi + adj		(correctly rounded)
270 	 */
271 	xy = dd_mul(xs, ys);
272 	r = dd_add(xy.hi, zs);
273 
274 	spread = ex + ey;
275 
276 	if (r.hi == (FLOAT_T) 0.0) {
277 		/*
278 		 * When the addends cancel to 0, ensure that the result has
279 		 * the correct sign.
280 		 */
281 #ifdef HAS_ROUNDING
282 		fesetround(oround);
283 #endif
284 		volatile FLOAT_T vzs = zs; /* XXX gcc CSE bug workaround */
285 		return (xy.hi + vzs + _scalbn_no_errno(xy.lo, spread));
286 	}
287 
288 #ifdef HAS_ROUNDING
289 	if (oround != FE_TONEAREST) {
290 		/*
291 		 * There is no need to worry about double rounding in directed
292 		 * rounding modes.
293 		 */
294 		fesetround(oround);
295 		adj = r.lo + xy.lo;
296 		return (_scalbn_no_errno(r.hi + adj, spread));
297 	}
298 #endif
299 
300 	adj = add_adjusted(r.lo, xy.lo);
301 	if (spread + ILOGB(r.hi) > -(FLOAT_MAX_EXP - FLOAT_DENORM_BIAS))
302 		return (_scalbn_no_errno(r.hi + adj, spread));
303 	else
304 		return (add_and_denormalize(r.hi, adj, spread));
305 }
306