1#include "libm.h"
2
3#if LDBL_MANT_DIG == 53 && LDBL_MAX_EXP == 1024
4long double tanhl(long double x) {
5    return tanh(x);
6}
7#elif LDBL_MANT_DIG == 64 && LDBL_MAX_EXP == 16384
8long double tanhl(long double x) {
9    union ldshape u = {x};
10    unsigned ex = u.i.se & 0x7fff;
11    unsigned sign = u.i.se & 0x8000;
12    uint32_t w;
13    long double t;
14
15    /* x = |x| */
16    u.i.se = ex;
17    x = u.f;
18    w = u.i.m >> 32;
19
20    if (ex > 0x3ffe || (ex == 0x3ffe && w > 0x8c9f53d5)) {
21        /* |x| > log(3)/2 ~= 0.5493 or nan */
22        if (ex >= 0x3fff + 5) {
23            /* |x| >= 32 */
24            t = 1 + 0 / (x + 0x1p-120f);
25        } else {
26            t = expm1l(2 * x);
27            t = 1 - 2 / (t + 2);
28        }
29    } else if (ex > 0x3ffd || (ex == 0x3ffd && w > 0x82c577d4)) {
30        /* |x| > log(5/3)/2 ~= 0.2554 */
31        t = expm1l(2 * x);
32        t = t / (t + 2);
33    } else {
34        /* |x| is small */
35        t = expm1l(-2 * x);
36        t = -t / (t + 2);
37    }
38    return sign ? -t : t;
39}
40#elif LDBL_MANT_DIG == 113 && LDBL_MAX_EXP == 16384
41// TODO: broken implementation to make things compile
42long double tanhl(long double x) {
43    return tanh(x);
44}
45#endif
46