1 //===- llvm/unittests/ADT/BitTest.cpp - <bit> tests ---===// 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 "llvm/ADT/bit.h" 10 #include "gtest/gtest.h" 11 #include <cstdint> 12 #include <cstdlib> 13 14 using namespace llvm; 15 16 namespace { 17 18 TEST(BitTest, BitCast) { 19 static const uint8_t kValueU8 = 0x80; 20 EXPECT_TRUE(llvm::bit_cast<int8_t>(kValueU8) < 0); 21 22 static const uint16_t kValueU16 = 0x8000; 23 EXPECT_TRUE(llvm::bit_cast<int16_t>(kValueU16) < 0); 24 25 static const float kValueF32 = 5632.34f; 26 EXPECT_FLOAT_EQ(kValueF32, 27 llvm::bit_cast<float>(llvm::bit_cast<uint32_t>(kValueF32))); 28 29 static const double kValueF64 = 87987234.983498; 30 EXPECT_DOUBLE_EQ(kValueF64, 31 llvm::bit_cast<double>(llvm::bit_cast<uint64_t>(kValueF64))); 32 } 33 34 TEST(BitTest, HasSingleBit) { 35 EXPECT_FALSE(llvm::has_single_bit(0U)); 36 EXPECT_FALSE(llvm::has_single_bit(0ULL)); 37 38 EXPECT_FALSE(llvm::has_single_bit(~0U)); 39 EXPECT_FALSE(llvm::has_single_bit(~0ULL)); 40 41 EXPECT_TRUE(llvm::has_single_bit(1U)); 42 EXPECT_TRUE(llvm::has_single_bit(1ULL)); 43 44 static const int8_t kValueS8 = -128; 45 EXPECT_TRUE(llvm::has_single_bit(static_cast<uint8_t>(kValueS8))); 46 47 static const int16_t kValueS16 = -32768; 48 EXPECT_TRUE(llvm::has_single_bit(static_cast<uint16_t>(kValueS16))); 49 } 50 51 TEST(BitTest, PopCount) { 52 EXPECT_EQ(0, llvm::popcount(0U)); 53 EXPECT_EQ(0, llvm::popcount(0ULL)); 54 55 EXPECT_EQ(32, llvm::popcount(~0U)); 56 EXPECT_EQ(64, llvm::popcount(~0ULL)); 57 58 for (int I = 0; I != 32; ++I) 59 EXPECT_EQ(1, llvm::popcount(1U << I)); 60 } 61 62 } // anonymous namespace 63