initial commit
[libm] / src / math / fma.c
1 /* origin: FreeBSD /usr/src/lib/msun/src/s_fma.c */
2 /*-
3  * Copyright (c) 2005-2011 David Schultz <das@FreeBSD.ORG>
4  * All rights reserved.
5  *
6  * Redistribution and use in source and binary forms, with or without
7  * modification, are permitted provided that the following conditions
8  * are met:
9  * 1. Redistributions of source code must retain the above copyright
10  *    notice, this list of conditions and the following disclaimer.
11  * 2. Redistributions in binary form must reproduce the above copyright
12  *    notice, this list of conditions and the following disclaimer in the
13  *    documentation and/or other materials provided with the distribution.
14  *
15  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
16  * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
17  * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
18  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
19  * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
20  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
21  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
22  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
23  * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
24  * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
25  * SUCH DAMAGE.
26  */
27
28 #include <fenv.h>
29 #include "libm.h"
30
31 /*
32  * A struct dd represents a floating-point number with twice the precision
33  * of a double.  We maintain the invariant that "hi" stores the 53 high-order
34  * bits of the result.
35  */
36 struct dd {
37         double hi;
38         double lo;
39 };
40
41 /*
42  * Compute a+b exactly, returning the exact result in a struct dd.  We assume
43  * that both a and b are finite, but make no assumptions about their relative
44  * magnitudes.
45  */
46 static inline struct dd dd_add(double a, double b)
47 {
48         struct dd ret;
49         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 double add_adjusted(double a, double b)
69 {
70         struct dd sum;
71         uint64_t hibits, lobits;
72
73         sum = dd_add(a, b);
74         if (sum.lo != 0) {
75                 EXTRACT_WORD64(hibits, sum.hi);
76                 if ((hibits & 1) == 0) {
77                         /* hibits += (int)copysign(1.0, sum.hi * sum.lo) */
78                         EXTRACT_WORD64(lobits, sum.lo);
79                         hibits += 1 - ((hibits ^ lobits) >> 62);
80                         INSERT_WORD64(sum.hi, hibits);
81                 }
82         }
83         return (sum.hi);
84 }
85
86 /*
87  * Compute ldexp(a+b, scale) with a single rounding error. It is assumed
88  * that the result will be subnormal, and care is taken to ensure that
89  * double rounding does not occur.
90  */
91 static inline double add_and_denormalize(double a, double b, int scale)
92 {
93         struct dd sum;
94         uint64_t hibits, lobits;
95         int bits_lost;
96
97         sum = dd_add(a, b);
98
99         /*
100          * If we are losing at least two bits of accuracy to denormalization,
101          * then the first lost bit becomes a round bit, and we adjust the
102          * lowest bit of sum.hi to make it a sticky bit summarizing all the
103          * bits in sum.lo. With the sticky bit adjusted, the hardware will
104          * break any ties in the correct direction.
105          *
106          * If we are losing only one bit to denormalization, however, we must
107          * break the ties manually.
108          */
109         if (sum.lo != 0) {
110                 EXTRACT_WORD64(hibits, sum.hi);
111                 bits_lost = -((int)(hibits >> 52) & 0x7ff) - scale + 1;
112                 if (bits_lost != 1 ^ (int)(hibits & 1)) {
113                         /* hibits += (int)copysign(1.0, sum.hi * sum.lo) */
114                         EXTRACT_WORD64(lobits, sum.lo);
115                         hibits += 1 - (((hibits ^ lobits) >> 62) & 2);
116                         INSERT_WORD64(sum.hi, hibits);
117                 }
118         }
119         return (ldexp(sum.hi, scale));
120 }
121
122 /*
123  * Compute a*b exactly, returning the exact result in a struct dd.  We assume
124  * that both a and b are normalized, so no underflow or overflow will occur.
125  * The current rounding mode must be round-to-nearest.
126  */
127 static inline struct dd dd_mul(double a, double b)
128 {
129         static const double split = 0x1p27 + 1.0;
130         struct dd ret;
131         double ha, hb, la, lb, p, q;
132
133         p = a * split;
134         ha = a - p;
135         ha += p;
136         la = a - ha;
137
138         p = b * split;
139         hb = b - p;
140         hb += p;
141         lb = b - hb;
142
143         p = ha * hb;
144         q = ha * lb + la * hb;
145
146         ret.hi = p + q;
147         ret.lo = p - ret.hi + q + la * lb;
148         return (ret);
149 }
150
151 /*
152  * Fused multiply-add: Compute x * y + z with a single rounding error.
153  *
154  * We use scaling to avoid overflow/underflow, along with the
155  * canonical precision-doubling technique adapted from:
156  *
157  *      Dekker, T.  A Floating-Point Technique for Extending the
158  *      Available Precision.  Numer. Math. 18, 224-242 (1971).
159  *
160  * This algorithm is sensitive to the rounding precision.  FPUs such
161  * as the i387 must be set in double-precision mode if variables are
162  * to be stored in FP registers in order to avoid incorrect results.
163  * This is the default on FreeBSD, but not on many other systems.
164  *
165  * Hardware instructions should be used on architectures that support it,
166  * since this implementation will likely be several times slower.
167  */
168 double fma(double x, double y, double z)
169 {
170         double xs, ys, zs, adj;
171         struct dd xy, r;
172         int oround;
173         int ex, ey, ez;
174         int spread;
175
176         /*
177          * Handle special cases. The order of operations and the particular
178          * return values here are crucial in handling special cases involving
179          * infinities, NaNs, overflows, and signed zeroes correctly.
180          */
181         if (x == 0.0 || y == 0.0)
182                 return (x * y + z);
183         if (z == 0.0)
184                 return (x * y);
185         if (!isfinite(x) || !isfinite(y))
186                 return (x * y + z);
187         if (!isfinite(z))
188                 return (z);
189
190         xs = frexp(x, &ex);
191         ys = frexp(y, &ey);
192         zs = frexp(z, &ez);
193         oround = fegetround();
194         spread = ex + ey - ez;
195
196         /*
197          * If x * y and z are many orders of magnitude apart, the scaling
198          * will overflow, so we handle these cases specially.  Rounding
199          * modes other than FE_TONEAREST are painful.
200          */
201         if (spread < -DBL_MANT_DIG) {
202                 feraiseexcept(FE_INEXACT);
203                 if (!isnormal(z))
204                         feraiseexcept(FE_UNDERFLOW);
205                 switch (oround) {
206                 case FE_TONEAREST:
207                         return (z);
208                 case FE_TOWARDZERO:
209                         if (x > 0.0 ^ y < 0.0 ^ z < 0.0)
210                                 return (z);
211                         else
212                                 return (nextafter(z, 0));
213                 case FE_DOWNWARD:
214                         if (x > 0.0 ^ y < 0.0)
215                                 return (z);
216                         else
217                                 return (nextafter(z, -INFINITY));
218                 default:        /* FE_UPWARD */
219                         if (x > 0.0 ^ y < 0.0)
220                                 return (nextafter(z, INFINITY));
221                         else
222                                 return (z);
223                 }
224         }
225         if (spread <= DBL_MANT_DIG * 2)
226                 zs = ldexp(zs, -spread);
227         else
228                 zs = copysign(DBL_MIN, zs);
229
230         fesetround(FE_TONEAREST);
231
232         /*
233          * Basic approach for round-to-nearest:
234          *
235          *     (xy.hi, xy.lo) = x * y           (exact)
236          *     (r.hi, r.lo)   = xy.hi + z       (exact)
237          *     adj = xy.lo + r.lo               (inexact; low bit is sticky)
238          *     result = r.hi + adj              (correctly rounded)
239          */
240         xy = dd_mul(xs, ys);
241         r = dd_add(xy.hi, zs);
242
243         spread = ex + ey;
244
245         if (r.hi == 0.0) {
246                 /*
247                  * When the addends cancel to 0, ensure that the result has
248                  * the correct sign.
249                  */
250                 fesetround(oround);
251                 volatile double vzs = zs; /* XXX gcc CSE bug workaround */
252                 return (xy.hi + vzs + ldexp(xy.lo, spread));
253         }
254
255         if (oround != FE_TONEAREST) {
256                 /*
257                  * There is no need to worry about double rounding in directed
258                  * rounding modes.
259                  */
260                 fesetround(oround);
261                 adj = r.lo + xy.lo;
262                 return (ldexp(r.hi + adj, spread));
263         }
264
265         adj = add_adjusted(r.lo, xy.lo);
266         if (spread + ilogb(r.hi) > -1023)
267                 return (ldexp(r.hi + adj, spread));
268         else
269                 return (add_and_denormalize(r.hi, adj, spread));
270 }