1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
//! 高级位操作 (ABM) 指令
//!
//! POPCNT 和 LZCNT 具有自己的 CPUID 位以指示支持。
//!
//! 引用的是:
//!
//! - [英特尔 64 位和 IA-32 架构软件开发人员手册第 2 卷:
//! 指令集引用,AZ][intel64_ref]。
//! - [AMD64 Architecture Programmer's Manual, Volume 3: General-Purpose and System Instructions][amd64_ref].
//!
//! [维基百科][wikipedia_bmi] 提供了可用指令的快速概览。
//!
//! [intel64_ref]: http://www.intel.de/content/dam/www/public/us/en/documents/manuals/64-ia-32-architectures-software-developer-instruction-set-reference-manual-325383.pdf
//! [amd64_ref]: http://support.amd.com/TechDocs/24594.pdf
//! [wikipedia_bmi]:
//! https://en.wikipedia.org/wiki/Bit_Manipulation_Instruction_Sets#ABM_.28Advanced_Bit_Manipulation.29
//!
//!

#[cfg(test)]
use stdarch_test::assert_instr;

/// 计算前导最高有效零位。
///
/// 当操作数为零时,它将返回其大小 (以位为单位)。
///
/// [Intel's documentation](https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_lzcnt_u32)
#[inline]
#[target_feature(enable = "lzcnt")]
#[cfg_attr(test, assert_instr(lzcnt))]
#[stable(feature = "simd_x86", since = "1.27.0")]
pub unsafe fn _lzcnt_u32(x: u32) -> u32 {
    x.leading_zeros()
}

/// 计算设置的位。
///
/// [Intel's documentation](https://www.intel.com/content/www/us/en/docs/intrinsics-guide/index.html#text=_popcnt32)
#[inline]
#[target_feature(enable = "popcnt")]
#[cfg_attr(test, assert_instr(popcnt))]
#[stable(feature = "simd_x86", since = "1.27.0")]
pub unsafe fn _popcnt32(x: i32) -> i32 {
    x.count_ones() as i32
}

#[cfg(test)]
mod tests {
    use stdarch_test::simd_test;

    use crate::core_arch::x86::*;

    #[simd_test(enable = "lzcnt")]
    unsafe fn test_lzcnt_u32() {
        assert_eq!(_lzcnt_u32(0b0101_1010), 25);
    }

    #[simd_test(enable = "popcnt")]
    unsafe fn test_popcnt32() {
        assert_eq!(_popcnt32(0b0101_1010), 4);
    }
}