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