divdc3.c revision 2406dfe472402ed7fa39d8e9ba25dd7865aa015f
1/* ===-- divdc3.c - Implement __divdc3 -------------------------------------===
2 *
3 *                     The LLVM Compiler Infrastructure
4 *
5 * This file is dual licensed under the MIT and the University of Illinois Open
6 * Source Licenses. See LICENSE.TXT for details.
7 *
8 * ===----------------------------------------------------------------------===
9 *
10 * This file implements __divdc3 for the compiler_rt library.
11 *
12 * ===----------------------------------------------------------------------===
13 */
14
15#include "int_lib.h"
16#include <math.h>
17
18/* Returns: the quotient of (a + ib) / (c + id) */
19
20double _Complex
21__divdc3(double __a, double __b, double __c, double __d)
22{
23    int __ilogbw = 0;
24    double __logbw = logb(fmax(fabs(__c), fabs(__d)));
25    if (isfinite(__logbw))
26    {
27        __ilogbw = (int)__logbw;
28        __c = scalbn(__c, -__ilogbw);
29        __d = scalbn(__d, -__ilogbw);
30    }
31    double __denom = __c * __c + __d * __d;
32    double _Complex z;
33    __real__ z = scalbn((__a * __c + __b * __d) / __denom, -__ilogbw);
34    __imag__ z = scalbn((__b * __c - __a * __d) / __denom, -__ilogbw);
35    if (isnan(__real__ z) && isnan(__imag__ z))
36    {
37        if ((__denom == 0.0) && (!isnan(__a) || !isnan(__b)))
38        {
39            __real__ z = copysign(INFINITY, __c) * __a;
40            __imag__ z = copysign(INFINITY, __c) * __b;
41        }
42        else if ((isinf(__a) || isinf(__b)) && isfinite(__c) && isfinite(__d))
43        {
44            __a = copysign(isinf(__a) ? 1.0 : 0.0, __a);
45            __b = copysign(isinf(__b) ? 1.0 : 0.0, __b);
46            __real__ z = INFINITY * (__a * __c + __b * __d);
47            __imag__ z = INFINITY * (__b * __c - __a * __d);
48        }
49        else if (isinf(__logbw) && __logbw > 0.0 && isfinite(__a) && isfinite(__b))
50        {
51            __c = copysign(isinf(__c) ? 1.0 : 0.0, __c);
52            __d = copysign(isinf(__d) ? 1.0 : 0.0, __d);
53            __real__ z = 0.0 * (__a * __c + __b * __d);
54            __imag__ z = 0.0 * (__b * __c - __a * __d);
55        }
56    }
57    return z;
58}
59