]> granicus.if.org Git - llvm/commitdiff
[ADT/MathExtras] Introduce PowerOf2Ceil.
authorDavide Italiano <davide@freebsd.org>
Fri, 11 Nov 2016 02:22:16 +0000 (02:22 +0000)
committerDavide Italiano <davide@freebsd.org>
Fri, 11 Nov 2016 02:22:16 +0000 (02:22 +0000)
To be used in lld (and probably somewhere else in llvm).

Differential Revision:  https://reviews.llvm.org/D26538

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@286549 91177308-0d34-0410-b5e6-96231b3b80d8

include/llvm/Support/MathExtras.h
unittests/Support/MathExtrasTest.cpp

index 77b1f74d336c1e0ba2eedf6de8dbfec374a53f66..dd835170c2c58e79f412174aca946ba86f297d1a 100644 (file)
@@ -641,6 +641,14 @@ inline uint64_t PowerOf2Floor(uint64_t A) {
   return 1ull << (63 - countLeadingZeros(A, ZB_Undefined));
 }
 
+/// Returns the power of two which is greater than or equal to the given value.
+/// Essentially, it is a ceil operation across the domain of powers of two.
+inline uint64_t PowerOf2Ceil(uint64_t A) {
+  if (!A)
+    return 0;
+  return NextPowerOf2(A - 1);
+}
+
 /// Returns the next integer (mod 2**64) that is greater than or equal to
 /// \p Value and is a multiple of \p Align. \p Align must be non-zero.
 ///
index d373030881ec75e6ddebb10d5438d1b2f1531c43..c8c49506ce5b46737e000ef0c28e35a2359c2ed2 100644 (file)
@@ -165,6 +165,12 @@ TEST(MathExtras, isPowerOf2_64) {
   EXPECT_FALSE(isPowerOf2_64(0xABCDEF0ABCDEF0LL));
 }
 
+TEST(MathExtras, PowerOf2Ceil) {
+  EXPECT_EQ(0, PowerOf2Ceil(0));
+  EXPECT_EQ(8, PowerOf2Ceil(8));
+  EXPECT_EQ(8, PowerOf2Ceil(7));
+}
+
 TEST(MathExtras, ByteSwap_32) {
   EXPECT_EQ(0x44332211u, ByteSwap_32(0x11223344));
   EXPECT_EQ(0xDDCCBBAAu, ByteSwap_32(0xAABBCCDD));