|
| 1 | +//===-- Unit tests for bfloat16 type --------------------------------------===// |
| 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 "src/__support/FPUtil/bfloat16.h" |
| 10 | +#include "test/UnitTest/FPMatcher.h" |
| 11 | +#include "test/UnitTest/Test.h" |
| 12 | +#include "utils/MPFRWrapper/MPCommon.h" |
| 13 | + |
| 14 | +using BFloat16 = LIBC_NAMESPACE::fputil::BFloat16; |
| 15 | +using LlvmLibcBfloat16ConversionTest = |
| 16 | + LIBC_NAMESPACE::testing::FPTest<BFloat16>; |
| 17 | + |
| 18 | +// range: [0, inf] |
| 19 | +static constexpr uint16_t POS_START = 0x0000U; |
| 20 | +static constexpr uint16_t POS_STOP = 0x7f80U; |
| 21 | + |
| 22 | +// range: [-0, -inf] |
| 23 | +static constexpr uint16_t NEG_START = 0x8000U; |
| 24 | +static constexpr uint16_t NEG_STOP = 0xff80U; |
| 25 | + |
| 26 | +using MPFRNumber = LIBC_NAMESPACE::testing::mpfr::MPFRNumber; |
| 27 | + |
| 28 | +TEST_F(LlvmLibcBfloat16ConversionTest, ToFloatPositiveRange) { |
| 29 | + for (uint16_t bits = POS_START; bits <= POS_STOP; bits++) { |
| 30 | + BFloat16 bf16_num{bits}; |
| 31 | + MPFRNumber mpfr_num{bf16_num}; |
| 32 | + |
| 33 | + // bfloat16 to float |
| 34 | + float mpfr_float = mpfr_num.as<float>(); |
| 35 | + EXPECT_FP_EQ_ALL_ROUNDING(mpfr_float, static_cast<float>(bf16_num)); |
| 36 | + |
| 37 | + // float to bfloat16 |
| 38 | + BFloat16 bf16_from_float{mpfr_float}; |
| 39 | + MPFRNumber mpfr_num_2{mpfr_float}; |
| 40 | + BFloat16 mpfr_bfloat = mpfr_num_2.as<BFloat16>(); |
| 41 | + EXPECT_FP_EQ_ALL_ROUNDING(mpfr_bfloat, bf16_from_float); |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +TEST_F(LlvmLibcBfloat16ConversionTest, ToFloatNegativeRange) { |
| 46 | + for (uint16_t bits = NEG_START; bits <= NEG_STOP; bits++) { |
| 47 | + BFloat16 bf16_num{bits}; |
| 48 | + MPFRNumber mpfr_num{bf16_num}; |
| 49 | + |
| 50 | + // bfloat16 to float |
| 51 | + float mpfr_float = mpfr_num.as<float>(); |
| 52 | + EXPECT_FP_EQ_ALL_ROUNDING(mpfr_float, static_cast<float>(bf16_num)); |
| 53 | + |
| 54 | + // float to bfloat16 |
| 55 | + BFloat16 bf16_from_float{mpfr_float}; |
| 56 | + MPFRNumber mpfr_num_2{mpfr_float}; |
| 57 | + BFloat16 mpfr_bfloat = mpfr_num_2.as<BFloat16>(); |
| 58 | + EXPECT_FP_EQ_ALL_ROUNDING(mpfr_bfloat, bf16_from_float); |
| 59 | + } |
| 60 | +} |
| 61 | + |
| 62 | +TEST_F(LlvmLibcBfloat16ConversionTest, FromInteger) { |
| 63 | + constexpr int RANGE = 100'000; |
| 64 | + for (int i = -RANGE; i <= RANGE; i++) { |
| 65 | + BFloat16 mpfr_bfloat = MPFRNumber(i).as<BFloat16>(); |
| 66 | + BFloat16 libc_bfloat{i}; |
| 67 | + EXPECT_FP_EQ_ALL_ROUNDING(mpfr_bfloat, libc_bfloat); |
| 68 | + } |
| 69 | +} |
0 commit comments