1//===-- Implementation header for roundf ------------------------*- 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#ifndef LLVM_LIBC_SRC___SUPPORT_MATH_ROUNDF_H
10#define LLVM_LIBC_SRC___SUPPORT_MATH_ROUNDF_H
11
12#include "src/__support/FPUtil/NearestIntegerOperations.h"
13#include "src/__support/macros/attributes.h"
14#include "src/__support/macros/config.h"
15#include "src/__support/macros/optimization.h"
16#include "src/__support/macros/properties/architectures.h"
17#include "src/__support/macros/properties/compiler.h"
18#include "src/__support/macros/properties/cpu_features.h"
19
20namespace LIBC_NAMESPACE_DECL {
21namespace math {
22
23// For the following targets, clang will generate rounding instructions
24// by default:
25// - x86-64 with sse4.1 or after
26// - ARM v8
27// - RISC-V
28
29// Notes: gcc does not generate the instructions for x86-64 by default.
30
31// Notes: for x86-64, if `-ffp-model=strict` is set, `__builtin_round` will
32// generate a callback to `round` and it does not look like there is any way for
33// us to detect that just from the pre-defined macros. The only way to really
34// detect the call back is to compile and link with nostdlib.
35// This also affects `__builtin_elementwise_round`, making it behave identical
36// to `__builtin_round`.
37
38// Notes: `__builtin_elementwise_round` is slightly better than
39// `__builtin_round` in that it is not defined for x86-64 pre-SSE4.1, but it
40// still generate callback for ARM version < 8, and for x86-64 with
41// `-ffp-model=strict`.
42
43// Notes: `__builtin_roundf` expansion for x86-64 using SSE4.1 rounding
44// instruction by clang is only correct for the default rounding mode.
45// See https://github.com/llvm/llvm-project/issues/140252
46// So we will only use `__builtin_round` with clang on x86-64 if we assume
47// default rounding mode (FE_TONEAREST) only.
48
49LIBC_INLINE LIBC_CONSTEXPR float roundf(float x) {
50#if __has_builtin(__builtin_roundf) && !defined(LIBC_USE_CONSTEXPR) && \
51 (defined(__LIBC_USE_BUILTIN_ROUND) || \
52 (defined(LIBC_COMPILER_IS_CLANG) && \
53 defined(LIBC_TARGET_CPU_HAS_FPU_FLOAT) && \
54 (!defined(__ARM_ARCH) || (__ARM_ARCH >= 8)) && \
55 (!defined(LIBC_TARGET_ARCH_IS_X86) || \
56 defined(LIBC_MATH_HAS_ASSUME_ROUND_NEAREST_ONLY))))
57 return __builtin_roundf(x);
58#else
59 return fputil::round(x);
60#endif
61}
62
63} // namespace math
64} // namespace LIBC_NAMESPACE_DECL
65
66#endif // LLVM_LIBC_SRC___SUPPORT_MATH_ROUNDF_H
67