fixes for MSVC6; also: default to best flavors of detect code
[platform/upstream/flac.git] / src / libFLAC / cpu.c
1 /* libFLAC - Free Lossless Audio Codec library
2  * Copyright (C) 2001,2002,2003,2004,2005,2006,2007  Josh Coalson
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * - Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *
11  * - Redistributions in binary form must reproduce the above copyright
12  * notice, this list of conditions and the following disclaimer in the
13  * documentation and/or other materials provided with the distribution.
14  *
15  * - Neither the name of the Xiph.org Foundation nor the names of its
16  * contributors may be used to endorse or promote products derived from
17  * this software without specific prior written permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * ``AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22  * A PARTICULAR PURPOSE ARE DISCLAIMED.  IN NO EVENT SHALL THE FOUNDATION OR
23  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  */
31
32 #if HAVE_CONFIG_H
33 #  include <config.h>
34 #endif
35
36 #include "private/cpu.h"
37 #include <stdlib.h>
38 #include <stdio.h>
39
40 #if defined FLAC__CPU_IA32
41 # include <signal.h>
42 #elif defined FLAC__CPU_PPC
43 # if !defined FLAC__NO_ASM
44 #  if defined FLAC__SYS_DARWIN
45 #   include <sys/sysctl.h>
46 #   include <mach/mach.h>
47 #   include <mach/mach_host.h>
48 #   include <mach/host_info.h>
49 #   include <mach/machine.h>
50 #   ifndef CPU_SUBTYPE_POWERPC_970
51 #    define CPU_SUBTYPE_POWERPC_970 ((cpu_subtype_t) 100)
52 #   endif
53 #  else /* FLAC__SYS_DARWIN */
54
55 #   include <signal.h>
56 #   include <setjmp.h>
57
58 static sigjmp_buf jmpbuf;
59 static volatile sig_atomic_t canjump = 0;
60
61 static void sigill_handler (int sig)
62 {
63         if (!canjump) {
64                 signal (sig, SIG_DFL);
65                 raise (sig);
66         }
67         canjump = 0;
68         siglongjmp (jmpbuf, 1);
69 }
70 #  endif /* FLAC__SYS_DARWIN */
71 # endif /* FLAC__NO_ASM */
72 #endif /* FLAC__CPU_PPC */
73
74 #if defined (__NetBSD__) || defined(__OpenBSD__)
75 #include <sys/param.h>
76 #include <sys/sysctl.h>
77 #include <machine/cpu.h>
78 #endif
79
80 #if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
81 #include <sys/types.h>
82 #include <sys/sysctl.h>
83 #endif
84
85 #if defined(__APPLE__)
86 /* how to get sysctlbyname()? */
87 #endif
88
89 const unsigned FLAC__CPUINFO_IA32_CPUID_CMOV = 0x00008000;
90 const unsigned FLAC__CPUINFO_IA32_CPUID_MMX = 0x00800000;
91 const unsigned FLAC__CPUINFO_IA32_CPUID_FXSR = 0x01000000;
92 const unsigned FLAC__CPUINFO_IA32_CPUID_SSE = 0x02000000;
93 const unsigned FLAC__CPUINFO_IA32_CPUID_SSE2 = 0x04000000;
94
95 const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW = 0x80000000;
96 const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW = 0x40000000;
97 const unsigned FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX = 0x00400000;
98
99
100 /*
101  * Extra stuff needed for detection of OS support for SSE on IA-32
102  */
103 #if defined(FLAC__CPU_IA32) && !defined FLAC__NO_ASM && defined FLAC__HAS_NASM && !defined FLAC__NO_SSE_OS && !defined FLAC__SSE_OS
104 # if defined(__linux__)
105 /*
106  * If the OS doesn't support SSE, we will get here with a SIGILL.  We
107  * modify the return address to jump over the offending SSE instruction
108  * and also the operation following it that indicates the instruction
109  * executed successfully.  In this way we use no global variables and
110  * stay thread-safe.
111  *
112  * 3 + 3 + 6:
113  *   3 bytes for "xorps xmm0,xmm0"
114  *   3 bytes for estimate of how long the follwing "inc var" instruction is
115  *   6 bytes extra in case our estimate is wrong
116  * 12 bytes puts us in the NOP "landing zone"
117  */
118 #  undef USE_OBSOLETE_SIGCONTEXT_FLAVOR /* #define this to use the older signal handler method */
119 #  ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
120         static void sigill_handler_sse_os(int signal, struct sigcontext sc)
121         {
122                 (void)signal;
123                 sc.eip += 3 + 3 + 6;
124         }
125 #  else
126 #   include <sys/ucontext.h>
127         static void sigill_handler_sse_os(int signal, siginfo_t *si, void *uc)
128         {
129                 (void)signal, (void)si;
130                 ((ucontext_t*)uc)->uc_mcontext.gregs[14/*REG_EIP*/] += 3 + 3 + 6;
131         }
132 #  endif
133 # elif defined(_MSC_VER)
134 #  include <windows.h>
135 #  undef USE_TRY_CATCH_FLAVOR /* #define this to use the try/catch method for catching illegal opcode exception */
136 #  ifdef USE_TRY_CATCH_FLAVOR
137 #  else
138         LONG CALLBACK sigill_handler_sse_os(EXCEPTION_POINTERS *ep)
139         {
140                 if(ep->ExceptionRecord->ExceptionCode == EXCEPTION_ILLEGAL_INSTRUCTION) {
141                         ep->ContextRecord->Eip += 3 + 3 + 6;
142                         return EXCEPTION_CONTINUE_EXECUTION;
143                 }
144                 return EXCEPTION_CONTINUE_SEARCH;
145         }
146 #  endif
147 # endif
148 #endif
149
150
151 void FLAC__cpu_info(FLAC__CPUInfo *info)
152 {
153 /*
154  * IA32-specific
155  */
156 #ifdef FLAC__CPU_IA32
157         info->type = FLAC__CPUINFO_TYPE_IA32;
158 #if !defined FLAC__NO_ASM && defined FLAC__HAS_NASM
159         info->use_asm = true;
160         {
161                 unsigned cpuid = FLAC__cpu_info_asm_ia32();
162                 info->data.ia32.cmov = (cpuid & FLAC__CPUINFO_IA32_CPUID_CMOV)? true : false;
163                 info->data.ia32.mmx  = (cpuid & FLAC__CPUINFO_IA32_CPUID_MMX )? true : false;
164                 info->data.ia32.fxsr = (cpuid & FLAC__CPUINFO_IA32_CPUID_FXSR)? true : false;
165                 info->data.ia32.sse  = (cpuid & FLAC__CPUINFO_IA32_CPUID_SSE )? true : false;
166                 info->data.ia32.sse2 = (cpuid & FLAC__CPUINFO_IA32_CPUID_SSE2)? true : false;
167
168 #ifdef FLAC__USE_3DNOW
169                 cpuid = FLAC__cpu_info_extended_amd_asm_ia32();
170                 info->data.ia32._3dnow = (cpuid & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_3DNOW)? true : false;
171                 info->data.ia32.ext3dnow = (cpuid & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXT3DNOW)? true : false;
172                 info->data.ia32.extmmx = (cpuid & FLAC__CPUINFO_IA32_CPUID_EXTENDED_AMD_EXTMMX)? true : false;
173 #else
174                 info->data.ia32._3dnow = info->data.ia32.ext3dnow = info->data.ia32.extmmx = false;
175 #endif
176
177                 /*
178                  * now have to check for OS support of SSE/SSE2
179                  */
180                 if(info->data.ia32.fxsr || info->data.ia32.sse || info->data.ia32.sse2) {
181 #if defined FLAC__NO_SSE_OS
182                         /* assume user knows better than us; turn it off */
183                         info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = false;
184 #elif defined FLAC__SSE_OS
185                         /* assume user knows better than us; leave as detected above */
186 #elif defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__) || defined(__APPLE__)
187                         int sse = 0;
188                         size_t len;
189                         /* at least one of these must work: */
190                         len = sizeof(sse); sse = sse || (sysctlbyname("hw.instruction_sse", &sse, &len, NULL, 0) == 0 && sse);
191                         len = sizeof(sse); sse = sse || (sysctlbyname("hw.optional.sse"   , &sse, &len, NULL, 0) == 0 && sse); /* __APPLE__ ? */
192                         if(!sse)
193                                 info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = false;
194 #elif defined(__NetBSD__) || defined (__OpenBSD__)
195 # if __NetBSD_Version__ >= 105250000 || (defined __OpenBSD__)
196                         int val = 0, mib[2] = { CTL_MACHDEP, CPU_SSE };
197                         size_t len = sizeof(val);
198                         if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
199                                 info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = false;
200                         else { /* double-check SSE2 */
201                                 mib[1] = CPU_SSE2;
202                                 len = sizeof(val);
203                                 if(sysctl(mib, 2, &val, &len, NULL, 0) < 0 || !val)
204                                         info->data.ia32.sse2 = false;
205                         }
206 # else
207                         info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = false;
208 # endif
209 #elif defined(__linux__)
210                         int sse = 0;
211                         struct sigaction sigill_save;
212 #ifdef USE_OBSOLETE_SIGCONTEXT_FLAVOR
213                         if(0 == sigaction(SIGILL, NULL, &sigill_save) && signal(SIGILL, (void (*)(int))sigill_handler_sse_os) != SIG_ERR)
214 #else
215                         struct sigaction sigill_sse;
216                         sigill_sse.sa_sigaction = sigill_handler_sse_os;
217                         __sigemptyset(&sigill_sse.sa_mask);
218                         sigill_sse.sa_flags = SA_SIGINFO | SA_RESETHAND; /* SA_RESETHAND just in case our SIGILL return jump breaks, so we don't get stuck in a loop */
219                         if(0 == sigaction(SIGILL, &sigill_sse, &sigill_save))
220 #endif
221                         {
222                                 /* http://www.ibiblio.org/gferg/ldp/GCC-Inline-Assembly-HOWTO.html */
223                                 /* see sigill_handler_sse_os() for an explanation of the following: */
224                                 asm volatile (
225                                         "xorl %0,%0\n\t"          /* for some reason, still need to do this to clear 'sse' var */
226                                         "xorps %%xmm0,%%xmm0\n\t" /* will cause SIGILL if unsupported by OS */
227                                         "incl %0\n\t"             /* SIGILL handler will jump over this */
228                                         /* landing zone */
229                                         "nop\n\t" /* SIGILL jump lands here if "inc" is 9 bytes */
230                                         "nop\n\t"
231                                         "nop\n\t"
232                                         "nop\n\t"
233                                         "nop\n\t"
234                                         "nop\n\t"
235                                         "nop\n\t" /* SIGILL jump lands here if "inc" is 3 bytes (expected) */
236                                         "nop\n\t"
237                                         "nop"     /* SIGILL jump lands here if "inc" is 1 byte */
238                                         : "=r"(sse)
239                                         : "r"(sse)
240                                 );
241
242                                 sigaction(SIGILL, &sigill_save, NULL);
243                         }
244
245                         if(!sse)
246                                 info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = false;
247 #elif defined(_MSC_VER)
248 # ifdef USE_TRY_CATCH_FLAVOR
249                         _try {
250                                 __asm {
251 #  if _MSC_VER <= 1200
252                                         /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
253                                         _emit 0x0F
254                                         _emit 0x57
255                                         _emit 0xC0
256 #  else
257                                         xorps xmm0,xmm0
258 #  endif
259                                 }
260                         }
261                         _except(EXCEPTION_EXECUTE_HANDLER) {
262                                 if (_exception_code() == STATUS_ILLEGAL_INSTRUCTION)
263                                         info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = false;
264                         }
265 # else
266                         int sse = 0;
267                         LPTOP_LEVEL_EXCEPTION_FILTER save = SetUnhandledExceptionFilter(sigill_handler_sse_os);
268                         /* see GCC version above for explanation */
269                         //@@@@@@ http://msdn2.microsoft.com/en-us/library/4ks26t93.aspx
270                         //@@@@@@ http://www.daniweb.com/techtalkforums/thread8072.html
271                         //@@@@@@ http://www.codeproject.com/cpp/gccasm.asp
272                         //@@@@@@ http://www.hick.org/~mmiller/msvc_inline_asm.html
273                         __asm {
274 #  if _MSC_VER <= 1200
275                                 /* VC6 assembler doesn't know SSE, have to emit bytecode instead */
276                                 _emit 0x0F
277                                 _emit 0x57
278                                 _emit 0xC0
279 #  else
280                                 xorps xmm0,xmm0
281 #  endif
282                                 inc sse
283                                 nop
284                                 nop
285                                 nop
286                                 nop
287                                 nop
288                                 nop
289                                 nop
290                                 nop
291                                 nop
292                         }
293                         SetUnhandledExceptionFilter(save);
294                         if(!sse)
295                                 info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = false;
296 fprintf(stderr,"\n@@@@@@ SSE OS=%d %d\n",sse?1:0,sse);
297 # endif
298 #else
299                         /* no way to test, disable to be safe */
300                         info->data.ia32.fxsr = info->data.ia32.sse = info->data.ia32.sse2 = false;
301 #endif
302                 }
303         }
304 #else
305         info->use_asm = false;
306 #endif
307
308 /*
309  * PPC-specific
310  */
311 #elif defined FLAC__CPU_PPC
312         info->type = FLAC__CPUINFO_TYPE_PPC;
313 # if !defined FLAC__NO_ASM
314         info->use_asm = true;
315 #  ifdef FLAC__USE_ALTIVEC
316 #   if defined FLAC__SYS_DARWIN
317         {
318                 int val = 0, mib[2] = { CTL_HW, HW_VECTORUNIT };
319                 size_t len = sizeof(val);
320                 info->data.ppc.altivec = !(sysctl(mib, 2, &val, &len, NULL, 0) || !val);
321         }
322         {
323                 host_basic_info_data_t hostInfo;
324                 mach_msg_type_number_t infoCount;
325
326                 infoCount = HOST_BASIC_INFO_COUNT;
327                 host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo, &infoCount);
328
329                 info->data.ppc.ppc64 = (hostInfo.cpu_type == CPU_TYPE_POWERPC) && (hostInfo.cpu_subtype == CPU_SUBTYPE_POWERPC_970);
330         }
331 #   else /* FLAC__USE_ALTIVEC && !FLAC__SYS_DARWIN */
332         {
333                 /* no Darwin, do it the brute-force way */
334                 /* @@@@@@ this is not thread-safe; replace with SSE OS method above or remove */
335                 info->data.ppc.altivec = 0;
336                 info->data.ppc.ppc64 = 0;
337
338                 signal (SIGILL, sigill_handler);
339                 canjump = 0;
340                 if (!sigsetjmp (jmpbuf, 1)) {
341                         canjump = 1;
342
343                         asm volatile (
344                                 "mtspr 256, %0\n\t"
345                                 "vand %%v0, %%v0, %%v0"
346                                 :
347                                 : "r" (-1)
348                         );
349
350                         info->data.ppc.altivec = 1;
351                 }
352                 canjump = 0;
353                 if (!sigsetjmp (jmpbuf, 1)) {
354                         int x = 0;
355                         canjump = 1;
356
357                         /* PPC64 hardware implements the cntlzd instruction */
358                         asm volatile ("cntlzd %0, %1" : "=r" (x) : "r" (x) );
359
360                         info->data.ppc.ppc64 = 1;
361                 }
362                 signal (SIGILL, SIG_DFL); /*@@@@@@ should save and restore old signal */
363         }
364 #   endif
365 #  else /* !FLAC__USE_ALTIVEC */
366         info->data.ppc.altivec = 0;
367         info->data.ppc.ppc64 = 0;
368 #  endif
369 # else
370         info->use_asm = false;
371 # endif
372
373 /*
374  * unknown CPI
375  */
376 #else
377         info->type = FLAC__CPUINFO_TYPE_UNKNOWN;
378         info->use_asm = false;
379 #endif
380 }