cpu_unittest.cc 2.49 KB
Newer Older
gejun's avatar
gejun committed
1 2 3 4
// Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

5 6
#include "butil/cpu.h"
#include "butil/build_config.h"
gejun's avatar
gejun committed
7 8 9 10 11 12 13 14 15 16 17

#include <gtest/gtest.h>

// Tests whether we can run extended instructions represented by the CPU
// information. This test actually executes some extended instructions (such as
// MMX, SSE, etc.) supported by the CPU and sees we can run them without
// "undefined instruction" exceptions. That is, this test succeeds when this
// test finishes without a crash.
TEST(CPU, RunExtendedInstructions) {
#if defined(ARCH_CPU_X86_FAMILY)
  // Retrieve the CPU information.
18
  butil::CPU cpu;
gejun's avatar
gejun committed
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 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97

// TODO(jschuh): crbug.com/168866 Find a way to enable this on Win64.
#if defined(OS_WIN) && !defined(_M_X64)
  ASSERT_TRUE(cpu.has_mmx());

  // Execute an MMX instruction.
  __asm emms;

  if (cpu.has_sse()) {
    // Execute an SSE instruction.
    __asm xorps xmm0, xmm0;
  }

  if (cpu.has_sse2()) {
    // Execute an SSE 2 instruction.
    __asm psrldq xmm0, 0;
  }

  if (cpu.has_sse3()) {
    // Execute an SSE 3 instruction.
    __asm addsubpd xmm0, xmm0;
  }

  if (cpu.has_ssse3()) {
    // Execute a Supplimental SSE 3 instruction.
    __asm psignb xmm0, xmm0;
  }

  if (cpu.has_sse41()) {
    // Execute an SSE 4.1 instruction.
    __asm pmuldq xmm0, xmm0;
  }

  if (cpu.has_sse42()) {
    // Execute an SSE 4.2 instruction.
    __asm crc32 eax, eax;
  }
#elif defined(OS_POSIX) && defined(__x86_64__)
  ASSERT_TRUE(cpu.has_mmx());

  // Execute an MMX instruction.
  __asm__ __volatile__("emms\n" : : : "mm0");

  if (cpu.has_sse()) {
    // Execute an SSE instruction.
    __asm__ __volatile__("xorps %%xmm0, %%xmm0\n" : : : "xmm0");
  }

  if (cpu.has_sse2()) {
    // Execute an SSE 2 instruction.
    __asm__ __volatile__("psrldq $0, %%xmm0\n" : : : "xmm0");
  }

  if (cpu.has_sse3()) {
    // Execute an SSE 3 instruction.
    __asm__ __volatile__("addsubpd %%xmm0, %%xmm0\n" : : : "xmm0");
  }

  // NOTE(gejun): Not work in gcc 3.4
#if !defined(COMPILER_GCC) || __GNUC__ >= 4
  if (cpu.has_ssse3()) {
    // Execute a Supplimental SSE 3 instruction.
    __asm__ __volatile__("psignb %%xmm0, %%xmm0\n" : : : "xmm0");
  }

  if (cpu.has_sse41()) {
    // Execute an SSE 4.1 instruction.
    __asm__ __volatile__("pmuldq %%xmm0, %%xmm0\n" : : : "xmm0");
  }

  if (cpu.has_sse42()) {
    // Execute an SSE 4.2 instruction.
    __asm__ __volatile__("crc32 %%eax, %%eax\n" : : : "eax");
  }
#endif
  
#endif
#endif
}