fma.c 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460
  1. #include <fenv.h>
  2. #include "libm.h"
  3. #if LDBL_MANT_DIG==64 && LDBL_MAX_EXP==16384
  4. /* exact add, assumes exponent_x >= exponent_y */
  5. static void add(long double *hi, long double *lo, long double x, long double y)
  6. {
  7. long double r;
  8. r = x + y;
  9. *hi = r;
  10. r -= x;
  11. *lo = y - r;
  12. }
  13. /* exact mul, assumes no over/underflow */
  14. static void mul(long double *hi, long double *lo, long double x, long double y)
  15. {
  16. static const long double c = 1.0 + 0x1p32L;
  17. long double cx, xh, xl, cy, yh, yl;
  18. cx = c*x;
  19. xh = (x - cx) + cx;
  20. xl = x - xh;
  21. cy = c*y;
  22. yh = (y - cy) + cy;
  23. yl = y - yh;
  24. *hi = x*y;
  25. *lo = (xh*yh - *hi) + xh*yl + xl*yh + xl*yl;
  26. }
  27. /*
  28. assume (long double)(hi+lo) == hi
  29. return an adjusted hi so that rounding it to double (or less) precision is correct
  30. */
  31. static long double adjust(long double hi, long double lo)
  32. {
  33. union ldshape uhi, ulo;
  34. if (lo == 0)
  35. return hi;
  36. uhi.f = hi;
  37. if (uhi.i.m & 0x3ff)
  38. return hi;
  39. ulo.f = lo;
  40. if ((uhi.i.se & 0x8000) == (ulo.i.se & 0x8000))
  41. uhi.i.m++;
  42. else {
  43. /* handle underflow and take care of ld80 implicit msb */
  44. if (uhi.i.m << 1 == 0) {
  45. uhi.i.m = 0;
  46. uhi.i.se--;
  47. }
  48. uhi.i.m--;
  49. }
  50. return uhi.f;
  51. }
  52. /* adjusted add so the result is correct when rounded to double (or less) precision */
  53. static long double dadd(long double x, long double y)
  54. {
  55. add(&x, &y, x, y);
  56. return adjust(x, y);
  57. }
  58. /* adjusted mul so the result is correct when rounded to double (or less) precision */
  59. static long double dmul(long double x, long double y)
  60. {
  61. mul(&x, &y, x, y);
  62. return adjust(x, y);
  63. }
  64. static int getexp(long double x)
  65. {
  66. union ldshape u;
  67. u.f = x;
  68. return u.i.se & 0x7fff;
  69. }
  70. double fma(double x, double y, double z)
  71. {
  72. #pragma STDC FENV_ACCESS ON
  73. long double hi, lo1, lo2, xy;
  74. int round, ez, exy;
  75. /* handle +-inf,nan */
  76. if (!isfinite(x) || !isfinite(y))
  77. return x*y + z;
  78. if (!isfinite(z))
  79. return z;
  80. /* handle +-0 */
  81. if (x == 0.0 || y == 0.0)
  82. return x*y + z;
  83. round = fegetround();
  84. if (z == 0.0) {
  85. if (round == FE_TONEAREST)
  86. return dmul(x, y);
  87. return x*y;
  88. }
  89. /* exact mul and add require nearest rounding */
  90. /* spurious inexact exceptions may be raised */
  91. fesetround(FE_TONEAREST);
  92. mul(&xy, &lo1, x, y);
  93. exy = getexp(xy);
  94. ez = getexp(z);
  95. if (ez > exy) {
  96. add(&hi, &lo2, z, xy);
  97. } else if (ez > exy - 12) {
  98. add(&hi, &lo2, xy, z);
  99. if (hi == 0) {
  100. /*
  101. xy + z is 0, but it should be calculated with the
  102. original rounding mode so the sign is correct, if the
  103. compiler does not support FENV_ACCESS ON it does not
  104. know about the changed rounding mode and eliminates
  105. the xy + z below without the volatile memory access
  106. */
  107. volatile double z_;
  108. fesetround(round);
  109. z_ = z;
  110. return (xy + z_) + lo1;
  111. }
  112. } else {
  113. /*
  114. ez <= exy - 12
  115. the 12 extra bits (1guard, 11round+sticky) are needed so with
  116. lo = dadd(lo1, lo2)
  117. elo <= ehi - 11, and we use the last 10 bits in adjust so
  118. dadd(hi, lo)
  119. gives correct result when rounded to double
  120. */
  121. hi = xy;
  122. lo2 = z;
  123. }
  124. /*
  125. the result is stored before return for correct precision and exceptions
  126. one corner case is when the underflow flag should be raised because
  127. the precise result is an inexact subnormal double, but the calculated
  128. long double result is an exact subnormal double
  129. (so rounding to double does not raise exceptions)
  130. in nearest rounding mode dadd takes care of this: the last bit of the
  131. result is adjusted so rounding sees an inexact value when it should
  132. in non-nearest rounding mode fenv is used for the workaround
  133. */
  134. fesetround(round);
  135. if (round == FE_TONEAREST)
  136. z = dadd(hi, dadd(lo1, lo2));
  137. else {
  138. #if defined(FE_INEXACT) && defined(FE_UNDERFLOW)
  139. int e = fetestexcept(FE_INEXACT);
  140. feclearexcept(FE_INEXACT);
  141. #endif
  142. z = hi + (lo1 + lo2);
  143. #if defined(FE_INEXACT) && defined(FE_UNDERFLOW)
  144. if (getexp(z) < 0x3fff-1022 && fetestexcept(FE_INEXACT))
  145. feraiseexcept(FE_UNDERFLOW);
  146. else if (e)
  147. feraiseexcept(FE_INEXACT);
  148. #endif
  149. }
  150. return z;
  151. }
  152. #else
  153. /* origin: FreeBSD /usr/src/lib/msun/src/s_fma.c */
  154. /*-
  155. * Copyright (c) 2005-2011 David Schultz <[email protected]>
  156. * All rights reserved.
  157. *
  158. * Redistribution and use in source and binary forms, with or without
  159. * modification, are permitted provided that the following conditions
  160. * are met:
  161. * 1. Redistributions of source code must retain the above copyright
  162. * notice, this list of conditions and the following disclaimer.
  163. * 2. Redistributions in binary form must reproduce the above copyright
  164. * notice, this list of conditions and the following disclaimer in the
  165. * documentation and/or other materials provided with the distribution.
  166. *
  167. * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND
  168. * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  169. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  170. * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE
  171. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  172. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
  173. * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
  174. * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
  175. * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
  176. * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
  177. * SUCH DAMAGE.
  178. */
  179. /*
  180. * A struct dd represents a floating-point number with twice the precision
  181. * of a double. We maintain the invariant that "hi" stores the 53 high-order
  182. * bits of the result.
  183. */
  184. struct dd {
  185. double hi;
  186. double lo;
  187. };
  188. /*
  189. * Compute a+b exactly, returning the exact result in a struct dd. We assume
  190. * that both a and b are finite, but make no assumptions about their relative
  191. * magnitudes.
  192. */
  193. static inline struct dd dd_add(double a, double b)
  194. {
  195. struct dd ret;
  196. double s;
  197. ret.hi = a + b;
  198. s = ret.hi - a;
  199. ret.lo = (a - (ret.hi - s)) + (b - s);
  200. return (ret);
  201. }
  202. /*
  203. * Compute a+b, with a small tweak: The least significant bit of the
  204. * result is adjusted into a sticky bit summarizing all the bits that
  205. * were lost to rounding. This adjustment negates the effects of double
  206. * rounding when the result is added to another number with a higher
  207. * exponent. For an explanation of round and sticky bits, see any reference
  208. * on FPU design, e.g.,
  209. *
  210. * J. Coonen. An Implementation Guide to a Proposed Standard for
  211. * Floating-Point Arithmetic. Computer, vol. 13, no. 1, Jan 1980.
  212. */
  213. static inline double add_adjusted(double a, double b)
  214. {
  215. struct dd sum;
  216. union {double f; uint64_t i;} uhi, ulo;
  217. sum = dd_add(a, b);
  218. if (sum.lo != 0) {
  219. uhi.f = sum.hi;
  220. if ((uhi.i & 1) == 0) {
  221. /* hibits += (int)copysign(1.0, sum.hi * sum.lo) */
  222. ulo.f = sum.lo;
  223. uhi.i += 1 - ((uhi.i ^ ulo.i) >> 62);
  224. sum.hi = uhi.f;
  225. }
  226. }
  227. return (sum.hi);
  228. }
  229. /*
  230. * Compute ldexp(a+b, scale) with a single rounding error. It is assumed
  231. * that the result will be subnormal, and care is taken to ensure that
  232. * double rounding does not occur.
  233. */
  234. static inline double add_and_denormalize(double a, double b, int scale)
  235. {
  236. struct dd sum;
  237. union {double f; uint64_t i;} uhi, ulo;
  238. int bits_lost;
  239. sum = dd_add(a, b);
  240. /*
  241. * If we are losing at least two bits of accuracy to denormalization,
  242. * then the first lost bit becomes a round bit, and we adjust the
  243. * lowest bit of sum.hi to make it a sticky bit summarizing all the
  244. * bits in sum.lo. With the sticky bit adjusted, the hardware will
  245. * break any ties in the correct direction.
  246. *
  247. * If we are losing only one bit to denormalization, however, we must
  248. * break the ties manually.
  249. */
  250. if (sum.lo != 0) {
  251. uhi.f = sum.hi;
  252. bits_lost = -((int)(uhi.i >> 52) & 0x7ff) - scale + 1;
  253. if (bits_lost != 1 ^ (int)(uhi.i & 1)) {
  254. /* hibits += (int)copysign(1.0, sum.hi * sum.lo) */
  255. ulo.f = sum.lo;
  256. uhi.i += 1 - (((uhi.i ^ ulo.i) >> 62) & 2);
  257. sum.hi = uhi.f;
  258. }
  259. }
  260. return scalbn(sum.hi, scale);
  261. }
  262. /*
  263. * Compute a*b exactly, returning the exact result in a struct dd. We assume
  264. * that both a and b are normalized, so no underflow or overflow will occur.
  265. * The current rounding mode must be round-to-nearest.
  266. */
  267. static inline struct dd dd_mul(double a, double b)
  268. {
  269. static const double split = 0x1p27 + 1.0;
  270. struct dd ret;
  271. double ha, hb, la, lb, p, q;
  272. p = a * split;
  273. ha = a - p;
  274. ha += p;
  275. la = a - ha;
  276. p = b * split;
  277. hb = b - p;
  278. hb += p;
  279. lb = b - hb;
  280. p = ha * hb;
  281. q = ha * lb + la * hb;
  282. ret.hi = p + q;
  283. ret.lo = p - ret.hi + q + la * lb;
  284. return (ret);
  285. }
  286. /*
  287. * Fused multiply-add: Compute x * y + z with a single rounding error.
  288. *
  289. * We use scaling to avoid overflow/underflow, along with the
  290. * canonical precision-doubling technique adapted from:
  291. *
  292. * Dekker, T. A Floating-Point Technique for Extending the
  293. * Available Precision. Numer. Math. 18, 224-242 (1971).
  294. *
  295. * This algorithm is sensitive to the rounding precision. FPUs such
  296. * as the i387 must be set in double-precision mode if variables are
  297. * to be stored in FP registers in order to avoid incorrect results.
  298. * This is the default on FreeBSD, but not on many other systems.
  299. *
  300. * Hardware instructions should be used on architectures that support it,
  301. * since this implementation will likely be several times slower.
  302. */
  303. double fma(double x, double y, double z)
  304. {
  305. #pragma STDC FENV_ACCESS ON
  306. double xs, ys, zs, adj;
  307. struct dd xy, r;
  308. int oround;
  309. int ex, ey, ez;
  310. int spread;
  311. /*
  312. * Handle special cases. The order of operations and the particular
  313. * return values here are crucial in handling special cases involving
  314. * infinities, NaNs, overflows, and signed zeroes correctly.
  315. */
  316. if (!isfinite(x) || !isfinite(y))
  317. return (x * y + z);
  318. if (!isfinite(z))
  319. return (z);
  320. if (x == 0.0 || y == 0.0)
  321. return (x * y + z);
  322. if (z == 0.0)
  323. return (x * y);
  324. xs = frexp(x, &ex);
  325. ys = frexp(y, &ey);
  326. zs = frexp(z, &ez);
  327. oround = fegetround();
  328. spread = ex + ey - ez;
  329. /*
  330. * If x * y and z are many orders of magnitude apart, the scaling
  331. * will overflow, so we handle these cases specially. Rounding
  332. * modes other than FE_TONEAREST are painful.
  333. */
  334. if (spread < -DBL_MANT_DIG) {
  335. #ifdef FE_INEXACT
  336. feraiseexcept(FE_INEXACT);
  337. #endif
  338. #ifdef FE_UNDERFLOW
  339. if (!isnormal(z))
  340. feraiseexcept(FE_UNDERFLOW);
  341. #endif
  342. switch (oround) {
  343. default: /* FE_TONEAREST */
  344. return (z);
  345. #ifdef FE_TOWARDZERO
  346. case FE_TOWARDZERO:
  347. if (x > 0.0 ^ y < 0.0 ^ z < 0.0)
  348. return (z);
  349. else
  350. return (nextafter(z, 0));
  351. #endif
  352. #ifdef FE_DOWNWARD
  353. case FE_DOWNWARD:
  354. if (x > 0.0 ^ y < 0.0)
  355. return (z);
  356. else
  357. return (nextafter(z, -INFINITY));
  358. #endif
  359. #ifdef FE_UPWARD
  360. case FE_UPWARD:
  361. if (x > 0.0 ^ y < 0.0)
  362. return (nextafter(z, INFINITY));
  363. else
  364. return (z);
  365. #endif
  366. }
  367. }
  368. if (spread <= DBL_MANT_DIG * 2)
  369. zs = scalbn(zs, -spread);
  370. else
  371. zs = copysign(DBL_MIN, zs);
  372. fesetround(FE_TONEAREST);
  373. /*
  374. * Basic approach for round-to-nearest:
  375. *
  376. * (xy.hi, xy.lo) = x * y (exact)
  377. * (r.hi, r.lo) = xy.hi + z (exact)
  378. * adj = xy.lo + r.lo (inexact; low bit is sticky)
  379. * result = r.hi + adj (correctly rounded)
  380. */
  381. xy = dd_mul(xs, ys);
  382. r = dd_add(xy.hi, zs);
  383. spread = ex + ey;
  384. if (r.hi == 0.0) {
  385. /*
  386. * When the addends cancel to 0, ensure that the result has
  387. * the correct sign.
  388. */
  389. fesetround(oround);
  390. volatile double vzs = zs; /* XXX gcc CSE bug workaround */
  391. return xy.hi + vzs + scalbn(xy.lo, spread);
  392. }
  393. if (oround != FE_TONEAREST) {
  394. /*
  395. * There is no need to worry about double rounding in directed
  396. * rounding modes.
  397. * But underflow may not be raised properly, example in downward rounding:
  398. * fma(0x1.000000001p-1000, 0x1.000000001p-30, -0x1p-1066)
  399. */
  400. double ret;
  401. #if defined(FE_INEXACT) && defined(FE_UNDERFLOW)
  402. int e = fetestexcept(FE_INEXACT);
  403. feclearexcept(FE_INEXACT);
  404. #endif
  405. fesetround(oround);
  406. adj = r.lo + xy.lo;
  407. ret = scalbn(r.hi + adj, spread);
  408. #if defined(FE_INEXACT) && defined(FE_UNDERFLOW)
  409. if (ilogb(ret) < -1022 && fetestexcept(FE_INEXACT))
  410. feraiseexcept(FE_UNDERFLOW);
  411. else if (e)
  412. feraiseexcept(FE_INEXACT);
  413. #endif
  414. return ret;
  415. }
  416. adj = add_adjusted(r.lo, xy.lo);
  417. if (spread + ilogb(r.hi) > -1023)
  418. return scalbn(r.hi + adj, spread);
  419. else
  420. return add_and_denormalize(r.hi, adj, spread);
  421. }
  422. #endif