xref: /freebsd/contrib/llvm-project/compiler-rt/lib/builtins/fp_fixint_impl.inc (revision 02e9120893770924227138ba49df1edb3896112a)
1//===-- lib/fixdfsi.c - Double-precision -> integer conversion ----*- C -*-===//
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 float to integer conversion for the
10// compiler-rt library.
11//
12//===----------------------------------------------------------------------===//
13
14#include "fp_lib.h"
15
16static __inline fixint_t __fixint(fp_t a) {
17  const fixint_t fixint_max = (fixint_t)((~(fixuint_t)0) / 2);
18  const fixint_t fixint_min = -fixint_max - 1;
19  // Break a into sign, exponent, significand parts.
20  const rep_t aRep = toRep(a);
21  const rep_t aAbs = aRep & absMask;
22  const fixint_t sign = aRep & signBit ? -1 : 1;
23  const int exponent = (aAbs >> significandBits) - exponentBias;
24  const rep_t significand = (aAbs & significandMask) | implicitBit;
25
26  // If exponent is negative, the result is zero.
27  if (exponent < 0)
28    return 0;
29
30  // If the value is too large for the integer type, saturate.
31  if ((unsigned)exponent >= sizeof(fixint_t) * CHAR_BIT)
32    return sign == 1 ? fixint_max : fixint_min;
33
34  // If 0 <= exponent < significandBits, right shift to get the result.
35  // Otherwise, shift left.
36  if (exponent < significandBits)
37    return sign * (significand >> (significandBits - exponent));
38  else
39    return sign * ((fixint_t)significand << (exponent - significandBits));
40}
41