1 // Copyright 2006-2008 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #ifndef V8_COMPILER_INTRINSICS_H_
6 #define V8_COMPILER_INTRINSICS_H_
8 #include "src/base/macros.h"
13 class CompilerIntrinsics {
15 // Returns number of zero bits preceding least significant 1 bit.
16 // Undefined for zero value.
17 INLINE(static int CountTrailingZeros(uint32_t value));
19 // Returns number of zero bits following most significant 1 bit.
20 // Undefined for zero value.
21 INLINE(static int CountLeadingZeros(uint32_t value));
23 // Returns the number of bits set.
24 INLINE(static int CountSetBits(uint32_t value));
28 int CompilerIntrinsics::CountTrailingZeros(uint32_t value) {
29 return __builtin_ctz(value);
32 int CompilerIntrinsics::CountLeadingZeros(uint32_t value) {
33 return __builtin_clz(value);
36 int CompilerIntrinsics::CountSetBits(uint32_t value) {
37 return __builtin_popcount(value);
40 #elif defined(_MSC_VER)
42 #pragma intrinsic(_BitScanForward)
43 #pragma intrinsic(_BitScanReverse)
45 int CompilerIntrinsics::CountTrailingZeros(uint32_t value) {
46 unsigned long result; //NOLINT
47 _BitScanForward(&result, static_cast<long>(value)); //NOLINT
48 return static_cast<int>(result);
51 int CompilerIntrinsics::CountLeadingZeros(uint32_t value) {
52 unsigned long result; //NOLINT
53 _BitScanReverse(&result, static_cast<long>(value)); //NOLINT
54 return 31 - static_cast<int>(result);
57 int CompilerIntrinsics::CountSetBits(uint32_t value) {
58 // Manually count set bits.
59 value = ((value >> 1) & 0x55555555) + (value & 0x55555555);
60 value = ((value >> 2) & 0x33333333) + (value & 0x33333333);
61 value = ((value >> 4) & 0x0f0f0f0f) + (value & 0x0f0f0f0f);
62 value = ((value >> 8) & 0x00ff00ff) + (value & 0x00ff00ff);
63 value = ((value >> 16) & 0x0000ffff) + (value & 0x0000ffff);
68 #error Unsupported compiler
71 } } // namespace v8::internal
73 #endif // V8_COMPILER_INTRINSICS_H_