1235368Sgnn//===-- lib/fixdfsi.c - Double-precision -> integer conversion ----*- C -*-===//
2235368Sgnn//
3235368Sgnn//                     The LLVM Compiler Infrastructure
4235368Sgnn//
5235368Sgnn// This file is dual licensed under the MIT and the University of Illinois Open
6235368Sgnn// Source Licenses. See LICENSE.TXT for details.
7235368Sgnn//
8235368Sgnn//===----------------------------------------------------------------------===//
9235368Sgnn//
10235368Sgnn// This file implements float to integer conversion for the
11235368Sgnn// compiler-rt library.
12235368Sgnn//
13235368Sgnn//===----------------------------------------------------------------------===//
14235368Sgnn
15235368Sgnn#include "fp_lib.h"
16235368Sgnn
17235368Sgnnstatic __inline fixint_t __fixint(fp_t a) {
18235368Sgnn    const fixint_t fixint_max = (fixint_t)((~(fixuint_t)0) / 2);
19235368Sgnn    const fixint_t fixint_min = -fixint_max - 1;
20235368Sgnn    // Break a into sign, exponent, significand
21235368Sgnn    const rep_t aRep = toRep(a);
22235368Sgnn    const rep_t aAbs = aRep & absMask;
23235368Sgnn    const fixint_t sign = aRep & signBit ? -1 : 1;
24235368Sgnn    const int exponent = (aAbs >> significandBits) - exponentBias;
25235368Sgnn    const rep_t significand = (aAbs & significandMask) | implicitBit;
26235368Sgnn
27235368Sgnn    // If exponent is negative, the result is zero.
28235368Sgnn    if (exponent < 0)
29235368Sgnn        return 0;
30235368Sgnn
31235368Sgnn    // If the value is too large for the integer type, saturate.
32235368Sgnn    if ((unsigned)exponent >= sizeof(fixint_t) * CHAR_BIT)
33235368Sgnn        return sign == 1 ? fixint_max : fixint_min;
34235368Sgnn
35235368Sgnn    // If 0 <= exponent < significandBits, right shift to get the result.
36235368Sgnn    // Otherwise, shift left.
37235368Sgnn    if (exponent < significandBits)
38235368Sgnn        return sign * (significand >> (significandBits - exponent));
39235368Sgnn    else
40235368Sgnn        return sign * ((fixint_t)significand << (exponent - significandBits));
41235368Sgnn}
42235368Sgnn