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