summaryrefslogtreecommitdiff
path: root/src/__support/FPUtil/NearestIntegerOperations.h
blob: 6b28e7ffb387b51a358b0c0e8124bac0eec2d544 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
//===-- Nearest integer floating-point operations ---------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#ifndef LLVM_LIBC_SRC___SUPPORT_FPUTIL_NEARESTINTEGEROPERATIONS_H
#define LLVM_LIBC_SRC___SUPPORT_FPUTIL_NEARESTINTEGEROPERATIONS_H

#include "FEnvImpl.h"
#include "FPBits.h"
#include "rounding_mode.h"

#include "include/llvm-libc-macros/math-macros.h"
#include "src/__support/CPP/type_traits.h"
#include "src/__support/common.h"

namespace LIBC_NAMESPACE {
namespace fputil {

template <typename T, cpp::enable_if_t<cpp::is_floating_point_v<T>, int> = 0>
LIBC_INLINE T trunc(T x) {
  FPBits<T> bits(x);

  // If x is infinity or NaN, return it.
  // If it is zero also we should return it as is, but the logic
  // later in this function takes care of it. But not doing a zero
  // check, we improve the run time of non-zero values.
  if (bits.is_inf_or_nan())
    return x;

  int exponent = bits.get_exponent();

  // If the exponent is greater than the most negative mantissa
  // exponent, then x is already an integer.
  if (exponent >= static_cast<int>(FPBits<T>::FRACTION_LEN))
    return x;

  // If the exponent is such that abs(x) is less than 1, then return 0.
  if (exponent <= -1)
    return FPBits<T>::zero(bits.sign()).get_val();

  int trim_size = FPBits<T>::FRACTION_LEN - exponent;
  bits.set_mantissa((bits.get_mantissa() >> trim_size) << trim_size);
  return bits.get_val();
}

template <typename T, cpp::enable_if_t<cpp::is_floating_point_v<T>, int> = 0>
LIBC_INLINE T ceil(T x) {
  FPBits<T> bits(x);

  // If x is infinity NaN or zero, return it.
  if (bits.is_inf_or_nan() || bits.is_zero())
    return x;

  bool is_neg = bits.is_neg();
  int exponent = bits.get_exponent();

  // If the exponent is greater than the most negative mantissa
  // exponent, then x is already an integer.
  if (exponent >= static_cast<int>(FPBits<T>::FRACTION_LEN))
    return x;

  if (exponent <= -1) {
    if (is_neg)
      return T(-0.0);
    else
      return T(1.0);
  }

  uint32_t trim_size = FPBits<T>::FRACTION_LEN - exponent;
  bits.set_mantissa((bits.get_mantissa() >> trim_size) << trim_size);
  T trunc_value = bits.get_val();

  // If x is already an integer, return it.
  if (trunc_value == x)
    return x;

  // If x is negative, the ceil operation is equivalent to the trunc operation.
  if (is_neg)
    return trunc_value;

  return trunc_value + T(1.0);
}

template <typename T, cpp::enable_if_t<cpp::is_floating_point_v<T>, int> = 0>
LIBC_INLINE T floor(T x) {
  FPBits<T> bits(x);
  if (bits.is_neg()) {
    return -ceil(-x);
  } else {
    return trunc(x);
  }
}

template <typename T, cpp::enable_if_t<cpp::is_floating_point_v<T>, int> = 0>
LIBC_INLINE T round(T x) {
  using StorageType = typename FPBits<T>::StorageType;
  FPBits<T> bits(x);

  // If x is infinity NaN or zero, return it.
  if (bits.is_inf_or_nan() || bits.is_zero())
    return x;

  int exponent = bits.get_exponent();

  // If the exponent is greater than the most negative mantissa
  // exponent, then x is already an integer.
  if (exponent >= static_cast<int>(FPBits<T>::FRACTION_LEN))
    return x;

  if (exponent == -1) {
    // Absolute value of x is greater than equal to 0.5 but less than 1.
    return FPBits<T>::one(bits.sign()).get_val();
  }

  if (exponent <= -2) {
    // Absolute value of x is less than 0.5.
    return FPBits<T>::zero(bits.sign()).get_val();
  }

  uint32_t trim_size = FPBits<T>::FRACTION_LEN - exponent;
  bool half_bit_set =
      bool(bits.get_mantissa() & (StorageType(1) << (trim_size - 1)));
  bits.set_mantissa((bits.get_mantissa() >> trim_size) << trim_size);
  T trunc_value = bits.get_val();

  // If x is already an integer, return it.
  if (trunc_value == x)
    return x;

  if (!half_bit_set) {
    // Franctional part is less than 0.5 so round value is the
    // same as the trunc value.
    return trunc_value;
  } else {
    return bits.is_neg() ? trunc_value - T(1.0) : trunc_value + T(1.0);
  }
}

template <typename T>
LIBC_INLINE constexpr cpp::enable_if_t<cpp::is_floating_point_v<T>, T>
round_using_specific_rounding_mode(T x, int rnd) {
  using StorageType = typename FPBits<T>::StorageType;
  FPBits<T> bits(x);

  // If x is infinity NaN or zero, return it.
  if (bits.is_inf_or_nan() || bits.is_zero())
    return x;

  bool is_neg = bits.is_neg();
  int exponent = bits.get_exponent();

  // If the exponent is greater than the most negative mantissa
  // exponent, then x is already an integer.
  if (exponent >= static_cast<int>(FPBits<T>::FRACTION_LEN))
    return x;

  if (exponent <= -1) {
    switch (rnd) {
    case FP_INT_DOWNWARD:
      return is_neg ? T(-1.0) : T(0.0);
    case FP_INT_UPWARD:
      return is_neg ? T(-0.0) : T(1.0);
    case FP_INT_TOWARDZERO:
      return is_neg ? T(-0.0) : T(0.0);
    case FP_INT_TONEARESTFROMZERO:
      if (exponent < -1)
        return is_neg ? T(-0.0) : T(0.0); // abs(x) < 0.5
      return is_neg ? T(-1.0) : T(1.0);   // abs(x) >= 0.5
    case FP_INT_TONEAREST:
    default:
      if (exponent <= -2 || bits.get_mantissa() == 0)
        return is_neg ? T(-0.0) : T(0.0); // abs(x) <= 0.5
      else
        return is_neg ? T(-1.0) : T(1.0); // abs(x) > 0.5
    }
  }

  uint32_t trim_size = FPBits<T>::FRACTION_LEN - exponent;
  FPBits<T> new_bits = bits;
  new_bits.set_mantissa((bits.get_mantissa() >> trim_size) << trim_size);
  T trunc_value = new_bits.get_val();

  // If x is already an integer, return it.
  if (trunc_value == x)
    return x;

  StorageType trim_value =
      bits.get_mantissa() & ((StorageType(1) << trim_size) - 1);
  StorageType half_value = (StorageType(1) << (trim_size - 1));
  // If exponent is 0, trimSize will be equal to the mantissa width, and
  // truncIsOdd` will not be correct. So, we handle it as a special case
  // below.
  StorageType trunc_is_odd =
      new_bits.get_mantissa() & (StorageType(1) << trim_size);

  switch (rnd) {
  case FP_INT_DOWNWARD:
    return is_neg ? trunc_value - T(1.0) : trunc_value;
  case FP_INT_UPWARD:
    return is_neg ? trunc_value : trunc_value + T(1.0);
  case FP_INT_TOWARDZERO:
    return trunc_value;
  case FP_INT_TONEARESTFROMZERO:
    if (trim_value >= half_value)
      return is_neg ? trunc_value - T(1.0) : trunc_value + T(1.0);
    return trunc_value;
  case FP_INT_TONEAREST:
  default:
    if (trim_value > half_value) {
      return is_neg ? trunc_value - T(1.0) : trunc_value + T(1.0);
    } else if (trim_value == half_value) {
      if (exponent == 0)
        return is_neg ? T(-2.0) : T(2.0);
      if (trunc_is_odd)
        return is_neg ? trunc_value - T(1.0) : trunc_value + T(1.0);
      else
        return trunc_value;
    } else {
      return trunc_value;
    }
  }
}

template <typename T>
LIBC_INLINE cpp::enable_if_t<cpp::is_floating_point_v<T>, T>
round_using_current_rounding_mode(T x) {
  int rounding_mode = quick_get_round();

  switch (rounding_mode) {
  case FE_DOWNWARD:
    return round_using_specific_rounding_mode(x, FP_INT_DOWNWARD);
  case FE_UPWARD:
    return round_using_specific_rounding_mode(x, FP_INT_UPWARD);
  case FE_TOWARDZERO:
    return round_using_specific_rounding_mode(x, FP_INT_TOWARDZERO);
  case FE_TONEAREST:
    return round_using_specific_rounding_mode(x, FP_INT_TONEAREST);
  default:
    __builtin_unreachable();
  }
}

template <bool IsSigned, typename T>
LIBC_INLINE constexpr cpp::enable_if_t<cpp::is_floating_point_v<T>, T>
fromfp(T x, int rnd, unsigned int width) {
  using StorageType = typename FPBits<T>::StorageType;

  constexpr StorageType EXPLICIT_BIT =
      FPBits<T>::SIG_MASK - FPBits<T>::FRACTION_MASK;

  if (width == 0U) {
    raise_except_if_required(FE_INVALID);
    return FPBits<T>::quiet_nan().get_val();
  }

  FPBits<T> bits(x);

  if (bits.is_inf_or_nan()) {
    raise_except_if_required(FE_INVALID);
    return FPBits<T>::quiet_nan().get_val();
  }

  T rounded_value = round_using_specific_rounding_mode(x, rnd);

  if constexpr (IsSigned) {
    // T can't hold a finite number >= 2.0 * 2^EXP_BIAS.
    if (width - 1 > FPBits<T>::EXP_BIAS)
      return rounded_value;

    StorageType range_exp = width - 1U + FPBits<T>::EXP_BIAS;
    // rounded_value < -2^(width - 1)
    T range_min =
        FPBits<T>::create_value(Sign::NEG, range_exp, EXPLICIT_BIT).get_val();
    if (rounded_value < range_min) {
      raise_except_if_required(FE_INVALID);
      return FPBits<T>::quiet_nan().get_val();
    }
    // rounded_value > 2^(width - 1) - 1
    T range_max =
        FPBits<T>::create_value(Sign::POS, range_exp, EXPLICIT_BIT).get_val() -
        T(1.0);
    if (rounded_value > range_max) {
      raise_except_if_required(FE_INVALID);
      return FPBits<T>::quiet_nan().get_val();
    }

    return rounded_value;
  }

  if (rounded_value < T(0.0)) {
    raise_except_if_required(FE_INVALID);
    return FPBits<T>::quiet_nan().get_val();
  }

  // T can't hold a finite number >= 2.0 * 2^EXP_BIAS.
  if (width > FPBits<T>::EXP_BIAS)
    return rounded_value;

  StorageType range_exp = width + FPBits<T>::EXP_BIAS;
  // rounded_value > 2^width - 1
  T range_max =
      FPBits<T>::create_value(Sign::POS, range_exp, EXPLICIT_BIT).get_val() -
      T(1.0);
  if (rounded_value > range_max) {
    raise_except_if_required(FE_INVALID);
    return FPBits<T>::quiet_nan().get_val();
  }

  return rounded_value;
}

template <bool IsSigned, typename T>
LIBC_INLINE constexpr cpp::enable_if_t<cpp::is_floating_point_v<T>, T>
fromfpx(T x, int rnd, unsigned int width) {
  T rounded_value = fromfp<IsSigned>(x, rnd, width);
  FPBits<T> bits(rounded_value);

  if (!bits.is_nan() && rounded_value != x)
    raise_except_if_required(FE_INEXACT);

  return rounded_value;
}

namespace internal {

template <typename F, typename I,
          cpp::enable_if_t<cpp::is_floating_point_v<F> && cpp::is_integral_v<I>,
                           int> = 0>
LIBC_INLINE I rounded_float_to_signed_integer(F x) {
  constexpr I INTEGER_MIN = (I(1) << (sizeof(I) * 8 - 1));
  constexpr I INTEGER_MAX = -(INTEGER_MIN + 1);
  FPBits<F> bits(x);
  auto set_domain_error_and_raise_invalid = []() {
    set_errno_if_required(EDOM);
    raise_except_if_required(FE_INVALID);
  };

  if (bits.is_inf_or_nan()) {
    set_domain_error_and_raise_invalid();
    return bits.is_neg() ? INTEGER_MIN : INTEGER_MAX;
  }

  int exponent = bits.get_exponent();
  constexpr int EXPONENT_LIMIT = sizeof(I) * 8 - 1;
  if (exponent > EXPONENT_LIMIT) {
    set_domain_error_and_raise_invalid();
    return bits.is_neg() ? INTEGER_MIN : INTEGER_MAX;
  } else if (exponent == EXPONENT_LIMIT) {
    if (bits.is_pos() || bits.get_mantissa() != 0) {
      set_domain_error_and_raise_invalid();
      return bits.is_neg() ? INTEGER_MIN : INTEGER_MAX;
    }
    // If the control reaches here, then it means that the rounded
    // value is the most negative number for the signed integer type I.
  }

  // For all other cases, if `x` can fit in the integer type `I`,
  // we just return `x`. static_cast will convert the floating
  // point value to the exact integer value.
  return static_cast<I>(x);
}

} // namespace internal

template <typename F, typename I,
          cpp::enable_if_t<cpp::is_floating_point_v<F> && cpp::is_integral_v<I>,
                           int> = 0>
LIBC_INLINE I round_to_signed_integer(F x) {
  return internal::rounded_float_to_signed_integer<F, I>(round(x));
}

template <typename F, typename I,
          cpp::enable_if_t<cpp::is_floating_point_v<F> && cpp::is_integral_v<I>,
                           int> = 0>
LIBC_INLINE I round_to_signed_integer_using_current_rounding_mode(F x) {
  return internal::rounded_float_to_signed_integer<F, I>(
      round_using_current_rounding_mode(x));
}

} // namespace fputil
} // namespace LIBC_NAMESPACE

#endif // LLVM_LIBC_SRC___SUPPORT_FPUTIL_NEARESTINTEGEROPERATIONS_H