fp_fixint_impl.inc 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  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. #include "fp_lib.h"
  14. static __inline fixint_t __fixint(fp_t a) {
  15. const fixint_t fixint_max = (fixint_t)((~(fixuint_t)0) / 2);
  16. const fixint_t fixint_min = -fixint_max - 1;
  17. // Break a into sign, exponent, significand parts.
  18. const rep_t aRep = toRep(a);
  19. const rep_t aAbs = aRep & absMask;
  20. const fixint_t sign = aRep & signBit ? -1 : 1;
  21. const int exponent = (aAbs >> significandBits) - exponentBias;
  22. const rep_t significand = (aAbs & significandMask) | implicitBit;
  23. // If exponent is negative, the result is zero.
  24. if (exponent < 0)
  25. return 0;
  26. // If the value is too large for the integer type, saturate.
  27. if ((unsigned)exponent >= sizeof(fixint_t) * CHAR_BIT)
  28. return sign == 1 ? fixint_max : fixint_min;
  29. // If 0 <= exponent < significandBits, right shift to get the result.
  30. // Otherwise, shift left.
  31. if (exponent < significandBits)
  32. return (fixint_t)(sign * (significand >> (significandBits - exponent)));
  33. else
  34. return (fixint_t)(sign * ((fixuint_t)significand << (exponent - significandBits)));
  35. }