Skip to main content

webp/dsp/
cpu.rs

1// libwebp v1.6.0, src/dsp/cpu.c:
2//
3// Copyright 2011 Google Inc. All Rights Reserved.
4//
5// Use of this source code is governed by a BSD-style license
6// that can be found in the COPYING file in the root of the source
7// tree. An additional intellectual property rights grant can be found
8// in the file PATENTS. All contributing project authors may
9// be found in the AUTHORS file in the root of the source tree.
10// -----------------------------------------------------------------------------
11//
12// CPU detection
13//
14// Author: Christian Duvivier (cduvivier@google.com)
15
16// libwebp v1.6.0, src/dsp/cpu.h:
17//
18// Copyright 2022 Google Inc. All Rights Reserved.
19//
20// Use of this source code is governed by a BSD-style license
21// that can be found in the COPYING file in the root of the source
22// tree. An additional intellectual property rights grant can be found
23// in the file PATENTS. All contributing project authors may
24// be found in the AUTHORS file in the root of the source tree.
25// -----------------------------------------------------------------------------
26//
27//   CPU detection functions and macros.
28//
29// Author: Skal (pascal.massimino@gmail.com)
30
31//! Translation of `src/dsp/cpu.c` and `src/dsp/cpu.h` from libwebp v1.6.0.
32//!
33//! Work package: WP4 (pixel ops).
34//!
35//! `VP8GetCPUInfo` is a query, not a function pointer (ADR 0003). On x86 it
36//! answers for the running CPU as `x86CPUInfo` does. On 64-bit ARM with the
37//! `simd` feature it answers `kNEON` as `armCPUInfo` does in upstream's NEON
38//! build (WP20, ADR 0008): upstream defines `WEBP_HAVE_NEON` there, assigns
39//! `armCPUInfo`, and without `WEBP_HAVE_NEON_RTCD`, which only 32-bit ARM
40//! builds use for their `/proc/cpuinfo` test, the query reports NEON and
41//! nothing else. Elsewhere, and in the scalar build, the reference
42//! configuration leaves the pointer NULL, and the query answers `false`.
43//! The `WEBP_DSP_INIT` guards of `cpu.h` have no counterpart: they protect
44//! pointer assignments, which ADR 0003 omits. The compile-time macros of
45//! `cpu.h` (`WEBP_USE_SSE2` and the other `WEBP_HAVE_*` tests, the sanitizer
46//! and byte-order macros) become `cfg` or are not compiled in the reference
47//! configuration, which defines no SIMD, uses no sanitizer and is
48//! little-endian.
49//!
50//! # Checks not applicable
51//!
52//! These checks do not apply, or cannot be made, with the reason:
53//!
54//! 1. **x86 query on an arm64 host.** `x86cpu_info`, `check_slow_model` and the
55//!    x86 branch of `vp8_get_cpu_info` are compiled only on x86 targets. On an
56//!    arm64 host the x86 test `slow_model_table_matches_the_c_helper` and the
57//!    x86 answers of `cpu_query_matches_the_c_query` are not run. They are
58//!    type-checked for `x86_64-unknown-linux-gnu` with Clippy, and they run on
59//!    the Linux x86-64 CI host (ADR 0002).
60//! 2. **Platform queries.** `AndroidCPUInfo`, `armCPUInfo`, `wasmCPUInfo` and
61//!    `mipsCPUInfo` (`cpu.c`) are selected only by macros the reference
62//!    configuration does not define.
63//! 3. **`WEBP_DSP_INIT`, `WEBP_DSP_INIT_FUNC` and `WEBP_DSP_INIT_STUB`** are
64//!    the once-only guards around the `Init` functions and the stubs that
65//!    expose a symbol per module. No counterpart is needed (ADR 0003).
66//! 4. **Preprocessor and sanitizer macros** (`LOCAL_GCC_*`, `LOCAL_CLANG_*`,
67//!    `WEBP_NEON_*`, `WEBP_TSAN_IGNORE_FUNCTION`, `WEBP_UBSAN_*`, `WEBP_MSAN`,
68//!    `WEBP_OFFSET_PTR`, `WEBP_RESTRICT`, `__has_builtin`): compiler and
69//!    sanitizer plumbing that Rust expresses with `cfg` or has no need for.
70
71#[cfg(target_arch = "x86")]
72use core::arch::x86::__cpuid_count;
73#[cfg(target_arch = "x86_64")]
74use core::arch::x86_64::__cpuid_count;
75use std::sync::atomic::{AtomicU64, Ordering};
76
77// upstream: src/dsp/cpu.h CPUFeature
78/// A CPU feature that the query reports on. The C enumeration has no negative
79/// values, so its type is `unsigned int` (ADR 0003).
80#[must_use]
81#[repr(transparent)]
82#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
83pub struct CPUFeature(pub u32);
84
85#[expect(
86    non_upper_case_globals,
87    reason = "C enumerator names such as kSSE2 keep their case"
88)]
89impl CPUFeature {
90    // upstream: src/dsp/cpu.h kSSE2
91    pub const kSSE2: Self = Self(0);
92    // upstream: src/dsp/cpu.h kSSE3
93    pub const kSSE3: Self = Self(1);
94    // upstream: src/dsp/cpu.h kSlowSSSE3
95    pub const kSlowSSSE3: Self = Self(2);
96    // upstream: src/dsp/cpu.h kSSE4_1
97    pub const kSSE4_1: Self = Self(3);
98    // upstream: src/dsp/cpu.h kAVX
99    pub const kAVX: Self = Self(4);
100    // upstream: src/dsp/cpu.h kAVX2
101    pub const kAVX2: Self = Self(5);
102    // upstream: src/dsp/cpu.h kNEON
103    pub const kNEON: Self = Self(6);
104    // upstream: src/dsp/cpu.h kMIPS32
105    pub const kMIPS32: Self = Self(7);
106    // upstream: src/dsp/cpu.h kMIPSdspR2
107    pub const kMIPSdspR2: Self = Self(8);
108    // upstream: src/dsp/cpu.h kMSA
109    pub const kMSA: Self = Self(9);
110}
111
112// upstream: src/dsp/cpu.h VP8CPUInfo
113/// The signature of the feature query: whether the CPU supports the feature.
114pub type VP8CPUInfo = fn(CPUFeature) -> bool;
115
116// upstream: src/dsp/cpu.c GetCPUInfo
117/// Runs `cpuid` with `info_type` in EAX and ECX zero, and returns EAX, EBX,
118/// ECX and EDX.
119#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
120fn get_cpu_info(info_type: u32) -> [u32; 4] {
121    let result = __cpuid_count(info_type, 0);
122    [result.eax, result.ebx, result.ecx, result.edx]
123}
124
125// upstream: src/dsp/cpu.c CheckSlowModel
126/// Whether the display model in `info`, the EAX value of `cpuid` leaf 1, is
127/// one of the Intel models with the longer latencies of `bsr` and of some
128/// SSSE3 instructions such as `pshufb`.
129#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
130#[must_use]
131pub fn check_slow_model(info: u32) -> bool {
132    // Table listing display models with longer latencies for the bsr instruction
133    // (ie 2 cycles vs 10/16 cycles) and some SSSE3 instructions like pshufb.
134    // Refer to Intel 64 and IA-32 Architectures Optimization Reference Manual.
135    const SLOW_MODELS: [u32; 6] = [
136        0x37, 0x4a, 0x4d, // Silvermont Microarchitecture
137        0x1c, 0x26, 0x27, // Atom Microarchitecture
138    ];
139    let model = ((info & 0xf_0000) >> 12) | ((info >> 4) & 0xf);
140    let family = (info >> 8) & 0xf;
141    if family == 0x06 {
142        return SLOW_MODELS.contains(&model);
143    }
144    false
145}
146
147// upstream: src/dsp/cpu.c x86CPUInfo
148/// The x86 query. The reference configuration installs it on x86 targets.
149#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
150#[expect(
151    clippy::cast_possible_wrap,
152    reason = "cpuid returns the highest leaf in the EAX of the C int that is compared with 1 and 7"
153)]
154fn x86cpu_info(feature: CPUFeature) -> bool {
155    const VENDOR_ID_INTEL_EBX: u32 = 0x756e_6547; // uneG
156    const VENDOR_ID_INTEL_EDX: u32 = 0x4965_6e69; // Ieni
157    const VENDOR_ID_INTEL_ECX: u32 = 0x6c65_746e; // letn
158    // get the highest feature value cpuid supports
159    let cpu_info = get_cpu_info(0);
160    let max_cpuid_value = cpu_info[0] as i32;
161    if max_cpuid_value < 1 {
162        return false;
163    }
164    let is_intel = cpu_info[1] == VENDOR_ID_INTEL_EBX
165        && cpu_info[2] == VENDOR_ID_INTEL_ECX
166        && cpu_info[3] == VENDOR_ID_INTEL_EDX; // genuine Intel?
167
168    let cpu_info = get_cpu_info(1);
169    if feature == CPUFeature::kSSE2 {
170        return cpu_info[3] & (1 << 26) != 0;
171    }
172    if feature == CPUFeature::kSSE3 {
173        return cpu_info[2] & (1 << 0) != 0;
174    }
175    if feature == CPUFeature::kSlowSSSE3 {
176        if is_intel && cpu_info[2] & (1 << 9) != 0 {
177            // SSSE3?
178            return check_slow_model(cpu_info[0]);
179        }
180        return false;
181    }
182    if feature == CPUFeature::kSSE4_1 {
183        return cpu_info[2] & (1 << 19) != 0;
184    }
185    if feature == CPUFeature::kAVX {
186        // bits 27 (OSXSAVE) & 28 (256-bit AVX)
187        if cpu_info[2] & 0x1800_0000 == 0x1800_0000 {
188            // XMM state and YMM state enabled by the OS. The C code reads XCR0
189            // with xgetbv and tests bits 1 and 2; the standard library's AVX
190            // detection performs that same test, and it is safe Rust.
191            return std::is_x86_feature_detected!("avx");
192        }
193    }
194    if feature == CPUFeature::kAVX2 && x86cpu_info(CPUFeature::kAVX) && max_cpuid_value >= 7 {
195        let cpu_info = get_cpu_info(7);
196        return cpu_info[1] & (1 << 5) != 0;
197    }
198    false
199}
200
201// upstream: src/dsp/cpu.c VP8GetCPUInfo
202/// Reports whether the running CPU supports `feature`.
203///
204/// On x86 the answer comes from `cpuid`, as in `x86CPUInfo`. On other targets
205/// the reference configuration has no query, `VP8GetCPUInfo` is NULL, and the
206/// answer is `false` for every feature. The NULL pointer itself exists only at
207/// the C ABI (ADR 0004).
208#[cfg(any(target_arch = "x86", target_arch = "x86_64"))]
209#[must_use]
210pub fn vp8_get_cpu_info(feature: CPUFeature) -> bool {
211    #[cfg(feature = "oracle")]
212    if !gate_level_allows(feature) {
213        return false;
214    }
215    x86cpu_info(feature)
216}
217
218/// Whether the differential gate's instruction-set level lets the query
219/// report `feature` (ADR 0008). The environment variable `LIBWEBP_SIMD_LEVEL`
220/// names the level of a `tools/check.py --oracle` mode: unset, `avx2` and
221/// `neon` report every feature as the CPU does; `sse41` reports nothing above
222/// `kSSE4_1`; `sse2` reports `kSSE2` alone. The oracle's
223/// `tools/oracle/probe_support/simd_level.c` wraps upstream's `VP8GetCPUInfo`
224/// with the same rule before `main`, so both sides select the variants of the
225/// same level. Compiled only with the `oracle` feature, which no ordinary
226/// build enables; no C counterpart.
227#[cfg(all(feature = "oracle", any(target_arch = "x86", target_arch = "x86_64")))]
228fn gate_level_allows(feature: CPUFeature) -> bool {
229    match std::env::var("LIBWEBP_SIMD_LEVEL").as_deref() {
230        Err(_) | Ok("" | "avx2" | "neon") => true,
231        Ok("sse41") => feature <= CPUFeature::kSSE4_1,
232        Ok("sse2") => feature == CPUFeature::kSSE2,
233        Ok(level) => panic!("LIBWEBP_SIMD_LEVEL={level}: unknown level"),
234    }
235}
236
237// upstream: src/dsp/cpu.c armCPUInfo
238/// The ARM query of upstream's NEON build: NEON is reported, every other
239/// feature is not. `WEBP_HAVE_NEON_RTCD`, the run-time test of 32-bit ARM
240/// Linux builds, is not defined for 64-bit ARM.
241#[cfg(all(feature = "simd", target_arch = "aarch64"))]
242fn arm_cpu_info(feature: CPUFeature) -> bool {
243    feature == CPUFeature::kNEON
244}
245
246// upstream: src/dsp/cpu.c VP8GetCPUInfo
247/// Reports whether the running CPU supports `feature`. On 64-bit ARM with the
248/// `simd` feature the answer is `armCPUInfo`'s: NEON only, as in upstream's
249/// NEON build (ADR 0008).
250#[cfg(all(feature = "simd", target_arch = "aarch64"))]
251#[must_use]
252pub fn vp8_get_cpu_info(feature: CPUFeature) -> bool {
253    arm_cpu_info(feature)
254}
255
256// upstream: src/dsp/cpu.c VP8GetCPUInfo
257/// Reports whether the running CPU supports `feature`. Without an x86 query,
258/// the reference configuration's NULL pointer reports no feature.
259#[cfg(not(any(
260    target_arch = "x86",
261    target_arch = "x86_64",
262    all(feature = "simd", target_arch = "aarch64")
263)))]
264#[must_use]
265pub fn vp8_get_cpu_info(_feature: CPUFeature) -> bool {
266    false
267}
268
269//------------------------------------------------------------------------------
270// Runtime selection of the SIMD variants (ADR 0008). No C counterpart as a
271// function: C's `WEBP_DSP_INIT` re-runs an `Init` function when `VP8GetCPUInfo`
272// changed since its last run, and the `Init` function assigns the dispatch
273// pointers from the query's answers.
274
275/// The CPU features that the dispatch functions select the SIMD variants by
276/// (ADR 0008). Each x86 flag answers as the `Init` functions' queries do,
277/// through the query behind the C ABI's `VP8GetCPUInfo` pointer: `false` for a
278/// `NULL` pointer (`-noasm`), `cpuid` for the translation's own query, and the
279/// caller's function for a query it installed. `neon` is true on 64-bit ARM
280/// whatever the pointer says, where upstream compiles the NEON code in and
281/// omits the C code it replaces (`WEBP_NEON_OMIT_C_CODE`).
282#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
283#[expect(
284    clippy::struct_excessive_bools,
285    reason = "one flag per CPU feature, as the C query answers them"
286)]
287pub struct Features {
288    /// `VP8GetCPUInfo(kSSE2)`.
289    pub sse2: bool,
290    /// `VP8GetCPUInfo(kSSE3)`.
291    pub sse3: bool,
292    /// `VP8GetCPUInfo(kSlowSSSE3)`.
293    pub slow_ssse3: bool,
294    /// `VP8GetCPUInfo(kSSE4_1)`.
295    pub sse4_1: bool,
296    /// `VP8GetCPUInfo(kAVX)`.
297    pub avx: bool,
298    /// `VP8GetCPUInfo(kAVX2)`.
299    pub avx2: bool,
300    /// NEON, always on 64-bit ARM.
301    pub neon: bool,
302    /// `VP8GetCPUInfo(kNEON)`, `false` for a `NULL` pointer. `VP8EncDspCostInit`
303    /// (`cost.c`) is the one `Init` function that selects its NEON variants by
304    /// the query alone, without `WEBP_NEON_OMIT_C_CODE`, so `-noasm` turns them
305    /// off; every other selection uses [`Features::neon`] (WP20, ADR 0008).
306    pub query_neon: bool,
307}
308
309impl Features {
310    const SSE2: u32 = 1 << 0;
311    const SSE3: u32 = 1 << 1;
312    const SLOW_SSSE3: u32 = 1 << 2;
313    const SSE4_1: u32 = 1 << 3;
314    const AVX: u32 = 1 << 4;
315    const AVX2: u32 = 1 << 5;
316    const NEON: u32 = 1 << 6;
317    const QUERY_NEON: u32 = 1 << 7;
318    /// Marks a computed record in the cache word.
319    const VALID: u32 = 1 << 31;
320
321    fn bits(self) -> u32 {
322        let mut bits = 0;
323        for (flag, bit) in [
324            (self.sse2, Self::SSE2),
325            (self.sse3, Self::SSE3),
326            (self.slow_ssse3, Self::SLOW_SSSE3),
327            (self.sse4_1, Self::SSE4_1),
328            (self.avx, Self::AVX),
329            (self.avx2, Self::AVX2),
330            (self.neon, Self::NEON),
331            (self.query_neon, Self::QUERY_NEON),
332        ] {
333            if flag {
334                bits |= bit;
335            }
336        }
337        bits
338    }
339
340    #[inline]
341    fn from_bits(bits: u32) -> Self {
342        Self {
343            sse2: bits & Self::SSE2 != 0,
344            sse3: bits & Self::SSE3 != 0,
345            slow_ssse3: bits & Self::SLOW_SSSE3 != 0,
346            sse4_1: bits & Self::SSE4_1 != 0,
347            avx: bits & Self::AVX != 0,
348            avx2: bits & Self::AVX2 != 0,
349            neon: bits & Self::NEON != 0,
350            query_neon: bits & Self::QUERY_NEON != 0,
351        }
352    }
353}
354
355/// The cached record: the token of the `VP8GetCPUInfo` pointer it was computed
356/// for in the high word, the feature bits with [`Features::VALID`] in the low
357/// word. One atomic word, so a reader never pairs a token with another
358/// pointer's bits.
359static FEATURES_CACHE: AtomicU64 = AtomicU64::new(0);
360
361/// The features the dispatch functions select by (ADR 0008), computed on the
362/// first call and again whenever the C ABI's `VP8GetCPUInfo` pointer has
363/// changed since, as `WEBP_DSP_INIT` re-runs the `Init` functions then.
364///
365/// The test of the cached record is inlined into each dispatch function, so a
366/// call with an unchanged pointer reads the pointer and the cache word and
367/// tests the one flag it selects by, where upstream reads its dispatch
368/// pointer; the computation runs out of line ([`refresh_features`]).
369#[inline]
370#[must_use]
371pub fn features() -> Features {
372    let token = crate::abi::decode::cpu_query_token();
373    let cached = FEATURES_CACHE.load(Ordering::Relaxed);
374    #[expect(
375        clippy::cast_possible_truncation,
376        reason = "the low word of the cache holds the feature bits"
377    )]
378    let bits = cached as u32;
379    let cached_token = (cached >> 32) as u32;
380    if cached_token == token && bits & Features::VALID != 0 {
381        return Features::from_bits(bits);
382    }
383    refresh_features(token)
384}
385
386/// Computes the record for the pointer of `token` and caches it: the first
387/// call of [`features`], and the first after the pointer changed.
388#[cold]
389#[inline(never)]
390fn refresh_features(token: u32) -> Features {
391    let computed = compute_features();
392    FEATURES_CACHE.store(
393        (u64::from(token) << 32) | u64::from(computed.bits() | Features::VALID),
394        Ordering::Relaxed,
395    );
396    computed
397}
398
399/// The record for the current `VP8GetCPUInfo` pointer.
400fn compute_features() -> Features {
401    let query =
402        |feature: CPUFeature| crate::abi::decode::cpu_feature_query(feature).unwrap_or(false);
403    Features {
404        sse2: query(CPUFeature::kSSE2),
405        sse3: query(CPUFeature::kSSE3),
406        slow_ssse3: query(CPUFeature::kSlowSSSE3),
407        sse4_1: query(CPUFeature::kSSE4_1),
408        avx: query(CPUFeature::kAVX),
409        avx2: query(CPUFeature::kAVX2),
410        neon: cfg!(target_arch = "aarch64"),
411        query_neon: query(CPUFeature::kNEON),
412    }
413}