1//===-- divsc3.c - Implement __divsc3 -------------------------------------===//
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 __divsc3 for the compiler_rt library.
10//
11//===----------------------------------------------------------------------===//
12
13#define SINGLE_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
20COMPILER_RT_ABI Fcomplex __divsc3(float __a, float __b, float __c, float __d) {
21  int __ilogbw = 0;
22  float __logbw =
23      __compiler_rt_logbf(__compiler_rt_fmaxf(crt_fabsf(__c), crt_fabsf(__d)));
24  if (crt_isfinite(__logbw)) {
25    __ilogbw = (int)__logbw;
26    __c = __compiler_rt_scalbnf(__c, -__ilogbw);
27    __d = __compiler_rt_scalbnf(__d, -__ilogbw);
28  }
29  float __denom = __c * __c + __d * __d;
30  Fcomplex z;
31  COMPLEX_REAL(z) =
32      __compiler_rt_scalbnf((__a * __c + __b * __d) / __denom, -__ilogbw);
33  COMPLEX_IMAGINARY(z) =
34      __compiler_rt_scalbnf((__b * __c - __a * __d) / __denom, -__ilogbw);
35  if (crt_isnan(COMPLEX_REAL(z)) && crt_isnan(COMPLEX_IMAGINARY(z))) {
36    if ((__denom == 0) && (!crt_isnan(__a) || !crt_isnan(__b))) {
37      COMPLEX_REAL(z) = crt_copysignf(CRT_INFINITY, __c) * __a;
38      COMPLEX_IMAGINARY(z) = crt_copysignf(CRT_INFINITY, __c) * __b;
39    } else if ((crt_isinf(__a) || crt_isinf(__b)) && crt_isfinite(__c) &&
40               crt_isfinite(__d)) {
41      __a = crt_copysignf(crt_isinf(__a) ? 1 : 0, __a);
42      __b = crt_copysignf(crt_isinf(__b) ? 1 : 0, __b);
43      COMPLEX_REAL(z) = CRT_INFINITY * (__a * __c + __b * __d);
44      COMPLEX_IMAGINARY(z) = CRT_INFINITY * (__b * __c - __a * __d);
45    } else if (crt_isinf(__logbw) && __logbw > 0 && crt_isfinite(__a) &&
46               crt_isfinite(__b)) {
47      __c = crt_copysignf(crt_isinf(__c) ? 1 : 0, __c);
48      __d = crt_copysignf(crt_isinf(__d) ? 1 : 0, __d);
49      COMPLEX_REAL(z) = 0 * (__a * __c + __b * __d);
50      COMPLEX_IMAGINARY(z) = 0 * (__b * __c - __a * __d);
51    }
52  }
53  return z;
54}
55