Coverage Report

Created: 2026-06-10 06:30

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/src/libavif/ext/libyuv/source/cpu_id.cc
Line
Count
Source
1
/*
2
 *  Copyright 2011 The LibYuv Project Authors. All rights reserved.
3
 *
4
 *  Use of this source code is governed by a BSD-style license
5
 *  that can be found in the LICENSE file in the root of the source
6
 *  tree. An additional intellectual property rights grant can be found
7
 *  in the file PATENTS. All contributing project authors may
8
 *  be found in the AUTHORS file in the root of the source tree.
9
 */
10
11
#include "libyuv/cpu_id.h"
12
13
#if defined(_MSC_VER)
14
#include <intrin.h>  // For __cpuidex()
15
#endif
16
#if !defined(__pnacl__) && !defined(__CLR_VER) &&                           \
17
    !defined(__native_client__) && (defined(_M_IX86) || defined(_M_X64)) && \
18
    defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 160040219)
19
#include <immintrin.h>  // For _xgetbv()
20
#endif
21
22
// For ArmCpuCaps() but unittested on all platforms
23
#include <stdio.h>  // For fopen()
24
#include <string.h>
25
26
#if defined(__linux__) && (defined(__aarch64__) || defined(__loongarch__))
27
#include <sys/auxv.h>  // For getauxval()
28
#endif
29
30
#if defined(_WIN32) && defined(__aarch64__)
31
#undef WIN32_LEAN_AND_MEAN
32
#define WIN32_LEAN_AND_MEAN
33
#undef WIN32_EXTRA_LEAN
34
#define WIN32_EXTRA_LEAN
35
#include <windows.h>  // For IsProcessorFeaturePresent()
36
#endif
37
38
#if defined(__APPLE__) && defined(__aarch64__)
39
#include <sys/sysctl.h>  // For sysctlbyname()
40
#endif
41
42
#ifdef __cplusplus
43
namespace libyuv {
44
extern "C" {
45
#endif
46
47
// For functions that use the stack and have runtime checks for overflow,
48
// use SAFEBUFFERS to avoid additional check.
49
#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 160040219) && \
50
    !defined(__clang__)
51
#define SAFEBUFFERS __declspec(safebuffers)
52
#else
53
#define SAFEBUFFERS
54
#endif
55
56
// cpu_info_ variable for SIMD instruction sets detected.
57
LIBYUV_API int cpu_info_ = 0;
58
59
// Low level cpuid for X86.
60
#if (defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \
61
     defined(__x86_64__)) &&                                     \
62
    !defined(__pnacl__) && !defined(__CLR_VER)
63
LIBYUV_API
64
15
void CpuId(int info_eax, int info_ecx, int* cpu_info) {
65
#if defined(_MSC_VER)
66
// Visual C version uses intrinsic or inline x86 assembly.
67
#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 160040219)
68
  __cpuidex(cpu_info, info_eax, info_ecx);
69
#elif defined(_M_IX86)
70
  __asm {
71
    mov        eax, info_eax
72
    mov        ecx, info_ecx
73
    mov        edi, cpu_info
74
    cpuid
75
    mov        [edi], eax
76
    mov        [edi + 4], ebx
77
    mov        [edi + 8], ecx
78
    mov        [edi + 12], edx
79
  }
80
#else  // Visual C but not x86
81
  if (info_ecx == 0) {
82
    __cpuid(cpu_info, info_eax);
83
  } else {
84
    cpu_info[3] = cpu_info[2] = cpu_info[1] = cpu_info[0] = 0u;
85
  }
86
#endif
87
// GCC version uses inline x86 assembly.
88
#else  // defined(_MSC_VER)
89
15
  int info_ebx, info_edx;
90
15
  asm volatile(
91
#if defined(__i386__) && defined(__PIC__)
92
      // Preserve ebx for fpic 32 bit.
93
      "mov         %%ebx, %%edi                  \n"
94
      "cpuid                                     \n"
95
      "xchg        %%edi, %%ebx                  \n"
96
      : "=D"(info_ebx),
97
#else
98
15
      "cpuid                                     \n"
99
15
      : "=b"(info_ebx),
100
15
#endif  //  defined( __i386__) && defined(__PIC__)
101
15
        "+a"(info_eax), "+c"(info_ecx), "=d"(info_edx));
102
15
  cpu_info[0] = info_eax;
103
15
  cpu_info[1] = info_ebx;
104
15
  cpu_info[2] = info_ecx;
105
15
  cpu_info[3] = info_edx;
106
15
#endif  // defined(_MSC_VER)
107
15
}
108
#else  // (defined(_M_IX86) || defined(_M_X64) ...
109
LIBYUV_API
110
void CpuId(int eax, int ecx, int* cpu_info) {
111
  (void)eax;
112
  (void)ecx;
113
  cpu_info[0] = cpu_info[1] = cpu_info[2] = cpu_info[3] = 0;
114
}
115
#endif
116
117
// For VS2010 and earlier emit can be used:
118
//   _asm _emit 0x0f _asm _emit 0x01 _asm _emit 0xd0  // For VS2010 and earlier.
119
//  __asm {
120
//    xor        ecx, ecx    // xcr 0
121
//    xgetbv
122
//    mov        xcr0, eax
123
//  }
124
// For VS2013 and earlier 32 bit, the _xgetbv(0) optimizer produces bad code.
125
// https://code.google.com/p/libyuv/issues/detail?id=529
126
#if defined(_M_IX86) && defined(_MSC_VER) && (_MSC_VER < 1900)
127
#pragma optimize("g", off)
128
#endif
129
#if (defined(_M_IX86) || defined(_M_X64) || defined(__i386__) || \
130
     defined(__x86_64__)) &&                                     \
