Optimize use of isnan, isinf, finite
[platform/upstream/glibc.git] / math / divtc3.c
1 /* Copyright (C) 2005, 2006, 2011 Free Software Foundation, Inc.
2    This file is part of the GNU C Library.
3    Contributed by Richard Henderson <rth@redhat.com>, 2005.
4
5    The GNU C Library is free software; you can redistribute it and/or
6    modify it under the terms of the GNU Lesser General Public
7    License as published by the Free Software Foundation; either
8    version 2.1 of the License, or (at your option) any later version.
9
10    The GNU C Library is distributed in the hope that it will be useful,
11    but WITHOUT ANY WARRANTY; without even the implied warranty of
12    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13    Lesser General Public License for more details.
14
15    You should have received a copy of the GNU Lesser General Public
16    License along with the GNU C Library; if not, write to the Free
17    Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
18    02111-1307 USA.  */
19
20 #include <stdbool.h>
21 #include <math.h>
22 #include <complex.h>
23
24 attribute_hidden
25 long double _Complex
26 __divtc3 (long double a, long double b, long double c, long double d)
27 {
28   long double denom, ratio, x, y;
29
30   /* ??? We can get better behavior from logarithmic scaling instead of
31      the division.  But that would mean starting to link libgcc against
32      libm.  We could implement something akin to ldexp/frexp as gcc builtins
33      fairly easily...  */
34   if (fabsl (c) < fabsl (d))
35     {
36       ratio = c / d;
37       denom = (c * ratio) + d;
38       x = ((a * ratio) + b) / denom;
39       y = ((b * ratio) - a) / denom;
40     }
41   else
42     {
43       ratio = d / c;
44       denom = (d * ratio) + c;
45       x = ((b * ratio) + a) / denom;
46       y = (b - (a * ratio)) / denom;
47     }
48
49   /* Recover infinities and zeros that computed as NaN+iNaN; the only cases
50      are nonzero/zero, infinite/finite, and finite/infinite.  */
51   if (isnan (x) && isnan (y))
52     {
53       if (denom == 0.0 && (!isnan (a) || !isnan (b)))
54         {
55           x = __copysignl (INFINITY, c) * a;
56           y = __copysignl (INFINITY, c) * b;
57         }
58       else if ((__isinf_nsl (a) || __isinf_nsl (b))
59                && isfinite (c) && isfinite (d))
60         {
61           a = __copysignl (__isinf_nsl (a) ? 1 : 0, a);
62           b = __copysignl (__isinf_nsl (b) ? 1 : 0, b);
63           x = INFINITY * (a * c + b * d);
64           y = INFINITY * (b * c - a * d);
65         }
66       else if ((__isinf_nsl (c) || __isinf_nsl (d))
67                && isfinite (a) && isfinite (b))
68         {
69           c = __copysignl (__isinf_nsl (c) ? 1 : 0, c);
70           d = __copysignl (__isinf_nsl (d) ? 1 : 0, d);
71           x = 0.0 * (a * c + b * d);
72           y = 0.0 * (b * c - a * d);
73         }
74     }
75
76   return x + I * y;
77 }