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 /*
31  * A struct dd represents a floating-point number with twice the precision
32  * of a long double.  We maintain the invariant that "hi" stores the high-order
33  * bits of the result.
34  */
35 struct dd {
36 	long double hi;
37 	long double lo;
38 };
39 
40 /*
41  * Compute a+b exactly, returning the exact result in a struct dd.  We assume
42  * that both a and b are finite, but make no assumptions about their relative
43  * magnitudes.
44  */
45 static inline struct dd
dd_add(long double a,long double b)46 dd_add(long double a, long double b)
47 {
48 	struct dd ret;
49 	long double s;
50 
51 	ret.hi = a + b;
52 	s = ret.hi - a;
53 	ret.lo = (a - (ret.hi - s)) + (b - s);
54 	return (ret);
55 }
56 
57 /*
58  * Compute a+b, with a small tweak:  The least significant bit of the
59  * result is adjusted into a sticky bit summarizing all the bits that
60  * were lost to rounding.  This adjustment negates the effects of double
61  * rounding when the result is added to another number with a higher
62  * exponent.  For an explanation of round and sticky bits, see any reference
63  * on FPU design, e.g.,
64  *
65  *     J. Coonen.  An Implementation Guide to a Proposed Standard for
66  *     Floating-Point Arithmetic.  Computer, vol. 13, no. 1, Jan 1980.
67  */
68 static inline long double
add_adjusted(long double a,long double b)69 add_adjusted(long double a, long double b)
70 {
71 	struct dd sum;
72 	union IEEEl2bits u;
73 
74 	sum = dd_add(a, b);
75 	if (sum.lo != 0) {
76 		u.e = sum.hi;
77 		if ((u.bits.manl & 1) == 0)
78 			sum.hi = nextafterl(sum.hi, (long double)INFINITY * sum.lo);
79 	}
80 	return (sum.hi);
81 }
82 
83 /*
84  * Compute ldexp(a+b, scale) with a single rounding error. It is assumed
85  * that the result will be subnormal, and care is taken to ensure that
86  * double rounding does not occur.
87  */
88 static inline long double
add_and_denormalize(long double a,long double b,int scale)89 add_and_denormalize(long double a, long double b, int scale)
90 {
91 	struct dd sum;
92 	int bits_lost;
93 	union IEEEl2bits u;
94 
95 	sum = dd_add(a, b);
96 
97 	/*
98 	 * If we are losing at least two bits of accuracy to denormalization,
99 	 * then the first lost bit becomes a round bit, and we adjust the
100 	 * lowest bit of sum.hi to make it a sticky bit summarizing all the
101 	 * bits in sum.lo. With the sticky bit adjusted, the hardware will
102 	 * break any ties in the correct direction.
103 	 *
104 	 * If we are losing only one bit to denormalization, however, we must
105 	 * break the ties manually.
106 	 */
107 	if (sum.lo != 0) {
108 		u.e = sum.hi;
109 		bits_lost = -u.bits.exp - scale + 1;
110 		if ((bits_lost != 1) ^ (int)(u.bits.manl & 1))
111 			sum.hi = nextafterl(sum.hi, (long double)INFINITY * sum.lo);
112 	}
113 	return (ldexpl(sum.hi, scale));
114 }
115 
116 /*
117  * Compute a*b exactly, returning the exact result in a struct dd.  We assume
118  * that both a and b are normalized, so no underflow or overflow will occur.
119  * The current rounding mode must be round-to-nearest.
120  */
121 static inline struct dd
dd_mul(long double a,long double b)122 dd_mul(long double a, long double b)
123 {
124 #if LDBL_MANT_DIG == 64
125 	static const long double split = 0x1p32L + 1.0L;
126 #elif LDBL_MANT_DIG == 113
127 	static const long double split = 0x1p57L + 1.0L;
128 #endif
129 	struct dd ret;
130 	long double ha, hb, la, lb, p, q;
131 
132 	p = a * split;
133 	ha = a - p;
134 	ha += p;
135 	la = a - ha;
136 
137 	p = b * split;
138 	hb = b - p;
139 	hb += p;
140 	lb = b - hb;
141 
142 	p = ha * hb;
143 	q = ha * lb + la * hb;
144 
145 	ret.hi = p + q;
146 	ret.lo = p - ret.hi + q + la * lb;
147 	return (ret);
148 }
149 
150 #ifdef _WANT_MATH_ERRNO
151 static long double
_scalbnl_no_errno(long double x,int n)152 _scalbnl_no_errno(long double x, int n)
153 {
154         int save_errno = errno;
155         x = scalbnl(x, n);
156         errno = save_errno;
157         return x;
158 }
159 #else
160 #define _scalbnl_no_errno(a,b) scalbnl(a,b)
161 #endif
162 
163 #ifdef __clang__
164 #pragma STDC FP_CONTRACT OFF
165 #endif
166 
167 /*
168  * Fused multiply-add: Compute x * y + z with a single rounding error.
169  *
170  * We use scaling to avoid overflow/underflow, along with the
171  * canonical precision-doubling technique adapted from:
172  *
173  *	Dekker, T.  A Floating-Point Technique for Extending the
174  *	Available Precision.  Numer. Math. 18, 224-242 (1971).
175  */
176 long double
fmal(long double x,long double y,long double z)177 fmal(long double x, long double y, long double z)
178 {
179 	long double xs, ys, zs, adj;
180 	struct dd xy, r;
181 	int oround;
182 	int ex, ey, ez;
183 	int spread;
184 
185 	/*
186 	 * Handle special cases. The order of operations and the particular
187 	 * return values here are crucial in handling special cases involving
188 	 * infinities, NaNs, overflows, and signed zeroes correctly.
189 	 */
190 	if (x == 0.0L || y == 0.0L)
191 		return (x * y + z);
192 	if (z == 0.0L)
193 		return (x * y);
194 	if (!isfinite(x) || !isfinite(y))
195 		return (x * y + z);
196 	if (!isfinite(z))
197 		return (z);
198 
199 	xs = frexpl(x, &ex);
200 	ys = frexpl(y, &ey);
201 	zs = frexpl(z, &ez);
202 	oround = fegetround();
203 	spread = ex + ey - ez;
204 
205 	/*
206 	 * If x * y and z are many orders of magnitude apart, the scaling
207 	 * will overflow, so we handle these cases specially.  Rounding
208 	 * modes other than FE_TONEAREST are painful.
209 	 */
210 	if (spread < -LDBL_MANT_DIG) {
211 #ifdef FE_INEXACT
212 		feraiseexcept(FE_INEXACT);
213 #endif
214 #ifdef FE_UNDERFLOW
215 		if (!isnormal(z))
216 			feraiseexcept(FE_UNDERFLOW);
217 #endif
218 		switch (oround) {
219 		default:
220 			return (z);
221 #ifdef FE_TOWARDZERO
222 		case FE_TOWARDZERO:
223 			if ((x > 0.0L) ^ (y < 0.0L) ^ (z < 0.0L))
224 				return (z);
225 			else
226 				return (nextafterl(z, 0));
227 #endif
228 #ifdef FE_DOWNWARD
229 		case FE_DOWNWARD:
230 			if ((x > 0.0L) ^ (y < 0.0L))
231 				return (z);
232 			else
233 				return (nextafterl(z, -(long double)INFINITY));
234 #endif
235 #ifdef FE_UPWARD
236                 case FE_UPWARD:
237 			if ((x > 0.0L) ^ (y < 0.0L))
238 				return (nextafterl(z, (long double)INFINITY));
239 			else
240 				return (z);
241 #endif
242 		}
243 	}
244 	if (spread <= LDBL_MANT_DIG * 2)
245 		zs = _scalbnl_no_errno(zs, -spread);
246 	else
247 		zs = copysignl(LDBL_MIN, zs);
248 
249 	fesetround(FE_TONEAREST);
250 
251 	/*
252 	 * Basic approach for round-to-nearest:
253 	 *
254 	 *     (xy.hi, xy.lo) = x * y		(exact)
255 	 *     (r.hi, r.lo)   = xy.hi + z	(exact)
256 	 *     adj = xy.lo + r.lo		(inexact; low bit is sticky)
257 	 *     result = r.hi + adj		(correctly rounded)
258 	 */
259 	xy = dd_mul(xs, ys);
260 	r = dd_add(xy.hi, zs);
261 
262 	spread = ex + ey;
263 
264 	if (r.hi == 0.0L) {
265 		/*
266 		 * When the addends cancel to 0, ensure that the result has
267 		 * the correct sign.
268 		 */
269 		fesetround(oround);
270 		volatile long double vzs = zs; /* XXX gcc CSE bug workaround */
271 		return (xy.hi + vzs + _scalbnl_no_errno(xy.lo, spread));
272 	}
273 
274 	if (oround != FE_TONEAREST) {
275 		/*
276 		 * There is no need to worry about double rounding in directed
277 		 * rounding modes.
278 		 */
279 		fesetround(oround);
280 		adj = r.lo + xy.lo;
281 		return (_scalbnl_no_errno(r.hi + adj, spread));
282 	}
283 
284 	adj = add_adjusted(r.lo, xy.lo);
285 	if (spread + ilogbl(r.hi) > -16383)
286 		return (_scalbnl_no_errno(r.hi + adj, spread));
287 	else
288 		return (add_and_denormalize(r.hi, adj, spread));
289 }
290