Coverage Report

Created: 2026-03-06 06:33

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
20
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
20
  int info_ebx, info_edx;
90
20
  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
20
      "cpuid                                     \n"
99
20
      : "=b"(info_ebx),
100
20
#endif  //  defined( __i386__) && defined(__PIC__)
101
20
        "+a"(info_eax), "+c"(info_ecx), "=d"(info_edx));
102
20
  cpu_info[0] = info_eax;
103
20
  cpu_info[1] = info_ebx;
104
20
  cpu_info[2] = info_ecx;
105
20
  cpu_info[3] = info_edx;
106
20
#endif  // defined(_MSC_VER)
107
20
}
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
8
static int GetXCR0() {
134
8
  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
8
#endif  // defined(__i386__) || defined(__x86_64__)
140
8
  return xcr0;
141
8
}
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
          // Multi-letter extensions are seperated by a single underscore
334
          // as described in RISC-V User-Level ISA V2.2.
335
0
          char* ext = strtok(extensions, "_");
336
0
          extensions_len = strlen(extensions);
337
0
          while (ext) {
338
            // Search for the ZVFH (Vector FP16) extension.
339
0
            if (!strcmp(ext, "zvfh")) {
340
0
              flag |= kCpuHasRVVZVFH;
341
0
            }
342
0
            ext = strtok(NULL, "_");
343
0
          }
344
0
        }
345
0
        std_isa_len = isa_len - extensions_len - 5;
346
        // Detect the v in the standard single-letter extensions.
347
0
        if (memchr(isa, 'v', std_isa_len)) {
348
          // The RVV implied the F extension.
349
0
          flag |= kCpuHasRVV;
350
0
        }
351
0
      }
352
0
    }
353
#if defined(__riscv_vector)
354
    // Assume RVV if /proc/cpuinfo is from x86 host running QEMU.
355
    else if ((memcmp(cpuinfo_line, "vendor_id\t: GenuineIntel", 24) == 0) ||
356
             (memcmp(cpuinfo_line, "vendor_id\t: AuthenticAMD", 24) == 0)) {
357
      fclose(f);
358
      return kCpuHasRVV;
359
    }
360
#endif
361
0
  }
362
0
  fclose(f);
363
0
  return flag;