131
    !defined(__pnacl__) && !defined(__CLR_VER) && !defined(__native_client__)
132
// X86 CPUs have xgetbv to detect OS saves high parts of ymm registers.
133
6
static int GetXCR0() {
134
6
  int xcr0 = 0;
135
#if defined(_MSC_FULL_VER) && (_MSC_FULL_VER >= 160040219)
136
  xcr0 = (int)_xgetbv(0);  // VS2010 SP1 required.  NOLINT
137
#elif defined(__i386__) || defined(__x86_64__)
138
  asm(".byte 0x0f, 0x01, 0xd0" : "=a"(xcr0) : "c"(0) : "%edx");
139
6
#endif  // defined(__i386__) || defined(__x86_64__)
140
6
  return xcr0;
141
6
}
142
#else
143
// xgetbv unavailable to query for OSSave support.  Return 0.
144
#define GetXCR0() 0
145
#endif  // defined(_M_IX86) || defined(_M_X64) ..
146
// Return optimization to previous setting.
147
#if defined(_M_IX86) && defined(_MSC_VER) && (_MSC_VER < 1900)
148
#pragma optimize("g", on)
149
#endif
150
151
static int cpuinfo_search(const char* cpuinfo_line,
152
                          const char* needle,
153
0
                          int needle_len) {
154
0
  const char* p = strstr(cpuinfo_line, needle);
155
0
  return p && (p[needle_len] == ' ' || p[needle_len] == '\n');
156
0
}
157
158
// Based on libvpx arm_cpudetect.c
159
// For Arm, but public to allow testing on any CPU
160
0
LIBYUV_API SAFEBUFFERS int ArmCpuCaps(const char* cpuinfo_name) {
161
0
  char cpuinfo_line[512];
162
0
  FILE* f = fopen(cpuinfo_name, "re");
163
0
  if (!f) {
164
    // Assume Neon if /proc/cpuinfo is unavailable.
165
    // This will occur for Chrome sandbox for Pepper or Render process.
166
0
    return kCpuHasNEON;
167
0
  }
168
0
  memset(cpuinfo_line, 0, sizeof(cpuinfo_line));
169
0
  int features = 0;
170
0
  while (fgets(cpuinfo_line, sizeof(cpuinfo_line), f)) {
171
0
    if (memcmp(cpuinfo_line, "Features", 8) == 0) {
172
0
      if (cpuinfo_search(cpuinfo_line, " neon", 5)) {
173
0
        features |= kCpuHasNEON;
174
0
      }
175
0
    }
176
0
  }
177
0
  fclose(f);
178
0
  return features;
179
0
}
180
181
#ifdef __aarch64__
182
#ifdef __linux__
183
// Define hwcap values ourselves: building with an old auxv header where these
184
// hwcap values are not defined should not prevent features from being enabled.
185
#define YUV_AARCH64_HWCAP_ASIMDDP (1UL << 20)
186
#define YUV_AARCH64_HWCAP_SVE (1UL << 22)
187
#define YUV_AARCH64_HWCAP2_SVE2 (1UL << 1)
188
#define YUV_AARCH64_HWCAP2_SVEF32MM (1UL << 10)
189
#define YUV_AARCH64_HWCAP2_I8MM (1UL << 13)
190
#define YUV_AARCH64_HWCAP2_SME (1UL << 23)
191
#define YUV_AARCH64_HWCAP2_SME2 (1UL << 37)
192
193
// For AArch64, but public to allow testing on any CPU.
194
LIBYUV_API SAFEBUFFERS int AArch64CpuCaps(unsigned long hwcap,
195
                                          unsigned long hwcap2) {
196
  // Neon is mandatory on AArch64, so enable regardless of hwcaps.
197
  int features = kCpuHasNEON;
198
199
  // Don't try to enable later extensions unless earlier extensions are also
200
  // reported available. Some of these constraints aren't strictly required by
201
  // the architecture, but are satisfied by all micro-architectures of
202
  // interest. This also avoids an issue on some emulators where true
203
  // architectural constraints are not satisfied, e.g. SVE2 may be reported as
204
  // available while SVE is not.
205
  if (hwcap & YUV_AARCH64_HWCAP_ASIMDDP) {
206
    features |= kCpuHasNeonDotProd;
207
    if (hwcap2 & YUV_AARCH64_HWCAP2_I8MM) {
208
      features |= kCpuHasNeonI8MM;
209
      if (hwcap & YUV_AARCH64_HWCAP_SVE) {
210
        features |= kCpuHasSVE;
211
        if (hwcap2 & YUV_AARCH64_HWCAP2_SVEF32MM) {
212
          features |= kCpuHasSVEF32MM;
213
        }
214
        if (hwcap2 & YUV_AARCH64_HWCAP2_SVE2) {
215
          features |= kCpuHasSVE2;
216
        }
217
      }
218
      // SME may be present without SVE
219
      if (hwcap2 & YUV_AARCH64_HWCAP2_SME) {
220
        features |= kCpuHasSME;
221
        if (hwcap2 & YUV_AARCH64_HWCAP2_SME2) {
222
          features |= kCpuHasSME2;
223
        }
224
      }
225
    }
226
  }
227
  return features;
228
}
229
230
#elif defined(_WIN32)
231
// For AArch64, but public to allow testing on any CPU.
232
LIBYUV_API SAFEBUFFERS int AArch64CpuCaps() {
233
  // Neon is mandatory on AArch64, so enable unconditionally.
234
  int features = kCpuHasNEON;
235
236
  // For more information on IsProcessorFeaturePresent(), see:
237
  // https://learn.microsoft.com/en-us/windows/win32/api/processthreadsapi/nf-processthreadsapi-isprocessorfeaturepresent#parameters
238
#ifdef PF_ARM_V82_DP_INSTRUCTIONS_AVAILABLE
239
  if (IsProcessorFeaturePresent(PF_ARM_V82_DP_INSTRUCTIONS_AVAILABLE)) {
240
    features |= kCpuHasNeonDotProd;
241
  }
242
#endif
243
  // No Neon I8MM or SVE feature detection available here at time of writing.
244
  return features;
245
}
246
247
#elif defined(__APPLE__)
248
static bool have_feature(const char* feature) {
249
  // For more information on sysctlbyname(), see:
250
  // https://developer.apple.com/documentation/kernel/1387446-sysctlbyname/determining_instruction_set_characteristics
251
  int64_t feature_present = 0;
252
  size_t size = sizeof(feature_present);
253
  if (sysctlbyname(feature, &feature_present, &size, NULL, 0) != 0) {
254
    return false;
255
  }
256
  return feature_present;
257
}
258
259
// For AArch64, but public to allow testing on any CPU.
260
LIBYUV_API SAFEBUFFERS int AArch64CpuCaps() {
261
  // Neon is mandatory on AArch64, so enable unconditionally.
262
  int features = kCpuHasNEON;
263
264
  if (have_feature("hw.optional.arm.FEAT_DotProd")) {
265
    features |= kCpuHasNeonDotProd;
266
    if (have_feature("hw.optional.arm.FEAT_I8MM")) {
267
      features |= kCpuHasNeonI8MM;
268
      if (have_feature("hw.optional.arm.FEAT_SME")) {
269
        features |= kCpuHasSME;
270
        if (have_feature("hw.optional.arm.FEAT_SME2")) {
271
          features |= kCpuHasSME2;
272
        }
273
      }
274
    }
275
  }
276
  // No SVE feature detection available here at time of writing.
277
  return features;
278
}
279
280
#else  // !defined(__linux__) && !defined(_WIN32) && !defined(__APPLE__)
281
// For AArch64, but public to allow testing on any CPU.
282
LIBYUV_API SAFEBUFFERS int AArch64CpuCaps() {
283
  // Neon is mandatory on AArch64, so enable unconditionally.
284
  int features = kCpuHasNEON;
285
286
  // TODO(libyuv:980) support feature detection on other platforms.
287
288
  return features;
289
}
290
#endif
291
#endif  // defined(__aarch64__)
292
293
0
LIBYUV_API SAFEBUFFERS int RiscvCpuCaps(const char* cpuinfo_name) {
294
0
  char cpuinfo_line[512];
295
0
  int flag = 0;
296
0
  FILE* f = fopen(cpuinfo_name, "re");
297
0
  if (!f) {
298
#if defined(__riscv_vector)
299
    // Assume RVV if /proc/cpuinfo is unavailable.
300
    // This will occur for Chrome sandbox for Pepper or Render process.
301
    return kCpuHasRVV;
302
#else
303
0
    return 0;
304
0
#endif
305
0
  }
306
0
  memset(cpuinfo_line, 0, sizeof(cpuinfo_line));
307
0
  while (fgets(cpuinfo_line, sizeof(cpuinfo_line), f)) {
308
0
    if (memcmp(cpuinfo_line, "isa", 3) == 0) {
309
      // ISA string must begin with rv64{i,e,g} for a 64-bit processor.
310
0
      char* isa = strstr(cpuinfo_line, "rv64");
311
0
      if (isa) {
312
0
        size_t isa_len = strlen(isa);
313
0
        char* extensions;
314
0
        size_t extensions_len = 0;
315
0
        size_t std_isa_len;
316
        // Remove the new-line character at the end of string
317
0
        if (isa[isa_len - 1] == '\n') {
318
0
          isa[--isa_len] = '\0';
319
0
        }
320
        // 5 ISA characters
321
0
        if (isa_len < 5) {
322
0
          fclose(f);
323
0
          return 0;
324
0
        }
325
        // Skip {i,e,g} canonical checking.
326
        // Skip rvxxx
327
0
        isa += 5;
328
        // Find the very first occurrence of 's', 'x' or 'z'.
329
        // To detect multi-letter standard, non-standard, and
330
        // supervisor-level extensions.
331
0
        extensions = strpbrk(isa, "zxs");
332
0
        if (extensions) {
333
0
          extensions_len = strlen(extensions);
334
          // Multi-letter extensions are seperated by a single underscore
335
          // as described in RISC-V User-Level ISA V2.2.
336
0
          char* ext = extensions;
337
0
          while (ext) {
338
0
            char* next = strchr(ext, '_');
339
0
            if (next) {
340
0
              *next = '\0';
341
0
              next++;
342
0
            }
343
            // Search for the ZVFH (Vector FP16) extension.
344
0
            if (!strcmp(ext, "zvfh")) {
345
0
              flag |= kCpuHasRVVZVFH;
346
0
            }
347
0
            ext = next;
348
0
          }
349
0
        }
350
0
        std_isa_len = isa_len - extensions_len - 5;
351
        // Detect the v in the standard single-letter extensions.
352
0
        if (memchr(isa, 'v', std_isa_len)) {
353
          // The RVV implied the F extension.
354
0
          flag |= kCpuHasRVV;
355
0
        }
356
0
      }
357
0
    }
358
#if defined(__riscv_vector)
359
    // Assume RVV if /proc/cpuinfo is from x86 host running QEMU.
360
    else if ((memcmp(cpuinfo_line, "vendor_id\t: GenuineIntel", 24) == 0) ||
361
             (memcmp(cpuinfo_line, "vendor_id\t: AuthenticAMD", 24) == 0)) {
362
      fclose(f);
363
      return kCpuHasRVV;
364
    }
365
#endif
366
0
  }
367
0
  fclose(f);
368
0
  return flag;
369
0
}
370
371
#if defined(__loongarch__) && defined(__linux__)
372
// Define hwcap values ourselves: building with an old auxv header where these
373
// hwcap values are not defined should not prevent features from being enabled.
374
#define YUV_LOONGARCH_HWCAP_LSX (1 << 4)
375
#define YUV_LOONGARCH_HWCAP_LASX (1 << 5)
376
377
LIBYUV_API SAFEBUFFERS int LoongArchCpuCaps(void) {
378
  int flag = 0;
379
  unsigned long hwcap = getauxval(AT_HWCAP);
380
381
  if (hwcap & YUV_LOONGARCH_HWCAP_LSX)
382
    flag |= kCpuHasLSX;
383
384
  if (hwcap & YUV_LOONGARCH_HWCAP_LASX)
385
    flag |= kCpuHasLASX;
386
  return flag;
387
}
388
#endif
389
390
3
static SAFEBUFFERS int GetCpuFlags(void) {
391
3
  int cpu_info = 0;
392
3
#if !defined(__pnacl__) && !defined(__CLR_VER) &&                   \
393
3
    (defined(__x86_64__) || defined(_M_X64) || defined(__i386__) || \
394
3
     defined(_M_IX86))
395
3
  int cpu_info0[4] = {0, 0, 0, 0};
396
3
  int cpu_info1[4] = {0, 0, 0, 0};
397
3
  int cpu_info7[4] = {0, 0, 0, 0};
398
3
  int cpu_einfo7[4] = {0, 0, 0, 0};
399
3
  int cpu_info24[4] = {0, 0, 0, 0};
400
3
  int cpu_amdinfo21[4] = {0, 0, 0, 0};
401
3
  CpuId(0, 0, cpu_info0);
402
3
  CpuId(1, 0, cpu_info1);
403
3
  if (cpu_info0[0] >= 7) {
404
3
    CpuId(7, 0, cpu_info7);
405
3
    CpuId(7, 1, cpu_einfo7);
406
3
    CpuId(0x80000021, 0, cpu_amdinfo21);
407
3
  }
408
3
  if (cpu_info0[0] >= 0x24) {
409
0
    CpuId(0x24, 0, cpu_info24);
410
0
  }
411
3
  cpu_info = kCpuHasX86 | ((cpu_info1[3] & 0x04000000) ? kCpuHasSSE2 : 0) |
412
3
             ((cpu_info1[2] & 0x00000200) ? kCpuHasSSSE3 : 0) |
413
3
             ((cpu_info1[2] & 0x00080000) ? kCpuHasSSE41 : 0) |
414
3
             ((cpu_info1[2] & 0x00100000) ? kCpuHasSSE42 : 0) |
415
3
             ((cpu_info7[1] & 0x00000200) ? kCpuHasERMS : 0) |
416
3
             ((cpu_info7[3] & 0x00000010) ? kCpuHasFSMR : 0);
417
418
  // AVX requires OS saves YMM registers.
419
3
  if (((cpu_info1[2] & 0x1c000000) == 0x1c000000) &&  // AVX and OSXSave
420
3
      ((GetXCR0() & 6) == 6)) {  // Test OS saves YMM registers
421
3
    cpu_info |= kCpuHasAVX | ((cpu_info7[1] & 0x00000020) ? kCpuHasAVX2 : 0) |
422
3
                ((cpu_info1[2] & 0x00001000) ? kCpuHasFMA3 : 0) |
423
3
                ((cpu_info1[2] & 0x20000000) ? kCpuHasF16C : 0) |
424
3
                ((cpu_einfo7[0] & 0x00000010) ? kCpuHasAVXVNNI : 0) |
425
3
                ((cpu_einfo7[3] & 0x00000010) ? kCpuHasAVXVNNIINT8 : 0);
426
427
3
    cpu_info |= ((cpu_amdinfo21[0] & 0x00008000) ? kCpuHasERMS : 0);
428
429
    // Detect AVX512bw
430
3
    if ((GetXCR0() & 0xe0) == 0xe0 && (cpu_info7[1] & 0x00010000)) {
431
0
      cpu_info |= ((cpu_info7[1] & 0x40000000) ? kCpuHasAVX512BW : 0) |
432
0
                  ((cpu_info7[1] & 0x80000000) ? kCpuHasAVX512VL : 0) |
433
0
                  ((cpu_info7[2] & 0x00000002) ? kCpuHasAVX512VBMI : 0) |
434
0
                  ((cpu_info7[2] & 0x00000040) ? kCpuHasAVX512VBMI2 : 0) |
435
0
                  ((cpu_info7[2] & 0x00000800) ? kCpuHasAVX512VNNI : 0) |
436
0
                  ((cpu_info7[2] & 0x00001000) ? kCpuHasAVX512VBITALG : 0) |
437
0
                  ((cpu_einfo7[3] & 0x00080000) ? kCpuHasAVX10 : 0) |
438
0
                  ((cpu_info7[3] & 0x02000000) ? kCpuHasAMXINT8 : 0);
439
0
      if (cpu_info0[0] >= 0x24 && (cpu_einfo7[3] & 0x00080000)) {
440
0
        cpu_info |= ((cpu_info24[1] & 0xFF) >= 2) ? kCpuHasAVX10_2 : 0;
441
0
      }
442
0
    }
443
3
  }
444
3
#endif
445
#if defined(__loongarch__) && defined(__linux__)
446
  cpu_info = LoongArchCpuCaps();
447
  cpu_info |= kCpuHasLOONGARCH;
448
#endif
449
#if defined(__aarch64__)
450
#if defined(__linux__)
451
  // getauxval is supported since Android SDK version 18, minimum at time of
452
  // writing is 21, so should be safe to always use this. If getauxval is
453
  // somehow disabled then getauxval returns 0, which will leave Neon enabled
454
  // since Neon is mandatory on AArch64.
455
  unsigned long hwcap = getauxval(AT_HWCAP);
456
  unsigned long hwcap2 = getauxval(AT_HWCAP2);
457
  cpu_info = AArch64CpuCaps(hwcap, hwcap2);
458
#else
459
  cpu_info = AArch64CpuCaps();
460
#endif
461
  cpu_info |= kCpuHasARM;
462
#endif  // __aarch64__
463
#if defined(__arm__)
464
  // gcc -mfpu=neon defines __ARM_NEON__
465
  // __ARM_NEON__ generates code that requires Neon.  NaCL also requires Neon.
466
  // For Linux, /proc/cpuinfo can be tested but without that assume Neon.
467
  // Linux arm parse text file for neon detect.
468
#if defined(__linux__)
469
  cpu_info = ArmCpuCaps("/proc/cpuinfo");
470
#elif defined(__ARM_NEON__)
471
  cpu_info = kCpuHasNEON;
472
#else
473
  cpu_info = 0;
474
#endif
475
  cpu_info |= kCpuHasARM;
476
#endif  // __arm__
477
#if defined(__riscv) && defined(__linux__)
478
  cpu_info = RiscvCpuCaps("/proc/cpuinfo");
479
  cpu_info |= kCpuHasRISCV;
480
#endif  // __riscv
481
3
  cpu_info |= kCpuInitialized;
482
3
  return cpu_info;
483
3
}
484
485
// Note that use of this function is not thread safe.
486
LIBYUV_API
487
3
int MaskCpuFlags(int enable_flags) {
488
3
  int cpu_info = GetCpuFlags() & enable_flags;
489
3
  SetCpuFlags(cpu_info);
490
3
  return cpu_info;
491
3
}
492
493
LIBYUV_API
494
3
int InitCpuFlags(void) {
495
3
  return MaskCpuFlags(-1);
496
3
}
497
498
#ifdef __cplusplus
499
}  // extern "C"
500
}  // namespace libyuv
501
#endif