1 //===-- Unittests for fmin -----------------------------------------------===//
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 #include "include/math.h"
10 #include "src/math/fmin.h"
11 #include "utils/FPUtil/FPBits.h"
12 #include "utils/FPUtil/TestHelpers.h"
13 #include "utils/UnitTest/Test.h"
14 
15 using FPBits = __llvm_libc::fputil::FPBits<double>;
16 
17 double nan = static_cast<double>(FPBits::buildNaN(1));
18 double inf = static_cast<double>(FPBits::inf());
19 double negInf = static_cast<double>(FPBits::negInf());
20 
21 TEST(FminTest, NaNArg) {
22   EXPECT_FP_EQ(inf, __llvm_libc::fmin(nan, inf));
23   EXPECT_FP_EQ(negInf, __llvm_libc::fmin(negInf, nan));
24   EXPECT_FP_EQ(0.0, __llvm_libc::fmin(nan, 0.0));
25   EXPECT_FP_EQ(-0.0, __llvm_libc::fmin(-0.0, nan));
26   EXPECT_FP_EQ(-1.2345, __llvm_libc::fmin(nan, -1.2345));
27   EXPECT_FP_EQ(1.2345, __llvm_libc::fmin(1.2345, nan));
28   EXPECT_NE(isnan(__llvm_libc::fmin(nan, nan)), 0);
29 }
30 
31 TEST(FminTest, InfArg) {
32   EXPECT_FP_EQ(negInf, __llvm_libc::fmin(negInf, inf));
33   EXPECT_FP_EQ(0.0, __llvm_libc::fmin(inf, 0.0));
34   EXPECT_FP_EQ(-0.0, __llvm_libc::fmin(-0.0, inf));
35   EXPECT_FP_EQ(1.2345, __llvm_libc::fmin(inf, 1.2345));
36   EXPECT_FP_EQ(-1.2345, __llvm_libc::fmin(-1.2345, inf));
37 }
38 
39 TEST(FminTest, NegInfArg) {
40   EXPECT_FP_EQ(negInf, __llvm_libc::fmin(inf, negInf));
41   EXPECT_FP_EQ(negInf, __llvm_libc::fmin(negInf, 0.0));
42   EXPECT_FP_EQ(negInf, __llvm_libc::fmin(-0.0, negInf));
43   EXPECT_FP_EQ(negInf, __llvm_libc::fmin(negInf, -1.2345));
44   EXPECT_FP_EQ(negInf, __llvm_libc::fmin(1.2345, negInf));
45 }
46 
47 TEST(FminTest, BothZero) {
48   EXPECT_FP_EQ(0.0, __llvm_libc::fmin(0.0, 0.0));
49   EXPECT_FP_EQ(-0.0, __llvm_libc::fmin(-0.0, 0.0));
50   EXPECT_FP_EQ(-0.0, __llvm_libc::fmin(0.0, -0.0));
51   EXPECT_FP_EQ(-0.0, __llvm_libc::fmin(-0.0, -0.0));
52 }
53 
54 TEST(FminTest, InFloatRange) {
55   using UIntType = FPBits::UIntType;
56   constexpr UIntType count = 10000000;
57   constexpr UIntType step = UIntType(-1) / count;
58   for (UIntType i = 0, v = 0, w = UIntType(-1); i <= count;
59        ++i, v += step, w -= step) {
60     double x = FPBits(v), y = FPBits(w);
61     if (isnan(x) || isinf(x))
62       continue;
63     if (isnan(y) || isinf(y))
64       continue;
65     if ((x == 0) && (y == 0))
66       continue;
67 
68     if (x < y) {
69       ASSERT_FP_EQ(x, __llvm_libc::fmin(x, y));
70     } else {
71       ASSERT_FP_EQ(y, __llvm_libc::fmin(x, y));
72     }
73   }
74 }
75