Skip to content

Commit 7fa9a67

Browse files
gnudlesCommit Bot
authored andcommitted
[vm] Update bit algorithms in utils.cc
Closes dart-lang/sdk#48942 GitOrigin-RevId: 484c201343c546abdfdc8669f87e844c26c0fd43 Change-Id: Ib918e0deca4cccbeef2cc6a17a84ec95a74e80f5 Reviewed-on: https://dart-review.googlesource.com/c/sdk/+/243361 Commit-Queue: Slava Egorov <vegorov@google.com> Reviewed-by: Slava Egorov <vegorov@google.com> Reviewed-by: Martin Kustermann <kustermann@google.com>
1 parent aa616d6 commit 7fa9a67

File tree

1 file changed

+17
-16
lines changed

1 file changed

+17
-16
lines changed

runtime/platform/utils.cc

Lines changed: 17 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,10 @@ int Utils::CountOneBits64(uint64_t x) {
3434
#if __GNUC__ && !defined(HOST_ARCH_IA32) && !defined(HOST_ARCH_X64)
3535
return __builtin_popcountll(x);
3636
#else
37-
return CountOneBits32(static_cast<uint32_t>(x)) +
38-
CountOneBits32(static_cast<uint32_t>(x >> 32));
37+
x = x - ((x >> 1) & 0x5555555555555555);
38+
x = (x & 0x3333333333333333) + ((x >> 2) & 0x3333333333333333);
39+
x = (((x + (x >> 4)) & 0x0f0f0f0f0f0f0f0f) * 0x0101010101010101) >> 56;
40+
return x;
3941
#endif
4042
}
4143

@@ -108,23 +110,22 @@ int Utils::CountTrailingZeros32(uint32_t x) {
108110
}
109111

110112
uint64_t Utils::ReverseBits64(uint64_t x) {
111-
const uint64_t one = static_cast<uint64_t>(1);
112-
uint64_t result = 0;
113-
for (uint64_t rbit = one << 63; x != 0; x >>= 1) {
114-
if ((x & one) != 0) result |= rbit;
115-
rbit >>= 1;
116-
}
117-
return result;
113+
x = ( (x >> 32) & 0x00000000ffffffff ) | ( x << 32 );
114+
x = ( (x >> 16) & 0x0000ffff0000ffff ) | ( (x & 0x0000ffff0000ffff) << 16 );
115+
x = ( (x >> 8) & 0x00ff00ff00ff00ff ) | ( (x & 0x00ff00ff00ff00ff) << 8 );
116+
x = ( (x >> 4) & 0x0f0f0f0f0f0f0f0f ) | ( (x & 0x0f0f0f0f0f0f0f0f) << 4 );
117+
x = ( (x >> 2) & 0x3333333333333333 ) | ( (x & 0x3333333333333333) << 2 );
118+
x = ( (x >> 1) & 0x5555555555555555 ) | ( (x & 0x5555555555555555) << 1 );
119+
return x;
118120
}
119121

120122
uint32_t Utils::ReverseBits32(uint32_t x) {
121-
const uint32_t one = static_cast<uint32_t>(1);
122-
uint32_t result = 0;
123-
for (uint32_t rbit = one << 31; x != 0; x >>= 1) {
124-
if ((x & one) != 0) result |= rbit;
125-
rbit >>= 1;
126-
}
127-
return result;
123+
x = ( (x >> 16) & 0x0000ffff ) | ( (x & 0x0000ffff) << 16 );
124+
x = ( (x >> 8) & 0x00ff00ff ) | ( (x & 0x00ff00ff) << 8 );
125+
x = ( (x >> 4) & 0x0f0f0f0f ) | ( (x & 0x0f0f0f0f) << 4 );
126+
x = ( (x >> 2) & 0x33333333 ) | ( (x & 0x33333333) << 2 );
127+
x = ( (x >> 1) & 0x55555555 ) | ( (x & 0x55555555) << 1 );
128+
return x;
128129
}
129130

130131
// Implementation according to H.S.Warren's "Hacker's Delight"

0 commit comments

Comments
 (0)