xref: /freebsd/contrib/llvm-project/compiler-rt/lib/builtins/divtc3.c (revision e6bfd18d21b225af6a0ed67ceeaf1293b7b9eba5)
1 //===-- divtc3.c - Implement __divtc3 -------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements __divtc3 for the compiler_rt library.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #define QUAD_PRECISION
14 #include "fp_lib.h"
15 #include "int_lib.h"
16 #include "int_math.h"
17 
18 // Returns: the quotient of (a + ib) / (c + id)
19 
20 COMPILER_RT_ABI Lcomplex __divtc3(long double __a, long double __b,
21                                   long double __c, long double __d) {
22   int __ilogbw = 0;
23   long double __logbw =
24       __compiler_rt_logbl(__compiler_rt_fmaxl(crt_fabsl(__c), crt_fabsl(__d)));
25   if (crt_isfinite(__logbw)) {
26     __ilogbw = (int)__logbw;
27     __c = __compiler_rt_scalbnl(__c, -__ilogbw);
28     __d = __compiler_rt_scalbnl(__d, -__ilogbw);
29   }
30   long double __denom = __c * __c + __d * __d;
31   Lcomplex z;
32   COMPLEX_REAL(z) =
33       __compiler_rt_scalbnl((__a * __c + __b * __d) / __denom, -__ilogbw);
34   COMPLEX_IMAGINARY(z) =
35       __compiler_rt_scalbnl((__b * __c - __a * __d) / __denom, -__ilogbw);
36   if (crt_isnan(COMPLEX_REAL(z)) && crt_isnan(COMPLEX_IMAGINARY(z))) {
37     if ((__denom == 0.0) && (!crt_isnan(__a) || !crt_isnan(__b))) {
38       COMPLEX_REAL(z) = crt_copysignl(CRT_INFINITY, __c) * __a;
39       COMPLEX_IMAGINARY(z) = crt_copysignl(CRT_INFINITY, __c) * __b;
40     } else if ((crt_isinf(__a) || crt_isinf(__b)) && crt_isfinite(__c) &&
41                crt_isfinite(__d)) {
42       __a = crt_copysignl(crt_isinf(__a) ? 1.0 : 0.0, __a);
43       __b = crt_copysignl(crt_isinf(__b) ? 1.0 : 0.0, __b);
44       COMPLEX_REAL(z) = CRT_INFINITY * (__a * __c + __b * __d);
45       COMPLEX_IMAGINARY(z) = CRT_INFINITY * (__b * __c - __a * __d);
46     } else if (crt_isinf(__logbw) && __logbw > 0.0 && crt_isfinite(__a) &&
47                crt_isfinite(__b)) {
48       __c = crt_copysignl(crt_isinf(__c) ? 1.0 : 0.0, __c);
49       __d = crt_copysignl(crt_isinf(__d) ? 1.0 : 0.0, __d);
50       COMPLEX_REAL(z) = 0.0 * (__a * __c + __b * __d);
51       COMPLEX_IMAGINARY(z) = 0.0 * (__b * __c - __a * __d);
52     }
53   }
54   return z;
55 }
56