xref: /aosp_15_r20/external/compiler-rt/lib/builtins/fp_fixint_impl.inc (revision 7c3d14c8b49c529e04be81a3ce6f5cc23712e4c6)
1*7c3d14c8STreehugger Robot//===-- lib/fixdfsi.c - Double-precision -> integer conversion ----*- C -*-===//
2*7c3d14c8STreehugger Robot//
3*7c3d14c8STreehugger Robot//                     The LLVM Compiler Infrastructure
4*7c3d14c8STreehugger Robot//
5*7c3d14c8STreehugger Robot// This file is dual licensed under the MIT and the University of Illinois Open
6*7c3d14c8STreehugger Robot// Source Licenses. See LICENSE.TXT for details.
7*7c3d14c8STreehugger Robot//
8*7c3d14c8STreehugger Robot//===----------------------------------------------------------------------===//
9*7c3d14c8STreehugger Robot//
10*7c3d14c8STreehugger Robot// This file implements float to integer conversion for the
11*7c3d14c8STreehugger Robot// compiler-rt library.
12*7c3d14c8STreehugger Robot//
13*7c3d14c8STreehugger Robot//===----------------------------------------------------------------------===//
14*7c3d14c8STreehugger Robot
15*7c3d14c8STreehugger Robot#include "fp_lib.h"
16*7c3d14c8STreehugger Robot
17*7c3d14c8STreehugger Robotstatic __inline fixint_t __fixint(fp_t a) {
18*7c3d14c8STreehugger Robot    const fixint_t fixint_max = (fixint_t)((~(fixuint_t)0) / 2);
19*7c3d14c8STreehugger Robot    const fixint_t fixint_min = -fixint_max - 1;
20*7c3d14c8STreehugger Robot    // Break a into sign, exponent, significand
21*7c3d14c8STreehugger Robot    const rep_t aRep = toRep(a);
22*7c3d14c8STreehugger Robot    const rep_t aAbs = aRep & absMask;
23*7c3d14c8STreehugger Robot    const fixint_t sign = aRep & signBit ? -1 : 1;
24*7c3d14c8STreehugger Robot    const int exponent = (aAbs >> significandBits) - exponentBias;
25*7c3d14c8STreehugger Robot    const rep_t significand = (aAbs & significandMask) | implicitBit;
26*7c3d14c8STreehugger Robot
27*7c3d14c8STreehugger Robot    // If exponent is negative, the result is zero.
28*7c3d14c8STreehugger Robot    if (exponent < 0)
29*7c3d14c8STreehugger Robot        return 0;
30*7c3d14c8STreehugger Robot
31*7c3d14c8STreehugger Robot    // If the value is too large for the integer type, saturate.
32*7c3d14c8STreehugger Robot    if ((unsigned)exponent >= sizeof(fixint_t) * CHAR_BIT)
33*7c3d14c8STreehugger Robot        return sign == 1 ? fixint_max : fixint_min;
34*7c3d14c8STreehugger Robot
35*7c3d14c8STreehugger Robot    // If 0 <= exponent < significandBits, right shift to get the result.
36*7c3d14c8STreehugger Robot    // Otherwise, shift left.
37*7c3d14c8STreehugger Robot    if (exponent < significandBits)
38*7c3d14c8STreehugger Robot        return sign * (significand >> (significandBits - exponent));
39*7c3d14c8STreehugger Robot    else
40*7c3d14c8STreehugger Robot        return sign * ((fixint_t)significand << (exponent - significandBits));
41*7c3d14c8STreehugger Robot}
42