364
0
}
365
366
#if defined(__loongarch__) && defined(__linux__)
367
// Define hwcap values ourselves: building with an old auxv header where these
368
// hwcap values are not defined should not prevent features from being enabled.
369
#define YUV_LOONGARCH_HWCAP_LSX (1 << 4)
370
#define YUV_LOONGARCH_HWCAP_LASX (1 << 5)
371
372
LIBYUV_API SAFEBUFFERS int LoongArchCpuCaps(void) {
373
  int flag = 0;
374
  unsigned long hwcap = getauxval(AT_HWCAP);
375
376
  if (hwcap & YUV_LOONGARCH_HWCAP_LSX)
377
    flag |= kCpuHasLSX;
378
379
  if (hwcap & YUV_LOONGARCH_HWCAP_LASX)
380
    flag |= kCpuHasLASX;
381
  return flag;
382
}
383
#endif
384
385
4
static SAFEBUFFERS int GetCpuFlags(void) {
386
4
  int cpu_info = 0;
387
4
#if !defined(__pnacl__) && !defined(__CLR_VER) &&                   \
388
4
    (defined(__x86_64__) || defined(_M_X64) || defined(__i386__) || \
389
4
     defined(_M_IX86))
390
4
  int cpu_info0[4] = {0, 0, 0, 0};
391
4
  int cpu_info1[4] = {0, 0, 0, 0};
392
4
  int cpu_info7[4] = {0, 0, 0, 0};
393
4
  int cpu_einfo7[4] = {0, 0, 0, 0};
394
4
  int cpu_info24[4] = {0, 0, 0, 0};
395
4
  int cpu_amdinfo21[4] = {0, 0, 0, 0};
396
4
  CpuId(0, 0, cpu_info0);
397
4
  CpuId(1, 0, cpu_info1);
398
4
  if (cpu_info0[0] >= 7) {
399
4
    CpuId(7, 0, cpu_info7);
400
4
    CpuId(7, 1, cpu_einfo7);
401
4
    CpuId(0x80000021, 0, cpu_amdinfo21);
402
4
  }
403
4
  if (cpu_info0[0] >= 0x24) {
404
0
    CpuId(0x24, 0, cpu_info24);
405
0
  }
406
4
  cpu_info = kCpuHasX86 | ((cpu_info1[3] & 0x04000000) ? kCpuHasSSE2 : 0) |
407
4
             ((cpu_info1[2] & 0x00000200) ? kCpuHasSSSE3 : 0) |
408
4
             ((cpu_info1[2] & 0x00080000) ? kCpuHasSSE41 : 0) |
409
4
             ((cpu_info1[2] & 0x00100000) ? kCpuHasSSE42 : 0) |
410
4
             ((cpu_info7[1] & 0x00000200) ? kCpuHasERMS : 0) |
411
4
             ((cpu_info7[3] & 0x00000010) ? kCpuHasFSMR : 0);
412
413
  // AVX requires OS saves YMM registers.
414
4
  if (((cpu_info1[2] & 0x1c000000) == 0x1c000000) &&  // AVX and OSXSave
415
4
      ((GetXCR0() & 6) == 6)) {  // Test OS saves YMM registers
416
4
    cpu_info |= kCpuHasAVX | ((cpu_info7[1] & 0x00000020) ? kCpuHasAVX2 : 0) |
417
4
                ((cpu_info1[2] & 0x00001000) ? kCpuHasFMA3 : 0) |
418
4
                ((cpu_info1[2] & 0x20000000) ? kCpuHasF16C : 0) |
419
4
                ((cpu_einfo7[0] & 0x00000010) ? kCpuHasAVXVNNI : 0) |
420
4
                ((cpu_einfo7[3] & 0x00000010) ? kCpuHasAVXVNNIINT8 : 0);
421
422
4
    cpu_info |= ((cpu_amdinfo21[0] & 0x00008000) ? kCpuHasERMS : 0);
423
424
    // Detect AVX512bw
425
4
    if ((GetXCR0() & 0xe0) == 0xe0) {
426
0
      cpu_info |= ((cpu_info7[1] & 0x40000000) ? kCpuHasAVX512BW : 0) |
427
0
                  ((cpu_info7[1] & 0x80000000) ? kCpuHasAVX512VL : 0) |
428
0
                  ((cpu_info7[2] & 0x00000002) ? kCpuHasAVX512VBMI : 0) |
429
0
                  ((cpu_info7[2] & 0x00000040) ? kCpuHasAVX512VBMI2 : 0) |
430
0
                  ((cpu_info7[2] & 0x00000800) ? kCpuHasAVX512VNNI : 0) |
431
0
                  ((cpu_info7[2] & 0x00001000) ? kCpuHasAVX512VBITALG : 0) |
432
0
                  ((cpu_einfo7[3] & 0x00080000) ? kCpuHasAVX10 : 0) |
433
0
                  ((cpu_info7[3] & 0x02000000) ? kCpuHasAMXINT8 : 0);
434
0
      if (cpu_info0[0] >= 0x24 && (cpu_einfo7[3] & 0x00080000)) {
435
0
        cpu_info |= ((cpu_info24[1] & 0xFF) >= 2) ? kCpuHasAVX10_2 : 0;
436
0
      }
437
0
    }
438
4
  }
439
4
#endif
440
#if defined(__loongarch__) && defined(__linux__)
441
  cpu_info = LoongArchCpuCaps();
442
  cpu_info |= kCpuHasLOONGARCH;
443
#endif
444
#if defined(__aarch64__)
445
#if defined(__linux__)
446
  // getauxval is supported since Android SDK version 18, minimum at time of
447
  // writing is 21, so should be safe to always use this. If getauxval is
448
  // somehow disabled then getauxval returns 0, which will leave Neon enabled
449
  // since Neon is mandatory on AArch64.
450
  unsigned long hwcap = getauxval(AT_HWCAP);
451
  unsigned long hwcap2 = getauxval(AT_HWCAP2);
452
  cpu_info = AArch64CpuCaps(hwcap, hwcap2);
453
#else
454
  cpu_info = AArch64CpuCaps();
455
#endif
456
  cpu_info |= kCpuHasARM;
457
#endif  // __aarch64__
458
#if defined(__arm__)
459
  // gcc -mfpu=neon defines __ARM_NEON__
460
  // __ARM_NEON__ generates code that requires Neon.  NaCL also requires Neon.
461
  // For Linux, /proc/cpuinfo can be tested but without that assume Neon.
462
  // Linux arm parse text file for neon detect.
463
#if defined(__linux__)
464
  cpu_info = ArmCpuCaps("/proc/cpuinfo");
465
#elif defined(__ARM_NEON__)
466
  cpu_info = kCpuHasNEON;
467
#else
468
  cpu_info = 0;
469
#endif
470
  cpu_info |= kCpuHasARM;
471
#endif  // __arm__
472
#if defined(__riscv) && defined(__linux__)
473
  cpu_info = RiscvCpuCaps("/proc/cpuinfo");
474
  cpu_info |= kCpuHasRISCV;
475
#endif  // __riscv
476
4
  cpu_info |= kCpuInitialized;
477
4
  return cpu_info;
478
4
}
479
480
// Note that use of this function is not thread safe.
481
LIBYUV_API
482
4
int MaskCpuFlags(int enable_flags) {
483
4
  int cpu_info = GetCpuFlags() & enable_flags;
484
4
  SetCpuFlags(cpu_info);
485
4
  return cpu_info;
486
4
}
487
488
LIBYUV_API
489
4
int InitCpuFlags(void) {
490
4
  return MaskCpuFlags(-1);
491
4
}
492
493
#ifdef __cplusplus
494
}  // extern "C"
495
}  // namespace libyuv
496
#endif