leading_zeros.rs 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. // Note: these functions happen to produce the correct `usize::leading_zeros(0)` value
  2. // without a explicit zero check. Zero is probably common enough that it could warrant
  3. // adding a zero check at the beginning, but `__clzsi2` has a precondition that `x != 0`.
  4. // Compilers will insert the check for zero in cases where it is needed.
  5. /// Returns the number of leading binary zeros in `x`.
  6. #[doc(hidden)]
  7. pub fn usize_leading_zeros_default(x: usize) -> usize {
  8. // The basic idea is to test if the higher bits of `x` are zero and bisect the number
  9. // of leading zeros. It is possible for all branches of the bisection to use the same
  10. // code path by conditionally shifting the higher parts down to let the next bisection
  11. // step work on the higher or lower parts of `x`. Instead of starting with `z == 0`
  12. // and adding to the number of zeros, it is slightly faster to start with
  13. // `z == usize::MAX.count_ones()` and subtract from the potential number of zeros,
  14. // because it simplifies the final bisection step.
  15. let mut x = x;
  16. // the number of potential leading zeros
  17. let mut z = usize::MAX.count_ones() as usize;
  18. // a temporary
  19. let mut t: usize;
  20. #[cfg(target_pointer_width = "64")]
  21. {
  22. t = x >> 32;
  23. if t != 0 {
  24. z -= 32;
  25. x = t;
  26. }
  27. }
  28. #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
  29. {
  30. t = x >> 16;
  31. if t != 0 {
  32. z -= 16;
  33. x = t;
  34. }
  35. }
  36. t = x >> 8;
  37. if t != 0 {
  38. z -= 8;
  39. x = t;
  40. }
  41. t = x >> 4;
  42. if t != 0 {
  43. z -= 4;
  44. x = t;
  45. }
  46. t = x >> 2;
  47. if t != 0 {
  48. z -= 2;
  49. x = t;
  50. }
  51. // the last two bisections are combined into one conditional
  52. t = x >> 1;
  53. if t != 0 {
  54. z - 2
  55. } else {
  56. z - x
  57. }
  58. // We could potentially save a few cycles by using the LUT trick from
  59. // "https://embeddedgurus.com/state-space/2014/09/
  60. // fast-deterministic-and-portable-counting-leading-zeros/".
  61. // However, 256 bytes for a LUT is too large for embedded use cases. We could remove
  62. // the last 3 bisections and use this 16 byte LUT for the rest of the work:
  63. //const LUT: [u8; 16] = [0, 1, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 4, 4, 4, 4];
  64. //z -= LUT[x] as usize;
  65. //z
  66. // However, it ends up generating about the same number of instructions. When benchmarked
  67. // on x86_64, it is slightly faster to use the LUT, but this is probably because of OOO
  68. // execution effects. Changing to using a LUT and branching is risky for smaller cores.
  69. }
  70. // The above method does not compile well on RISC-V (because of the lack of predicated
  71. // instructions), producing code with many branches or using an excessively long
  72. // branchless solution. This method takes advantage of the set-if-less-than instruction on
  73. // RISC-V that allows `(x >= power-of-two) as usize` to be branchless.
  74. /// Returns the number of leading binary zeros in `x`.
  75. #[doc(hidden)]
  76. pub fn usize_leading_zeros_riscv(x: usize) -> usize {
  77. let mut x = x;
  78. // the number of potential leading zeros
  79. let mut z = usize::MAX.count_ones() as usize;
  80. // a temporary
  81. let mut t: usize;
  82. // RISC-V does not have a set-if-greater-than-or-equal instruction and
  83. // `(x >= power-of-two) as usize` will get compiled into two instructions, but this is
  84. // still the most optimal method. A conditional set can only be turned into a single
  85. // immediate instruction if `x` is compared with an immediate `imm` (that can fit into
  86. // 12 bits) like `x < imm` but not `imm < x` (because the immediate is always on the
  87. // right). If we try to save an instruction by using `x < imm` for each bisection, we
  88. // have to shift `x` left and compare with powers of two approaching `usize::MAX + 1`,
  89. // but the immediate will never fit into 12 bits and never save an instruction.
  90. #[cfg(target_pointer_width = "64")]
  91. {
  92. // If the upper 32 bits of `x` are not all 0, `t` is set to `1 << 5`, otherwise
  93. // `t` is set to 0.
  94. t = ((x >= (1 << 32)) as usize) << 5;
  95. // If `t` was set to `1 << 5`, then the upper 32 bits are shifted down for the
  96. // next step to process.
  97. x >>= t;
  98. // If `t` was set to `1 << 5`, then we subtract 32 from the number of potential
  99. // leading zeros
  100. z -= t;
  101. }
  102. #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))]
  103. {
  104. t = ((x >= (1 << 16)) as usize) << 4;
  105. x >>= t;
  106. z -= t;
  107. }
  108. t = ((x >= (1 << 8)) as usize) << 3;
  109. x >>= t;
  110. z -= t;
  111. t = ((x >= (1 << 4)) as usize) << 2;
  112. x >>= t;
  113. z -= t;
  114. t = ((x >= (1 << 2)) as usize) << 1;
  115. x >>= t;
  116. z -= t;
  117. t = (x >= (1 << 1)) as usize;
  118. x >>= t;
  119. z -= t;
  120. // All bits except the LSB are guaranteed to be zero for this final bisection step.
  121. // If `x != 0` then `x == 1` and subtracts one potential zero from `z`.
  122. z - x
  123. }
  124. intrinsics! {
  125. #[maybe_use_optimized_c_shim]
  126. #[cfg(any(
  127. target_pointer_width = "16",
  128. target_pointer_width = "32",
  129. target_pointer_width = "64"
  130. ))]
  131. /// Returns the number of leading binary zeros in `x`.
  132. pub extern "C" fn __clzsi2(x: usize) -> usize {
  133. if cfg!(any(target_arch = "riscv32", target_arch = "riscv64")) {
  134. usize_leading_zeros_riscv(x)
  135. } else {
  136. usize_leading_zeros_default(x)
  137. }
  138. }
  139. }