bit_util.h 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. // Copyright 2018 yuzu emulator team
  2. // Licensed under GPLv2 or any later version
  3. // Refer to the license.txt file included.
  4. #pragma once
  5. #include <climits>
  6. #include <cstddef>
  7. #ifdef _MSC_VER
  8. #include <intrin.h>
  9. #endif
  10. #include "common/common_types.h"
  11. namespace Common {
  12. /// Gets the size of a specified type T in bits.
  13. template <typename T>
  14. constexpr std::size_t BitSize() {
  15. return sizeof(T) * CHAR_BIT;
  16. }
  17. #ifdef _MSC_VER
  18. inline u32 CountLeadingZeroes32(u32 value) {
  19. unsigned long leading_zero = 0;
  20. if (_BitScanReverse(&leading_zero, value) != 0) {
  21. return 31 - leading_zero;
  22. }
  23. return 32;
  24. }
  25. inline u32 CountLeadingZeroes64(u64 value) {
  26. unsigned long leading_zero = 0;
  27. if (_BitScanReverse64(&leading_zero, value) != 0) {
  28. return 63 - leading_zero;
  29. }
  30. return 64;
  31. }
  32. #else
  33. inline u32 CountLeadingZeroes32(u32 value) {
  34. if (value == 0) {
  35. return 32;
  36. }
  37. return static_cast<u32>(__builtin_clz(value));
  38. }
  39. inline u32 CountLeadingZeroes64(u64 value) {
  40. if (value == 0) {
  41. return 64;
  42. }
  43. return static_cast<u32>(__builtin_clzll(value));
  44. }
  45. #endif
  46. #ifdef _MSC_VER
  47. inline u32 CountTrailingZeroes32(u32 value) {
  48. unsigned long trailing_zero = 0;
  49. if (_BitScanForward(&trailing_zero, value) != 0) {
  50. return trailing_zero;
  51. }
  52. return 32;
  53. }
  54. inline u32 CountTrailingZeroes64(u64 value) {
  55. unsigned long trailing_zero = 0;
  56. if (_BitScanForward64(&trailing_zero, value) != 0) {
  57. return trailing_zero;
  58. }
  59. return 64;
  60. }
  61. #else
  62. inline u32 CountTrailingZeroes32(u32 value) {
  63. if (value == 0) {
  64. return 32;
  65. }
  66. return static_cast<u32>(__builtin_ctz(value));
  67. }
  68. inline u32 CountTrailingZeroes64(u64 value) {
  69. if (value == 0) {
  70. return 64;
  71. }
  72. return static_cast<u32>(__builtin_ctzll(value));
  73. }
  74. #endif
  75. } // namespace Common