M1 primary view: wx-rs patched+extended (Linux/GTK3 build, widget bridge), vendored wx 3.3.3 + asic-rs in thirdparty/, UI-SPEC table+KPIs+dialogs, build scripts

This commit is contained in:
2026-09-15 13:59:55 -06:00
parent 165d899fd8
commit b264cdd6d1
16316 changed files with 4932188 additions and 58 deletions
+195
View File
@@ -0,0 +1,195 @@
//! This module implements minimal run-time feature detection for x86.
//!
//! The features are detected using the `detect_features` function below.
//! This function uses the CPUID instruction to read the feature flags from the
//! CPU and encodes them in an `usize` where each bit position represents
//! whether a feature is available (bit is set) or unavaiable (bit is cleared).
//!
//! The enum `Feature` is used to map bit positions to feature names, and the
//! the `__crate::detect::check_for!` macro is used to map string literals (e.g.,
//! "avx") to these bit positions (e.g., `Feature::avx`).
//!
//! The run-time feature detection is performed by the
//! `__crate::detect::check_for(Feature) -> bool` function. On its first call,
//! this functions queries the CPU for the available features and stores them
//! in a global `AtomicUsize` variable. The query is performed by just checking
//! whether the feature bit in this global variable is set or cleared.
features! {
@TARGET: x86;
@MACRO_NAME: is_x86_feature_detected;
@MACRO_ATTRS:
/// A macro to test at *runtime* whether a CPU feature is available on
/// x86/x86-64 platforms.
///
/// This macro is provided in the standard library and will detect at runtime
/// whether the specified CPU feature is detected. This does **not** resolve at
/// compile time unless the specified feature is already enabled for the entire
/// crate. Runtime detection currently relies mostly on the `cpuid` instruction.
///
/// This macro only takes one argument which is a string literal of the feature
/// being tested for. The feature names supported are the lowercase versions of
/// the ones defined by Intel in [their documentation][docs].
///
/// ## Supported arguments
///
/// This macro supports the same names that `#[target_feature]` supports. Unlike
/// `#[target_feature]`, however, this macro does not support names separated
/// with a comma. Instead testing for multiple features must be done through
/// separate macro invocations for now.
///
/// Supported arguments are:
///
/// * `"aes"`
/// * `"pclmulqdq"`
/// * `"rdrand"`
/// * `"rdseed"`
/// * `"tsc"`
/// * `"mmx"`
/// * `"sse"`
/// * `"sse2"`
/// * `"sse3"`
/// * `"ssse3"`
/// * `"sse4.1"`
/// * `"sse4.2"`
/// * `"sse4a"`
/// * `"sha"`
/// * `"avx"`
/// * `"avx2"`
/// * `"avx512f"`
/// * `"avx512cd"`
/// * `"avx512er"`
/// * `"avx512pf"`
/// * `"avx512bw"`
/// * `"avx512dq"`
/// * `"avx512vl"`
/// * `"avx512ifma"`
/// * `"avx512vbmi"`
/// * `"avx512vpopcntdq"`
/// * `"avx512vbmi2"`
/// * `"avx512gfni"`
/// * `"avx512vaes"`
/// * `"avx512vpclmulqdq"`
/// * `"avx512vnni"`
/// * `"avx512bitalg"`
/// * `"avx512bf16"`
/// * `"avx512vp2intersect"`
/// * `"f16c"`
/// * `"fma"`
/// * `"bmi1"`
/// * `"bmi2"`
/// * `"abm"`
/// * `"lzcnt"`
/// * `"tbm"`
/// * `"popcnt"`
/// * `"fxsr"`
/// * `"xsave"`
/// * `"xsaveopt"`
/// * `"xsaves"`
/// * `"xsavec"`
/// * `"cmpxchg16b"`
/// * `"adx"`
/// * `"rtm"`
///
/// [docs]: https://software.intel.com/sites/landingpage/IntrinsicsGuide
@BIND_FEATURE_NAME: "abm"; "lzcnt"; // abm is a synonym for lzcnt
@FEATURE: aes: "aes";
/// AES (Advanced Encryption Standard New Instructions AES-NI)
@FEATURE: pclmulqdq: "pclmulqdq";
/// CLMUL (Carry-less Multiplication)
@FEATURE: rdrand: "rdrand";
/// RDRAND
@FEATURE: rdseed: "rdseed";
/// RDSEED
@FEATURE: tsc: "tsc";
/// TSC (Time Stamp Counter)
@FEATURE: mmx: "mmx";
/// MMX (MultiMedia eXtensions)
@FEATURE: sse: "sse";
/// SSE (Streaming SIMD Extensions)
@FEATURE: sse2: "sse2";
/// SSE2 (Streaming SIMD Extensions 2)
@FEATURE: sse3: "sse3";
/// SSE3 (Streaming SIMD Extensions 3)
@FEATURE: ssse3: "ssse3";
/// SSSE3 (Supplemental Streaming SIMD Extensions 3)
@FEATURE: sse4_1: "sse4.1";
/// SSE4.1 (Streaming SIMD Extensions 4.1)
@FEATURE: sse4_2: "sse4.2";
/// SSE4.2 (Streaming SIMD Extensions 4.2)
@FEATURE: sse4a: "sse4a";
/// SSE4a (Streaming SIMD Extensions 4a)
@FEATURE: sha: "sha";
/// SHA
@FEATURE: avx: "avx";
/// AVX (Advanced Vector Extensions)
@FEATURE: avx2: "avx2";
/// AVX2 (Advanced Vector Extensions 2)
@FEATURE: avx512f: "avx512f" ;
/// AVX-512 F (Foundation)
@FEATURE: avx512cd: "avx512cd" ;
/// AVX-512 CD (Conflict Detection Instructions)
@FEATURE: avx512er: "avx512er";
/// AVX-512 ER (Expo nential and Reciprocal Instructions)
@FEATURE: avx512pf: "avx512pf";
/// AVX-512 PF (Prefetch Instructions)
@FEATURE: avx512bw: "avx512bw";
/// AVX-512 BW (Byte and Word Instructions)
@FEATURE: avx512dq: "avx512dq";
/// AVX-512 DQ (Doubleword and Quadword)
@FEATURE: avx512vl: "avx512vl";
/// AVX-512 VL (Vector Length Extensions)
@FEATURE: avx512ifma: "avx512ifma";
/// AVX-512 IFMA (Integer Fused Multiply Add)
@FEATURE: avx512vbmi: "avx512vbmi";
/// AVX-512 VBMI (Vector Byte Manipulation Instructions)
@FEATURE: avx512vpopcntdq: "avx512vpopcntdq";
/// AVX-512 VPOPCNTDQ (Vector Population Count Doubleword and
/// Quadword)
@FEATURE: avx512vbmi2: "avx512vbmi2";
/// AVX-512 VBMI2 (Additional byte, word, dword and qword capabilities)
@FEATURE: avx512gfni: "avx512gfni";
/// AVX-512 GFNI (Galois Field New Instruction)
@FEATURE: avx512vaes: "avx512vaes";
/// AVX-512 VAES (Vector AES instruction)
@FEATURE: avx512vpclmulqdq: "avx512vpclmulqdq";
/// AVX-512 VPCLMULQDQ (Vector PCLMULQDQ instructions)
@FEATURE: avx512vnni: "avx512vnni";
/// AVX-512 VNNI (Vector Neural Network Instructions)
@FEATURE: avx512bitalg: "avx512bitalg";
/// AVX-512 BITALG (Support for VPOPCNT[B,W] and VPSHUFBITQMB)
@FEATURE: avx512bf16: "avx512bf16";
/// AVX-512 BF16 (BFLOAT16 instructions)
@FEATURE: avx512vp2intersect: "avx512vp2intersect";
/// AVX-512 P2INTERSECT
@FEATURE: f16c: "f16c";
/// F16C (Conversions between IEEE-754 `binary16` and `binary32` formats)
@FEATURE: fma: "fma";
/// FMA (Fused Multiply Add)
@FEATURE: bmi1: "bmi1" ;
/// BMI1 (Bit Manipulation Instructions 1)
@FEATURE: bmi2: "bmi2" ;
/// BMI2 (Bit Manipulation Instructions 2)
@FEATURE: lzcnt: "lzcnt";
/// ABM (Advanced Bit Manipulation) / LZCNT (Leading Zero Count)
@FEATURE: tbm: "tbm";
/// TBM (Trailing Bit Manipulation)
@FEATURE: popcnt: "popcnt";
/// POPCNT (Population Count)
@FEATURE: fxsr: "fxsr";
/// FXSR (Floating-point context fast save and restor)
@FEATURE: xsave: "xsave";
/// XSAVE (Save Processor Extended States)
@FEATURE: xsaveopt: "xsaveopt";
/// XSAVEOPT (Save Processor Extended States Optimized)
@FEATURE: xsaves: "xsaves";
/// XSAVES (Save Processor Extended States Supervisor)
@FEATURE: xsavec: "xsavec";
/// XSAVEC (Save Processor Extended States Compacted)
@FEATURE: cmpxchg16b: "cmpxchg16b";
/// CMPXCH16B (16-byte compare-and-swap instruction)
@FEATURE: adx: "adx";
/// ADX, Intel ADX (Multi-Precision Add-Carry Instruction Extensions)
@FEATURE: rtm: "rtm";
/// RTM, Intel (Restricted Transactional Memory)
}
+148
View File
@@ -0,0 +1,148 @@
//! Caches run-time feature detection so that it only needs to be computed
//! once.
#![allow(dead_code)] // not used on all platforms
use core::sync::atomic::{AtomicUsize, Ordering};
/// Sets the `bit` of `x`.
#[inline]
const fn set_bit(x: u64, bit: u32) -> u64 {
x | 1 << bit
}
/// Tests the `bit` of `x`.
#[inline]
const fn test_bit(x: u64, bit: u32) -> bool {
x & (1 << bit) != 0
}
/// Maximum number of features that can be cached.
const CACHE_CAPACITY: u32 = 62;
/// This type is used to initialize the cache
#[derive(Copy, Clone)]
pub(crate) struct Initializer(u64);
#[allow(clippy::use_self)]
impl Default for Initializer {
fn default() -> Self {
Initializer(0)
}
}
// NOTE: the `debug_assert!` would catch that we do not add more Features than
// the one fitting our cache.
impl Initializer {
/// Tests the `bit` of the cache.
#[inline]
pub(crate) fn test(self, bit: u32) -> bool {
debug_assert!(
bit < CACHE_CAPACITY,
"too many features, time to increase the cache size!"
);
test_bit(self.0, bit)
}
/// Sets the `bit` of the cache.
#[inline]
pub(crate) fn set(&mut self, bit: u32) {
debug_assert!(
bit < CACHE_CAPACITY,
"too many features, time to increase the cache size!"
);
let v = self.0;
self.0 = set_bit(v, bit);
}
}
/// This global variable is a cache of the features supported by the CPU.
// Note: on x64, we only use the first slot
static CACHE: [Cache; 2] = [Cache::uninitialized(), Cache::uninitialized()];
/// Feature cache with capacity for `size_of::<usize::MAX>() * 8 - 1` features.
///
/// Note: 0 is used to represent an uninitialized cache, and (at least) the most
/// significant bit is set on any cache which has been initialized.
///
/// Note: we use `Relaxed` atomic operations, because we are only interested in
/// the effects of operations on a single memory location. That is, we only need
/// "modification order", and not the full-blown "happens before".
struct Cache(AtomicUsize);
impl Cache {
const CAPACITY: u32 = (core::mem::size_of::<usize>() * 8 - 1) as u32;
const MASK: usize = (1 << Cache::CAPACITY) - 1;
const INITIALIZED_BIT: usize = 1usize << Cache::CAPACITY;
/// Creates an uninitialized cache.
#[allow(clippy::declare_interior_mutable_const)]
const fn uninitialized() -> Self {
Cache(AtomicUsize::new(0))
}
/// Is the `bit` in the cache set? Returns `None` if the cache has not been initialized.
#[inline]
pub(crate) fn test(&self, bit: u32) -> Option<bool> {
let cached = self.0.load(Ordering::Relaxed);
if cached == 0 {
None
} else {
Some(test_bit(cached as u64, bit))
}
}
/// Initializes the cache.
#[inline]
fn initialize(&self, value: usize) -> usize {
debug_assert_eq!((value & !Cache::MASK), 0);
self.0
.store(value | Cache::INITIALIZED_BIT, Ordering::Relaxed);
value
}
}
#[inline]
fn initialize(value: Initializer) -> Initializer {
CACHE[0].initialize((value.0) as usize & Cache::MASK);
CACHE[1].initialize((value.0 >> Cache::CAPACITY) as usize & Cache::MASK);
value
}
// We only have to detect features once, and it's fairly costly, so hint to LLVM
// that it should assume that cache hits are more common than misses (which is
// the point of caching). It's possibly unfortunate that this function needs to
// reach across modules like this to call `os::detect_features`, but it produces
// the best code out of several attempted variants.
//
// The `Initializer` that the cache was initialized with is returned, so that
// the caller can call `test()` on it without having to load the value from the
// cache again.
#[cold]
fn detect_and_initialize() -> Initializer {
initialize(super::os::detect_features())
}
/// Tests the `bit` of the storage. If the storage has not been initialized,
/// initializes it with the result of `os::detect_features()`.
///
/// On its first invocation, it detects the CPU features and caches them in the
/// `CACHE` global variable as an `AtomicU64`.
///
/// It uses the `Feature` variant to index into this variable as a bitset. If
/// the bit is set, the feature is enabled, and otherwise it is disabled.
///
/// If the feature `std_detect_env_override` is enabled looks for the env
/// variable `RUST_STD_DETECT_UNSTABLE` and uses its its content to disable
/// Features that would had been otherwise detected.
#[inline]
pub(crate) fn test(bit: u32) -> bool {
let (relative_bit, idx) = if bit < Cache::CAPACITY {
(bit, 0)
} else {
(bit - Cache::CAPACITY, 1)
};
CACHE[idx]
.test(relative_bit)
.unwrap_or_else(|| detect_and_initialize().test(bit))
}
+162
View File
@@ -0,0 +1,162 @@
//! This crate provides a `no_std` version of std's [`is_x86_feature_detected!`]
//! macro.
//!
//! This is possible because x86 chips can just use the `cpuid` instruction to
//! detect CPU features, whereas most other architectures require either reading
//! files or querying the OS.
//!
//! # Usage
//!
//! ```
//! # #[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
//! # fn main() {
//! if core_detect::is_x86_feature_detected!("ssse3") {
//! println!("SSSE3 is available");
//! }
//! # }
//! # #[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
//! # fn main() {}
//! ```
//!
//! Note that like the [equivalent macro in `std`][stddetect], this will error
//! on architectures other than x86/x86_64, so you should put the code behind a
//! `#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]` check.
//!
//! [stddetect]:
//! https://doc.rust-lang.org/nightly/std/macro.is_x86_feature_detected.html
//!
//! (In the future, this crate may provide another macro which returns false in
//! these cases instead, and supports testing multiple features simultaneously).
//!
//! # Caveats
//! The `cpuid` instruction doesn't exist on all x86 machines, it was added
//! around 1994. (It's also not available on SGX, but this doesn't cause any
//! issues since we can check that with `cfg(target_env = "sgx")`).
//!
//! If you run `cpuid` on a machine older than that, it causes an illegal
//! instruction fault (SIGILL). Unfortunately, there's no good stable way to
//! reliably determine if `cpuid` will fault in stable rust: A
//! [`core::arch::x86::has_cpuid`](https://doc.rust-lang.org/nightly/core/arch/x86/fn.has_cpuid.html)
//! function exists, but didn't stabilize with the rest of `core::arch::x86`,
//! and the only way to implement it ourselves is with inline asm, which... is
//! also still unstable.
//!
//! For what it's worth, it's actually pretty uncommon that we'd need to call
//! `has_cpuid` on common rust targets, since we perform the following compile
//! time checks:
//! - We never have cpuid on `target_env = "sgx"` (as mentioned).
//! - We always have cpuid on `target_arch = "x86_64"`.
//! - And we always have cpuid if `target_feature = "sse"` (which covers the
//! `i686-*` targets).
//!
//! Unfortunately, if none of those applies... we don't know if calling CPUID
//! will crash the process. This library has a few ways it can handle this:
//!
//! 1. Cautiously (the default): In this mode, we conceptually swap `has_cpuid`
//! out with a function that always returns false. That is: we never call it
//! unless we're sure it wont crash the process.
//!
//! 2. Recklessly (`feature = "assume_has_cpuid"`): This is essentially the
//! opposite of the last one — assume `has_cpuid` would have returned true,
//! and call `cpuid` anyway.
//!
//! In practice, this should be fine. These machines are rare now (they're
//! over 30 years old...), and pretty only are common through QEMU, and even
//! then, usually after a misconfiguration.
//!
//! If you do happen to run the instruction, the process crashes, but in a
//! controlled manner — Executing an illegal instruction to tringger a
//! SIGILL is what `core::intrinsics::abort` does on x86, so it's not
//! dangerous or anything.
//!
//! 3. Using unstable nightly features (`feature = "unstable_has_cpuid"`): This
//! approach requires a nightly compiler, but has no other major downsides,
//! besides the fact that the `has_cpuid` function could vanish at any time.
//!
//! Eventually, inline asm will stabilize and we can solve this problem more
//! cleanly.
#![no_std]
#![allow(dead_code)]
#![cfg_attr(
all(
target_arch = "x86",
not(target_env = "sgx"),
not(target_feature = "sse"),
feature = "unstable_has_cpuid",
),
feature(stdsimd)
)]
#[macro_use]
mod macros;
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
#[path = "arch/x86.rs"]
#[macro_use]
mod arch;
// Unimplemented architecture:
#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
mod arch {
#[doc(hidden)]
pub(crate) enum Feature {
Null,
}
#[doc(hidden)]
pub mod __is_feature_detected {}
impl Feature {
#[doc(hidden)]
pub(crate) fn from_str(_s: &str) -> Result<Feature, ()> {
Err(())
}
#[doc(hidden)]
pub(crate) fn to_str(self) -> &'static str {
""
}
}
}
pub(crate) use crate::arch::Feature;
#[doc(hidden)]
pub use crate::arch::__is_feature_detected;
/// Performs run-time feature detection.
#[inline]
#[allow(dead_code)]
fn check_for(x: Feature) -> bool {
cache::test(x as u32)
}
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
#[path = "os/x86.rs"]
mod os;
#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
mod os {
#[inline]
pub(crate) fn detect_features() -> crate::cache::Initializer {
Default::default()
}
}
#[cfg(not(any(target_arch = "x86", target_arch = "x86_64")))]
#[macro_export]
macro_rules! is_x86_feature_detected {
($t: tt) => {
compile_error!(
r#"
is_x86_feature_detected can only be used on x86 and x86_64 targets.
You can prevent it from being used in other architectures by
guarding it behind a cfg(target_arch) as follows:
#[cfg(any(target_arch = "x86", target_arch = "x86_64"))] {
if is_x86_feature_detected(...) { ... }
}
"#
)
};
}
mod cache;
+100
View File
@@ -0,0 +1,100 @@
#[allow(unused)]
macro_rules! features {
(
@TARGET: $target:ident;
@MACRO_NAME: $macro_name:ident;
@MACRO_ATTRS: $(#[$macro_attrs:meta])*
$(@BIND_FEATURE_NAME: $bind_feature:tt; $feature_impl:tt; )*
$(@NO_RUNTIME_DETECTION: $nort_feature:tt; )*
$(@FEATURE: $feature:ident: $feature_lit:tt; $(#[$feature_comment:meta])*)*
) => {
#[macro_export]
$(#[$macro_attrs])*
macro_rules! $macro_name {
$(
($feature_lit) => {
$crate::__is_feature_detected::$feature()
};
)*
$(
($bind_feature) => { $macro_name!($feature_impl); };
)*
$(
($nort_feature) => {
compile_error!(
concat!(
stringify!(nort_feature),
" feature cannot be detected at run-time"
)
)
};
)*
($t:tt,) => {
$macro_name!($t);
};
($t:tt) => {
compile_error!(
concat!(
concat!("unknown ", stringify!($target)),
concat!(" target feature: ", $t)
)
)
};
}
/// Each variant denotes a position in a bitset for a particular feature.
///
/// PLEASE: do not use this, it is an implementation detail subject
/// to change.
#[doc(hidden)]
#[allow(non_camel_case_types)]
#[derive(Copy, Clone)]
#[repr(u8)]
pub(crate) enum Feature {
$(
$(#[$feature_comment])*
$feature,
)*
// Do not add variants after last:
_last
}
impl Feature {
pub(crate) fn to_str(self) -> &'static str {
match self {
$(Feature::$feature => $feature_lit,)*
Feature::_last => unreachable!(),
}
}
#[cfg(feature = "std_detect_env_override")]
pub(crate) fn from_str(s: &str) -> Result<Feature, ()> {
match s {
$($feature_lit => Ok(Feature::$feature),)*
_ => Err(())
}
}
}
/// Each function performs run-time feature detection for a single
/// feature. This allow us to use stability attributes on a per feature
/// basis.
///
/// PLEASE: do not use this, it is an implementation detail subject
/// to change.
#[doc(hidden)]
pub mod __is_feature_detected {
$(
/// PLEASE: do not use this, it is an implementation detail
/// subject to change.
#[inline]
#[doc(hidden)]
pub fn $feature() -> bool {
cfg!(target_feature = $feature_lit) ||
$crate::check_for($crate::Feature::$feature)
}
)*
}
};
}
+297
View File
@@ -0,0 +1,297 @@
//! x86 run-time feature detection is OS independent.
#[cfg(target_arch = "x86")]
use core::arch::x86::*;
#[cfg(target_arch = "x86_64")]
use core::arch::x86_64::*;
use core::mem;
use crate::{cache, Feature};
mod bit {
#[inline]
pub(crate) fn test(x: usize, bit: u32) -> bool {
debug_assert!(bit < 32, "bit index out-of-bounds");
x & (1 << bit) != 0
}
}
#[inline]
fn have_cpuid() -> bool {
#[cfg(target_env = "sgx")]
{
false
}
#[cfg(all(not(target_env = "sgx"), target_arch = "x86_64"))]
{
true
}
#[cfg(all(not(target_env = "sgx"), target_arch = "x86"))]
{
// Optimization for i586 and i686 Rust targets which SSE enabled
// and support cpuid:
#[cfg(target_feature = "sse")]
{
true
}
#[cfg(all(not(target_feature = "sse"), feature = "unstable_has_cpuid"))]
{
has_cpuid()
}
#[cfg(all(not(target_feature = "sse"), not(feature = "unstable_has_cpuid")))]
{
// FIXME: This is wrong for machines before 1994. On those machines,
// we'll SIGILL (this isn't great, but in practice it should be
// well-defined enough). In practice, it's almost impossible to
// target these machines with LLVM, but it probably can be done —
// stdarch's detect code handles it after all. If we need to handle
// this, we can compile and link with some C code that uses inline
// ASM to detect cpuid, but for now this is probably fine in
// practice.
cfg!(feature = "assume_has_cpuid")
}
}
}
/// Run-time feature detection on x86 works by using the CPUID instruction.
///
/// The [CPUID Wikipedia page][wiki_cpuid] contains
/// all the information about which flags to set to query which values, and in
/// which registers these are reported.
///
/// The definitive references are:
/// - [Intel 64 and IA-32 Architectures Software Developer's Manual Volume 2:
/// Instruction Set Reference, A-Z][intel64_ref].
/// - [AMD64 Architecture Programmer's Manual, Volume 3: General-Purpose and
/// System Instructions][amd64_ref].
///
/// [wiki_cpuid]: https://en.wikipedia.org/wiki/CPUID
/// [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
pub(crate) fn detect_features() -> cache::Initializer {
let mut value = cache::Initializer::default();
// If the x86 CPU does not support the CPUID instruction then it is too
// old to support any of the currently-detectable features.
if !have_cpuid() {
return value;
}
// Calling `__cpuid`/`__cpuid_count` from here on is safe because the CPU
// has `cpuid` support.
// 0. EAX = 0: Basic Information:
// - EAX returns the "Highest Function Parameter", that is, the maximum
// leaf value for subsequent calls of `cpuinfo` in range [0,
// 0x8000_0000]. - The vendor ID is stored in 12 u8 ascii chars,
// returned in EBX, EDX, and ECX (in that order):
let (max_basic_leaf, vendor_id) = unsafe {
let CpuidResult {
eax: max_basic_leaf,
ebx,
ecx,
edx,
} = __cpuid(0);
let vendor_id: [[u8; 4]; 3] = [
mem::transmute(ebx),
mem::transmute(edx),
mem::transmute(ecx),
];
let vendor_id: [u8; 12] = mem::transmute(vendor_id);
(max_basic_leaf, vendor_id)
};
if max_basic_leaf < 1 {
// Earlier Intel 486, CPUID not implemented
return value;
}
// EAX = 1, ECX = 0: Queries "Processor Info and Feature Bits";
// Contains information about most x86 features.
let CpuidResult {
ecx: proc_info_ecx,
edx: proc_info_edx,
..
} = unsafe { __cpuid(0x0000_0001_u32) };
// EAX = 7, ECX = 0: Queries "Extended Features";
// Contains information about bmi,bmi2, and avx2 support.
let (extended_features_ebx, extended_features_ecx) = if max_basic_leaf >= 7 {
let CpuidResult { ebx, ecx, .. } = unsafe { __cpuid(0x0000_0007_u32) };
(ebx, ecx)
} else {
(0, 0) // CPUID does not support "Extended Features"
};
// EAX = 0x8000_0000, ECX = 0: Get Highest Extended Function Supported
// - EAX returns the max leaf value for extended information, that is,
// `cpuid` calls in range [0x8000_0000; u32::MAX]:
let CpuidResult {
eax: extended_max_basic_leaf,
..
} = unsafe { __cpuid(0x8000_0000_u32) };
// EAX = 0x8000_0001, ECX=0: Queries "Extended Processor Info and Feature
// Bits"
let extended_proc_info_ecx = if extended_max_basic_leaf >= 1 {
let CpuidResult { ecx, .. } = unsafe { __cpuid(0x8000_0001_u32) };
ecx
} else {
0
};
{
// borrows value till the end of this scope:
let mut enable = |r, rb, f| {
if bit::test(r as usize, rb) {
value.set(f as u32);
}
};
enable(proc_info_ecx, 0, Feature::sse3);
enable(proc_info_ecx, 1, Feature::pclmulqdq);
enable(proc_info_ecx, 9, Feature::ssse3);
enable(proc_info_ecx, 13, Feature::cmpxchg16b);
enable(proc_info_ecx, 19, Feature::sse4_1);
enable(proc_info_ecx, 20, Feature::sse4_2);
enable(proc_info_ecx, 23, Feature::popcnt);
enable(proc_info_ecx, 25, Feature::aes);
enable(proc_info_ecx, 29, Feature::f16c);
enable(proc_info_ecx, 30, Feature::rdrand);
enable(extended_features_ebx, 18, Feature::rdseed);
enable(extended_features_ebx, 19, Feature::adx);
enable(extended_features_ebx, 11, Feature::rtm);
enable(proc_info_edx, 4, Feature::tsc);
enable(proc_info_edx, 23, Feature::mmx);
enable(proc_info_edx, 24, Feature::fxsr);
enable(proc_info_edx, 25, Feature::sse);
enable(proc_info_edx, 26, Feature::sse2);
enable(extended_features_ebx, 29, Feature::sha);
enable(extended_features_ebx, 3, Feature::bmi1);
enable(extended_features_ebx, 8, Feature::bmi2);
// `XSAVE` and `AVX` support:
let cpu_xsave = bit::test(proc_info_ecx as usize, 26);
if cpu_xsave {
// 0. Here the CPU supports `XSAVE`.
// 1. Detect `OSXSAVE`, that is, whether the OS is AVX enabled and
// supports saving the state of the AVX/AVX2 vector registers on
// context-switches, see:
//
// - [intel: is avx enabled?][is_avx_enabled],
// - [mozilla: sse.cpp][mozilla_sse_cpp].
//
// [is_avx_enabled]: https://software.intel.com/en-us/blogs/2011/04/14/is-avx-enabled
// [mozilla_sse_cpp]: https://hg.mozilla.org/mozilla-central/file/64bab5cbb9b6/mozglue/build/SSE.cpp#l190
let cpu_osxsave = bit::test(proc_info_ecx as usize, 27);
if cpu_osxsave {
// 2. The OS must have signaled the CPU that it supports saving and
// restoring the:
//
// * SSE -> `XCR0.SSE[1]`
// * AVX -> `XCR0.AVX[2]`
// * AVX-512 -> `XCR0.AVX-512[7:5]`.
//
// by setting the corresponding bits of `XCR0` to `1`.
//
// This is safe because the CPU supports `xsave`
// and the OS has set `osxsave`.
let xcr0 = unsafe { _xgetbv(0) };
// Test `XCR0.SSE[1]` and `XCR0.AVX[2]` with the mask `0b110 == 6`:
let os_avx_support = xcr0 & 6 == 6;
// Test `XCR0.AVX-512[7:5]` with the mask `0b1110_0000 == 224`:
let os_avx512_support = xcr0 & 224 == 224;
// Only if the OS and the CPU support saving/restoring the AVX
// registers we enable `xsave` support:
if os_avx_support {
// See "13.3 ENABLING THE XSAVE FEATURE SET AND XSAVE-ENABLED
// FEATURES" in the "Intel® 64 and IA-32 Architectures Software
// Developer’s Manual, Volume 1: Basic Architecture":
//
// "Software enables the XSAVE feature set by setting
// CR4.OSXSAVE[bit 18] to 1 (e.g., with the MOV to CR4
// instruction). If this bit is 0, execution of any of XGETBV,
// XRSTOR, XRSTORS, XSAVE, XSAVEC, XSAVEOPT, XSAVES, and XSETBV
// causes an invalid-opcode exception (#UD)"
//
enable(proc_info_ecx, 26, Feature::xsave);
// For `xsaveopt`, `xsavec`, and `xsaves` we need to query:
// Processor Extended State Enumeration Sub-leaf (EAX = 0DH,
// ECX = 1):
if max_basic_leaf >= 0xd {
let CpuidResult {
eax: proc_extended_state1_eax,
..
} = unsafe { __cpuid_count(0xd_u32, 1) };
enable(proc_extended_state1_eax, 0, Feature::xsaveopt);
enable(proc_extended_state1_eax, 1, Feature::xsavec);
enable(proc_extended_state1_eax, 3, Feature::xsaves);
}
// FMA (uses 256-bit wide registers):
enable(proc_info_ecx, 12, Feature::fma);
// And AVX/AVX2:
enable(proc_info_ecx, 28, Feature::avx);
enable(extended_features_ebx, 5, Feature::avx2);
// For AVX-512 the OS also needs to support saving/restoring
// the extended state, only then we enable AVX-512 support:
if os_avx512_support {
enable(extended_features_ebx, 16, Feature::avx512f);
enable(extended_features_ebx, 17, Feature::avx512dq);
enable(extended_features_ebx, 21, Feature::avx512ifma);
enable(extended_features_ebx, 26, Feature::avx512pf);
enable(extended_features_ebx, 27, Feature::avx512er);
enable(extended_features_ebx, 28, Feature::avx512cd);
enable(extended_features_ebx, 30, Feature::avx512bw);
enable(extended_features_ebx, 31, Feature::avx512vl);
enable(extended_features_ecx, 1, Feature::avx512vbmi);
enable(extended_features_ecx, 5, Feature::avx512bf16);
enable(extended_features_ecx, 6, Feature::avx512vbmi2);
enable(extended_features_ecx, 8, Feature::avx512gfni);
enable(extended_features_ecx, 8, Feature::avx512vp2intersect);
enable(extended_features_ecx, 9, Feature::avx512vaes);
enable(extended_features_ecx, 10, Feature::avx512vpclmulqdq);
enable(extended_features_ecx, 11, Feature::avx512vnni);
enable(extended_features_ecx, 12, Feature::avx512bitalg);
enable(extended_features_ecx, 14, Feature::avx512vpopcntdq);
}
}
}
}
// This detects ABM on AMD CPUs and LZCNT on Intel CPUs.
// On intel CPUs with popcnt, lzcnt implements the
// "missing part" of ABM, so we map both to the same
// internal feature.
//
// The `is_x86_feature_detected!("lzcnt")` macro then
// internally maps to Feature::abm.
enable(extended_proc_info_ecx, 5, Feature::lzcnt);
// As Hygon Dhyana originates from AMD technology and shares most of the architecture with
// AMD's family 17h, but with different CPU Vendor ID("HygonGenuine")/Family series
// number(Family 18h).
//
// For CPUID feature bits, Hygon Dhyana(family 18h) share the same definition with AMD
// family 17h.
//
// Related AMD CPUID specification is https://www.amd.com/system/files/TechDocs/25481.pdf.
// Related Hygon kernel patch can be found on
// http://lkml.kernel.org/r/5ce86123a7b9dad925ac583d88d2f921040e859b.1538583282.git.puwen@hygon.cn
if vendor_id == *b"AuthenticAMD" || vendor_id == *b"HygonGenuine" {
// These features are available on AMD arch CPUs:
enable(extended_proc_info_ecx, 6, Feature::sse4a);
enable(extended_proc_info_ecx, 21, Feature::tbm);
}
}
value
}