]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Support/Host.cpp
Merge libc++ r291274, and update the library Makefile.
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Support / Host.cpp
1 //===-- Host.cpp - Implement OS Host Concept --------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 //  This file implements the operating system Host concept.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Support/Host.h"
15 #include "llvm/ADT/SmallSet.h"
16 #include "llvm/ADT/SmallVector.h"
17 #include "llvm/ADT/StringRef.h"
18 #include "llvm/ADT/StringSwitch.h"
19 #include "llvm/ADT/Triple.h"
20 #include "llvm/Config/config.h"
21 #include "llvm/Support/Debug.h"
22 #include "llvm/Support/FileSystem.h"
23 #include "llvm/Support/MemoryBuffer.h"
24 #include "llvm/Support/raw_ostream.h"
25 #include <assert.h>
26 #include <string.h>
27
28 // Include the platform-specific parts of this class.
29 #ifdef LLVM_ON_UNIX
30 #include "Unix/Host.inc"
31 #endif
32 #ifdef LLVM_ON_WIN32
33 #include "Windows/Host.inc"
34 #endif
35 #ifdef _MSC_VER
36 #include <intrin.h>
37 #endif
38 #if defined(__APPLE__) && (defined(__ppc__) || defined(__powerpc__))
39 #include <mach/host_info.h>
40 #include <mach/mach.h>
41 #include <mach/mach_host.h>
42 #include <mach/machine.h>
43 #endif
44
45 #define DEBUG_TYPE "host-detection"
46
47 //===----------------------------------------------------------------------===//
48 //
49 //  Implementations of the CPU detection routines
50 //
51 //===----------------------------------------------------------------------===//
52
53 using namespace llvm;
54
55 #if defined(__linux__)
56 static ssize_t LLVM_ATTRIBUTE_UNUSED readCpuInfo(void *Buf, size_t Size) {
57   // Note: We cannot mmap /proc/cpuinfo here and then process the resulting
58   // memory buffer because the 'file' has 0 size (it can be read from only
59   // as a stream).
60
61   int FD;
62   std::error_code EC = sys::fs::openFileForRead("/proc/cpuinfo", FD);
63   if (EC) {
64     DEBUG(dbgs() << "Unable to open /proc/cpuinfo: " << EC.message() << "\n");
65     return -1;
66   }
67   int Ret = read(FD, Buf, Size);
68   int CloseStatus = close(FD);
69   if (CloseStatus)
70     return -1;
71   return Ret;
72 }
73 #endif
74
75 #if defined(__i386__) || defined(_M_IX86) || \
76     defined(__x86_64__) || defined(_M_X64)
77
78 enum VendorSignatures {
79   SIG_INTEL = 0x756e6547 /* Genu */,
80   SIG_AMD = 0x68747541 /* Auth */
81 };
82
83 enum ProcessorVendors {
84   VENDOR_INTEL = 1,
85   VENDOR_AMD,
86   VENDOR_OTHER,
87   VENDOR_MAX
88 };
89
90 enum ProcessorTypes {
91   INTEL_ATOM = 1,
92   INTEL_CORE2,
93   INTEL_COREI7,
94   AMDFAM10H,
95   AMDFAM15H,
96   INTEL_i386,
97   INTEL_i486,
98   INTEL_PENTIUM,
99   INTEL_PENTIUM_PRO,
100   INTEL_PENTIUM_II,
101   INTEL_PENTIUM_III,
102   INTEL_PENTIUM_IV,
103   INTEL_PENTIUM_M,
104   INTEL_CORE_DUO,
105   INTEL_XEONPHI,
106   INTEL_X86_64,
107   INTEL_NOCONA,
108   INTEL_PRESCOTT,
109   AMD_i486,
110   AMDPENTIUM,
111   AMDATHLON,
112   AMDFAM14H,
113   AMDFAM16H,
114   CPU_TYPE_MAX
115 };
116
117 enum ProcessorSubtypes {
118   INTEL_COREI7_NEHALEM = 1,
119   INTEL_COREI7_WESTMERE,
120   INTEL_COREI7_SANDYBRIDGE,
121   AMDFAM10H_BARCELONA,
122   AMDFAM10H_SHANGHAI,
123   AMDFAM10H_ISTANBUL,
124   AMDFAM15H_BDVER1,
125   AMDFAM15H_BDVER2,
126   INTEL_PENTIUM_MMX,
127   INTEL_CORE2_65,
128   INTEL_CORE2_45,
129   INTEL_COREI7_IVYBRIDGE,
130   INTEL_COREI7_HASWELL,
131   INTEL_COREI7_BROADWELL,
132   INTEL_COREI7_SKYLAKE,
133   INTEL_COREI7_SKYLAKE_AVX512,
134   INTEL_ATOM_BONNELL,
135   INTEL_ATOM_SILVERMONT,
136   INTEL_KNIGHTS_LANDING,
137   AMDPENTIUM_K6,
138   AMDPENTIUM_K62,
139   AMDPENTIUM_K63,
140   AMDPENTIUM_GEODE,
141   AMDATHLON_TBIRD,
142   AMDATHLON_MP,
143   AMDATHLON_XP,
144   AMDATHLON_K8SSE3,
145   AMDATHLON_OPTERON,
146   AMDATHLON_FX,
147   AMDATHLON_64,
148   AMD_BTVER1,
149   AMD_BTVER2,
150   AMDFAM15H_BDVER3,
151   AMDFAM15H_BDVER4,
152   CPU_SUBTYPE_MAX
153 };
154
155 enum ProcessorFeatures {
156   FEATURE_CMOV = 0,
157   FEATURE_MMX,
158   FEATURE_POPCNT,
159   FEATURE_SSE,
160   FEATURE_SSE2,
161   FEATURE_SSE3,
162   FEATURE_SSSE3,
163   FEATURE_SSE4_1,
164   FEATURE_SSE4_2,
165   FEATURE_AVX,
166   FEATURE_AVX2,
167   FEATURE_AVX512,
168   FEATURE_AVX512SAVE,
169   FEATURE_MOVBE,
170   FEATURE_ADX,
171   FEATURE_EM64T
172 };
173
174 // The check below for i386 was copied from clang's cpuid.h (__get_cpuid_max).
175 // Check motivated by bug reports for OpenSSL crashing on CPUs without CPUID
176 // support. Consequently, for i386, the presence of CPUID is checked first
177 // via the corresponding eflags bit.
178 // Removal of cpuid.h header motivated by PR30384
179 // Header cpuid.h and method __get_cpuid_max are not used in llvm, clang, openmp
180 // or test-suite, but are used in external projects e.g. libstdcxx
181 static bool isCpuIdSupported() {
182 #if defined(__GNUC__) || defined(__clang__)
183 #if defined(__i386__)
184   int __cpuid_supported;
185   __asm__("  pushfl\n"
186           "  popl   %%eax\n"
187           "  movl   %%eax,%%ecx\n"
188           "  xorl   $0x00200000,%%eax\n"
189           "  pushl  %%eax\n"
190           "  popfl\n"
191           "  pushfl\n"
192           "  popl   %%eax\n"
193           "  movl   $0,%0\n"
194           "  cmpl   %%eax,%%ecx\n"
195           "  je     1f\n"
196           "  movl   $1,%0\n"
197           "1:"
198           : "=r"(__cpuid_supported)
199           :
200           : "eax", "ecx");
201   if (!__cpuid_supported)
202     return false;
203 #endif
204   return true;
205 #endif
206   return true;
207 }
208
209 /// getX86CpuIDAndInfo - Execute the specified cpuid and return the 4 values in
210 /// the specified arguments.  If we can't run cpuid on the host, return true.
211 static bool getX86CpuIDAndInfo(unsigned value, unsigned *rEAX, unsigned *rEBX,
212                                unsigned *rECX, unsigned *rEDX) {
213 #if defined(__GNUC__) || defined(__clang__) || defined(_MSC_VER)
214 #if defined(__GNUC__) || defined(__clang__)
215 #if defined(__x86_64__)
216   // gcc doesn't know cpuid would clobber ebx/rbx. Preserve it manually.
217   // FIXME: should we save this for Clang?
218   __asm__("movq\t%%rbx, %%rsi\n\t"
219           "cpuid\n\t"
220           "xchgq\t%%rbx, %%rsi\n\t"
221           : "=a"(*rEAX), "=S"(*rEBX), "=c"(*rECX), "=d"(*rEDX)
222           : "a"(value));
223 #elif defined(__i386__)
224   __asm__("movl\t%%ebx, %%esi\n\t"
225           "cpuid\n\t"
226           "xchgl\t%%ebx, %%esi\n\t"
227           : "=a"(*rEAX), "=S"(*rEBX), "=c"(*rECX), "=d"(*rEDX)
228           : "a"(value));
229 #else
230   assert(0 && "This method is defined only for x86.");
231 #endif
232 #elif defined(_MSC_VER)
233   // The MSVC intrinsic is portable across x86 and x64.
234   int registers[4];
235   __cpuid(registers, value);
236   *rEAX = registers[0];
237   *rEBX = registers[1];
238   *rECX = registers[2];
239   *rEDX = registers[3];
240 #endif
241   return false;
242 #else
243   return true;
244 #endif
245 }
246
247 /// getX86CpuIDAndInfoEx - Execute the specified cpuid with subleaf and return
248 /// the 4 values in the specified arguments.  If we can't run cpuid on the host,
249 /// return true.
250 static bool getX86CpuIDAndInfoEx(unsigned value, unsigned subleaf,
251                                  unsigned *rEAX, unsigned *rEBX, unsigned *rECX,
252                                  unsigned *rEDX) {
253 #if defined(__GNUC__) || defined(__clang__) || defined(_MSC_VER)
254 #if defined(__x86_64__) || defined(_M_X64)
255 #if defined(__GNUC__) || defined(__clang__)
256   // gcc doesn't know cpuid would clobber ebx/rbx. Preseve it manually.
257   // FIXME: should we save this for Clang?
258   __asm__("movq\t%%rbx, %%rsi\n\t"
259           "cpuid\n\t"
260           "xchgq\t%%rbx, %%rsi\n\t"
261           : "=a"(*rEAX), "=S"(*rEBX), "=c"(*rECX), "=d"(*rEDX)
262           : "a"(value), "c"(subleaf));
263 #elif defined(_MSC_VER)
264   int registers[4];
265   __cpuidex(registers, value, subleaf);
266   *rEAX = registers[0];
267   *rEBX = registers[1];
268   *rECX = registers[2];
269   *rEDX = registers[3];
270 #endif
271 #elif defined(__i386__) || defined(_M_IX86)
272 #if defined(__GNUC__) || defined(__clang__)
273   __asm__("movl\t%%ebx, %%esi\n\t"
274           "cpuid\n\t"
275           "xchgl\t%%ebx, %%esi\n\t"
276           : "=a"(*rEAX), "=S"(*rEBX), "=c"(*rECX), "=d"(*rEDX)
277           : "a"(value), "c"(subleaf));
278 #elif defined(_MSC_VER)
279   __asm {
280       mov   eax,value
281       mov   ecx,subleaf
282       cpuid
283       mov   esi,rEAX
284       mov   dword ptr [esi],eax
285       mov   esi,rEBX
286       mov   dword ptr [esi],ebx
287       mov   esi,rECX
288       mov   dword ptr [esi],ecx
289       mov   esi,rEDX
290       mov   dword ptr [esi],edx
291   }
292 #endif
293 #else
294   assert(0 && "This method is defined only for x86.");
295 #endif
296   return false;
297 #else
298   return true;
299 #endif
300 }
301
302 static bool getX86XCR0(unsigned *rEAX, unsigned *rEDX) {
303 #if defined(__GNUC__) || defined(__clang__)
304   // Check xgetbv; this uses a .byte sequence instead of the instruction
305   // directly because older assemblers do not include support for xgetbv and
306   // there is no easy way to conditionally compile based on the assembler used.
307   __asm__(".byte 0x0f, 0x01, 0xd0" : "=a"(*rEAX), "=d"(*rEDX) : "c"(0));
308   return false;
309 #elif defined(_MSC_FULL_VER) && defined(_XCR_XFEATURE_ENABLED_MASK)
310   unsigned long long Result = _xgetbv(_XCR_XFEATURE_ENABLED_MASK);
311   *rEAX = Result;
312   *rEDX = Result >> 32;
313   return false;
314 #else
315   return true;
316 #endif
317 }
318
319 static void detectX86FamilyModel(unsigned EAX, unsigned *Family,
320                                  unsigned *Model) {
321   *Family = (EAX >> 8) & 0xf; // Bits 8 - 11
322   *Model = (EAX >> 4) & 0xf;  // Bits 4 - 7
323   if (*Family == 6 || *Family == 0xf) {
324     if (*Family == 0xf)
325       // Examine extended family ID if family ID is F.
326       *Family += (EAX >> 20) & 0xff; // Bits 20 - 27
327     // Examine extended model ID if family ID is 6 or F.
328     *Model += ((EAX >> 16) & 0xf) << 4; // Bits 16 - 19
329   }
330 }
331
332 static void
333 getIntelProcessorTypeAndSubtype(unsigned int Family, unsigned int Model,
334                                 unsigned int Brand_id, unsigned int Features,
335                                 unsigned *Type, unsigned *Subtype) {
336   if (Brand_id != 0)
337     return;
338   switch (Family) {
339   case 3:
340     *Type = INTEL_i386;
341     break;
342   case 4:
343     switch (Model) {
344     case 0: // Intel486 DX processors
345     case 1: // Intel486 DX processors
346     case 2: // Intel486 SX processors
347     case 3: // Intel487 processors, IntelDX2 OverDrive processors,
348             // IntelDX2 processors
349     case 4: // Intel486 SL processor
350     case 5: // IntelSX2 processors
351     case 7: // Write-Back Enhanced IntelDX2 processors
352     case 8: // IntelDX4 OverDrive processors, IntelDX4 processors
353     default:
354       *Type = INTEL_i486;
355       break;
356     }
357     break;
358   case 5:
359     switch (Model) {
360     case 1: // Pentium OverDrive processor for Pentium processor (60, 66),
361             // Pentium processors (60, 66)
362     case 2: // Pentium OverDrive processor for Pentium processor (75, 90,
363             // 100, 120, 133), Pentium processors (75, 90, 100, 120, 133,
364             // 150, 166, 200)
365     case 3: // Pentium OverDrive processors for Intel486 processor-based
366             // systems
367       *Type = INTEL_PENTIUM;
368       break;
369     case 4: // Pentium OverDrive processor with MMX technology for Pentium
370             // processor (75, 90, 100, 120, 133), Pentium processor with
371             // MMX technology (166, 200)
372       *Type = INTEL_PENTIUM;
373       *Subtype = INTEL_PENTIUM_MMX;
374       break;
375     default:
376       *Type = INTEL_PENTIUM;
377       break;
378     }
379     break;
380   case 6:
381     switch (Model) {
382     case 0x01: // Pentium Pro processor
383       *Type = INTEL_PENTIUM_PRO;
384       break;
385     case 0x03: // Intel Pentium II OverDrive processor, Pentium II processor,
386                // model 03
387     case 0x05: // Pentium II processor, model 05, Pentium II Xeon processor,
388                // model 05, and Intel Celeron processor, model 05
389     case 0x06: // Celeron processor, model 06
390       *Type = INTEL_PENTIUM_II;
391       break;
392     case 0x07: // Pentium III processor, model 07, and Pentium III Xeon
393                // processor, model 07
394     case 0x08: // Pentium III processor, model 08, Pentium III Xeon processor,
395                // model 08, and Celeron processor, model 08
396     case 0x0a: // Pentium III Xeon processor, model 0Ah
397     case 0x0b: // Pentium III processor, model 0Bh
398       *Type = INTEL_PENTIUM_III;
399       break;
400     case 0x09: // Intel Pentium M processor, Intel Celeron M processor model 09.
401     case 0x0d: // Intel Pentium M processor, Intel Celeron M processor, model
402                // 0Dh. All processors are manufactured using the 90 nm process.
403     case 0x15: // Intel EP80579 Integrated Processor and Intel EP80579
404                // Integrated Processor with Intel QuickAssist Technology
405       *Type = INTEL_PENTIUM_M;
406       break;
407     case 0x0e: // Intel Core Duo processor, Intel Core Solo processor, model
408                // 0Eh. All processors are manufactured using the 65 nm process.
409       *Type = INTEL_CORE_DUO;
410       break;   // yonah
411     case 0x0f: // Intel Core 2 Duo processor, Intel Core 2 Duo mobile
412                // processor, Intel Core 2 Quad processor, Intel Core 2 Quad
413                // mobile processor, Intel Core 2 Extreme processor, Intel
414                // Pentium Dual-Core processor, Intel Xeon processor, model
415                // 0Fh. All processors are manufactured using the 65 nm process.
416     case 0x16: // Intel Celeron processor model 16h. All processors are
417                // manufactured using the 65 nm process
418       *Type = INTEL_CORE2; // "core2"
419       *Subtype = INTEL_CORE2_65;
420       break;
421     case 0x17: // Intel Core 2 Extreme processor, Intel Xeon processor, model
422                // 17h. All processors are manufactured using the 45 nm process.
423                //
424                // 45nm: Penryn , Wolfdale, Yorkfield (XE)
425     case 0x1d: // Intel Xeon processor MP. All processors are manufactured using
426                // the 45 nm process.
427       *Type = INTEL_CORE2; // "penryn"
428       *Subtype = INTEL_CORE2_45;
429       break;
430     case 0x1a: // Intel Core i7 processor and Intel Xeon processor. All
431                // processors are manufactured using the 45 nm process.
432     case 0x1e: // Intel(R) Core(TM) i7 CPU         870  @ 2.93GHz.
433                // As found in a Summer 2010 model iMac.
434     case 0x1f:
435     case 0x2e:             // Nehalem EX
436       *Type = INTEL_COREI7; // "nehalem"
437       *Subtype = INTEL_COREI7_NEHALEM;
438       break;
439     case 0x25: // Intel Core i7, laptop version.
440     case 0x2c: // Intel Core i7 processor and Intel Xeon processor. All
441                // processors are manufactured using the 32 nm process.
442     case 0x2f: // Westmere EX
443       *Type = INTEL_COREI7; // "westmere"
444       *Subtype = INTEL_COREI7_WESTMERE;
445       break;
446     case 0x2a: // Intel Core i7 processor. All processors are manufactured
447                // using the 32 nm process.
448     case 0x2d:
449       *Type = INTEL_COREI7; //"sandybridge"
450       *Subtype = INTEL_COREI7_SANDYBRIDGE;
451       break;
452     case 0x3a:
453     case 0x3e:             // Ivy Bridge EP
454       *Type = INTEL_COREI7; // "ivybridge"
455       *Subtype = INTEL_COREI7_IVYBRIDGE;
456       break;
457
458     // Haswell:
459     case 0x3c:
460     case 0x3f:
461     case 0x45:
462     case 0x46:
463       *Type = INTEL_COREI7; // "haswell"
464       *Subtype = INTEL_COREI7_HASWELL;
465       break;
466
467     // Broadwell:
468     case 0x3d:
469     case 0x47:
470     case 0x4f:
471     case 0x56:
472       *Type = INTEL_COREI7; // "broadwell"
473       *Subtype = INTEL_COREI7_BROADWELL;
474       break;
475
476     // Skylake:
477     case 0x4e: // Skylake mobile
478     case 0x5e: // Skylake desktop
479     case 0x8e: // Kaby Lake mobile
480     case 0x9e: // Kaby Lake desktop
481       *Type = INTEL_COREI7; // "skylake"
482       *Subtype = INTEL_COREI7_SKYLAKE;
483       break;
484
485     // Skylake Xeon:
486     case 0x55:
487       *Type = INTEL_COREI7;
488       // Check that we really have AVX512
489       if (Features & (1 << FEATURE_AVX512)) {
490         *Subtype = INTEL_COREI7_SKYLAKE_AVX512; // "skylake-avx512"
491       } else {
492         *Subtype = INTEL_COREI7_SKYLAKE; // "skylake"
493       }
494       break;
495
496     case 0x1c: // Most 45 nm Intel Atom processors
497     case 0x26: // 45 nm Atom Lincroft
498     case 0x27: // 32 nm Atom Medfield
499     case 0x35: // 32 nm Atom Midview
500     case 0x36: // 32 nm Atom Midview
501       *Type = INTEL_ATOM;
502       *Subtype = INTEL_ATOM_BONNELL;
503       break; // "bonnell"
504
505     // Atom Silvermont codes from the Intel software optimization guide.
506     case 0x37:
507     case 0x4a:
508     case 0x4d:
509     case 0x5a:
510     case 0x5d:
511     case 0x4c: // really airmont
512       *Type = INTEL_ATOM;
513       *Subtype = INTEL_ATOM_SILVERMONT;
514       break; // "silvermont"
515
516     case 0x57:
517       *Type = INTEL_XEONPHI; // knl
518       *Subtype = INTEL_KNIGHTS_LANDING;
519       break;
520
521     default: // Unknown family 6 CPU, try to guess.
522       if (Features & (1 << FEATURE_AVX512)) {
523         *Type = INTEL_XEONPHI; // knl
524         *Subtype = INTEL_KNIGHTS_LANDING;
525         break;
526       }
527       if (Features & (1 << FEATURE_ADX)) {
528         *Type = INTEL_COREI7;
529         *Subtype = INTEL_COREI7_BROADWELL;
530         break;
531       }
532       if (Features & (1 << FEATURE_AVX2)) {
533         *Type = INTEL_COREI7;
534         *Subtype = INTEL_COREI7_HASWELL;
535         break;
536       }
537       if (Features & (1 << FEATURE_AVX)) {
538         *Type = INTEL_COREI7;
539         *Subtype = INTEL_COREI7_SANDYBRIDGE;
540         break;
541       }
542       if (Features & (1 << FEATURE_SSE4_2)) {
543         if (Features & (1 << FEATURE_MOVBE)) {
544           *Type = INTEL_ATOM;
545           *Subtype = INTEL_ATOM_SILVERMONT;
546         } else {
547           *Type = INTEL_COREI7;
548           *Subtype = INTEL_COREI7_NEHALEM;
549         }
550         break;
551       }
552       if (Features & (1 << FEATURE_SSE4_1)) {
553         *Type = INTEL_CORE2; // "penryn"
554         *Subtype = INTEL_CORE2_45;
555         break;
556       }
557       if (Features & (1 << FEATURE_SSSE3)) {
558         if (Features & (1 << FEATURE_MOVBE)) {
559           *Type = INTEL_ATOM;
560           *Subtype = INTEL_ATOM_BONNELL; // "bonnell"
561         } else {
562           *Type = INTEL_CORE2; // "core2"
563           *Subtype = INTEL_CORE2_65;
564         }
565         break;
566       }
567       if (Features & (1 << FEATURE_EM64T)) {
568         *Type = INTEL_X86_64;
569         break; // x86-64
570       }
571       if (Features & (1 << FEATURE_SSE2)) {
572         *Type = INTEL_PENTIUM_M;
573         break;
574       }
575       if (Features & (1 << FEATURE_SSE)) {
576         *Type = INTEL_PENTIUM_III;
577         break;
578       }
579       if (Features & (1 << FEATURE_MMX)) {
580         *Type = INTEL_PENTIUM_II;
581         break;
582       }
583       *Type = INTEL_PENTIUM_PRO;
584       break;
585     }
586     break;
587   case 15: {
588     switch (Model) {
589     case 0: // Pentium 4 processor, Intel Xeon processor. All processors are
590             // model 00h and manufactured using the 0.18 micron process.
591     case 1: // Pentium 4 processor, Intel Xeon processor, Intel Xeon
592             // processor MP, and Intel Celeron processor. All processors are
593             // model 01h and manufactured using the 0.18 micron process.
594     case 2: // Pentium 4 processor, Mobile Intel Pentium 4 processor - M,
595             // Intel Xeon processor, Intel Xeon processor MP, Intel Celeron
596             // processor, and Mobile Intel Celeron processor. All processors
597             // are model 02h and manufactured using the 0.13 micron process.
598       *Type =
599           ((Features & (1 << FEATURE_EM64T)) ? INTEL_X86_64 : INTEL_PENTIUM_IV);
600       break;
601
602     case 3: // Pentium 4 processor, Intel Xeon processor, Intel Celeron D
603             // processor. All processors are model 03h and manufactured using
604             // the 90 nm process.
605     case 4: // Pentium 4 processor, Pentium 4 processor Extreme Edition,
606             // Pentium D processor, Intel Xeon processor, Intel Xeon
607             // processor MP, Intel Celeron D processor. All processors are
608             // model 04h and manufactured using the 90 nm process.
609     case 6: // Pentium 4 processor, Pentium D processor, Pentium processor
610             // Extreme Edition, Intel Xeon processor, Intel Xeon processor
611             // MP, Intel Celeron D processor. All processors are model 06h
612             // and manufactured using the 65 nm process.
613       *Type =
614           ((Features & (1 << FEATURE_EM64T)) ? INTEL_NOCONA : INTEL_PRESCOTT);
615       break;
616
617     default:
618       *Type =
619           ((Features & (1 << FEATURE_EM64T)) ? INTEL_X86_64 : INTEL_PENTIUM_IV);
620       break;
621     }
622     break;
623   }
624   default:
625     break; /*"generic"*/
626   }
627 }
628
629 static void getAMDProcessorTypeAndSubtype(unsigned int Family,
630                                           unsigned int Model,
631                                           unsigned int Features,
632                                           unsigned *Type,
633                                           unsigned *Subtype) {
634   // FIXME: this poorly matches the generated SubtargetFeatureKV table.  There
635   // appears to be no way to generate the wide variety of AMD-specific targets
636   // from the information returned from CPUID.
637   switch (Family) {
638   case 4:
639     *Type = AMD_i486;
640     break;
641   case 5:
642     *Type = AMDPENTIUM;
643     switch (Model) {
644     case 6:
645     case 7:
646       *Subtype = AMDPENTIUM_K6;
647       break; // "k6"
648     case 8:
649       *Subtype = AMDPENTIUM_K62;
650       break; // "k6-2"
651     case 9:
652     case 13:
653       *Subtype = AMDPENTIUM_K63;
654       break; // "k6-3"
655     case 10:
656       *Subtype = AMDPENTIUM_GEODE;
657       break; // "geode"
658     }
659     break;
660   case 6:
661     *Type = AMDATHLON;
662     switch (Model) {
663     case 4:
664       *Subtype = AMDATHLON_TBIRD;
665       break; // "athlon-tbird"
666     case 6:
667     case 7:
668     case 8:
669       *Subtype = AMDATHLON_MP;
670       break; // "athlon-mp"
671     case 10:
672       *Subtype = AMDATHLON_XP;
673       break; // "athlon-xp"
674     }
675     break;
676   case 15:
677     *Type = AMDATHLON;
678     if (Features & (1 << FEATURE_SSE3)) {
679       *Subtype = AMDATHLON_K8SSE3;
680       break; // "k8-sse3"
681     }
682     switch (Model) {
683     case 1:
684       *Subtype = AMDATHLON_OPTERON;
685       break; // "opteron"
686     case 5:
687       *Subtype = AMDATHLON_FX;
688       break; // "athlon-fx"; also opteron
689     default:
690       *Subtype = AMDATHLON_64;
691       break; // "athlon64"
692     }
693     break;
694   case 16:
695     *Type = AMDFAM10H; // "amdfam10"
696     switch (Model) {
697     case 2:
698       *Subtype = AMDFAM10H_BARCELONA;
699       break;
700     case 4:
701       *Subtype = AMDFAM10H_SHANGHAI;
702       break;
703     case 8:
704       *Subtype = AMDFAM10H_ISTANBUL;
705       break;
706     }
707     break;
708   case 20:
709     *Type = AMDFAM14H;
710     *Subtype = AMD_BTVER1;
711     break; // "btver1";
712   case 21:
713     *Type = AMDFAM15H;
714     if (!(Features &
715           (1 << FEATURE_AVX))) { // If no AVX support, provide a sane fallback.
716       *Subtype = AMD_BTVER1;
717       break; // "btver1"
718     }
719     if (Model >= 0x50 && Model <= 0x6f) {
720       *Subtype = AMDFAM15H_BDVER4;
721       break; // "bdver4"; 50h-6Fh: Excavator
722     }
723     if (Model >= 0x30 && Model <= 0x3f) {
724       *Subtype = AMDFAM15H_BDVER3;
725       break; // "bdver3"; 30h-3Fh: Steamroller
726     }
727     if (Model >= 0x10 && Model <= 0x1f) {
728       *Subtype = AMDFAM15H_BDVER2;
729       break; // "bdver2"; 10h-1Fh: Piledriver
730     }
731     if (Model <= 0x0f) {
732       *Subtype = AMDFAM15H_BDVER1;
733       break; // "bdver1"; 00h-0Fh: Bulldozer
734     }
735     break;
736   case 22:
737     *Type = AMDFAM16H;
738     if (!(Features &
739           (1 << FEATURE_AVX))) { // If no AVX support provide a sane fallback.
740       *Subtype = AMD_BTVER1;
741       break; // "btver1";
742     }
743     *Subtype = AMD_BTVER2;
744     break; // "btver2"
745   default:
746     break; // "generic"
747   }
748 }
749
750 static unsigned getAvailableFeatures(unsigned int ECX, unsigned int EDX,
751                                      unsigned MaxLeaf) {
752   unsigned Features = 0;
753   unsigned int EAX, EBX;
754   Features |= (((EDX >> 23) & 1) << FEATURE_MMX);
755   Features |= (((EDX >> 25) & 1) << FEATURE_SSE);
756   Features |= (((EDX >> 26) & 1) << FEATURE_SSE2);
757   Features |= (((ECX >> 0) & 1) << FEATURE_SSE3);
758   Features |= (((ECX >> 9) & 1) << FEATURE_SSSE3);
759   Features |= (((ECX >> 19) & 1) << FEATURE_SSE4_1);
760   Features |= (((ECX >> 20) & 1) << FEATURE_SSE4_2);
761   Features |= (((ECX >> 22) & 1) << FEATURE_MOVBE);
762
763   // If CPUID indicates support for XSAVE, XRESTORE and AVX, and XGETBV
764   // indicates that the AVX registers will be saved and restored on context
765   // switch, then we have full AVX support.
766   const unsigned AVXBits = (1 << 27) | (1 << 28);
767   bool HasAVX = ((ECX & AVXBits) == AVXBits) && !getX86XCR0(&EAX, &EDX) &&
768                 ((EAX & 0x6) == 0x6);
769   bool HasAVX512Save = HasAVX && ((EAX & 0xe0) == 0xe0);
770   bool HasLeaf7 =
771       MaxLeaf >= 0x7 && !getX86CpuIDAndInfoEx(0x7, 0x0, &EAX, &EBX, &ECX, &EDX);
772   bool HasADX = HasLeaf7 && ((EBX >> 19) & 1);
773   bool HasAVX2 = HasAVX && HasLeaf7 && (EBX & 0x20);
774   bool HasAVX512 = HasLeaf7 && HasAVX512Save && ((EBX >> 16) & 1);
775   Features |= (HasAVX << FEATURE_AVX);
776   Features |= (HasAVX2 << FEATURE_AVX2);
777   Features |= (HasAVX512 << FEATURE_AVX512);
778   Features |= (HasAVX512Save << FEATURE_AVX512SAVE);
779   Features |= (HasADX << FEATURE_ADX);
780
781   getX86CpuIDAndInfo(0x80000001, &EAX, &EBX, &ECX, &EDX);
782   Features |= (((EDX >> 29) & 0x1) << FEATURE_EM64T);
783   return Features;
784 }
785
786 StringRef sys::getHostCPUName() {
787   unsigned EAX = 0, EBX = 0, ECX = 0, EDX = 0;
788   unsigned MaxLeaf, Vendor;
789
790 #if defined(__GNUC__) || defined(__clang__)
791   //FIXME: include cpuid.h from clang or copy __get_cpuid_max here
792   // and simplify it to not invoke __cpuid (like cpu_model.c in
793   // compiler-rt/lib/builtins/cpu_model.c?
794   // Opting for the second option.
795   if(!isCpuIdSupported())
796     return "generic";
797 #endif
798   if (getX86CpuIDAndInfo(0, &MaxLeaf, &Vendor, &ECX, &EDX))
799     return "generic";
800   if (getX86CpuIDAndInfo(0x1, &EAX, &EBX, &ECX, &EDX))
801     return "generic";
802
803   unsigned Brand_id = EBX & 0xff;
804   unsigned Family = 0, Model = 0;
805   unsigned Features = 0;
806   detectX86FamilyModel(EAX, &Family, &Model);
807   Features = getAvailableFeatures(ECX, EDX, MaxLeaf);
808
809   unsigned Type;
810   unsigned Subtype;
811
812   if (Vendor == SIG_INTEL) {
813     getIntelProcessorTypeAndSubtype(Family, Model, Brand_id, Features, &Type,
814                                     &Subtype);
815     switch (Type) {
816     case INTEL_i386:
817       return "i386";
818     case INTEL_i486:
819       return "i486";
820     case INTEL_PENTIUM:
821       if (Subtype == INTEL_PENTIUM_MMX)
822         return "pentium-mmx";
823       return "pentium";
824     case INTEL_PENTIUM_PRO:
825       return "pentiumpro";
826     case INTEL_PENTIUM_II:
827       return "pentium2";
828     case INTEL_PENTIUM_III:
829       return "pentium3";
830     case INTEL_PENTIUM_IV:
831       return "pentium4";
832     case INTEL_PENTIUM_M:
833       return "pentium-m";
834     case INTEL_CORE_DUO:
835       return "yonah";
836     case INTEL_CORE2:
837       switch (Subtype) {
838       case INTEL_CORE2_65:
839         return "core2";
840       case INTEL_CORE2_45:
841         return "penryn";
842       default:
843         return "core2";
844       }
845     case INTEL_COREI7:
846       switch (Subtype) {
847       case INTEL_COREI7_NEHALEM:
848         return "nehalem";
849       case INTEL_COREI7_WESTMERE:
850         return "westmere";
851       case INTEL_COREI7_SANDYBRIDGE:
852         return "sandybridge";
853       case INTEL_COREI7_IVYBRIDGE:
854         return "ivybridge";
855       case INTEL_COREI7_HASWELL:
856         return "haswell";
857       case INTEL_COREI7_BROADWELL:
858         return "broadwell";
859       case INTEL_COREI7_SKYLAKE:
860         return "skylake";
861       case INTEL_COREI7_SKYLAKE_AVX512:
862         return "skylake-avx512";
863       default:
864         return "corei7";
865       }
866     case INTEL_ATOM:
867       switch (Subtype) {
868       case INTEL_ATOM_BONNELL:
869         return "bonnell";
870       case INTEL_ATOM_SILVERMONT:
871         return "silvermont";
872       default:
873         return "atom";
874       }
875     case INTEL_XEONPHI:
876       return "knl"; /*update for more variants added*/
877     case INTEL_X86_64:
878       return "x86-64";
879     case INTEL_NOCONA:
880       return "nocona";
881     case INTEL_PRESCOTT:
882       return "prescott";
883     default:
884       return "generic";
885     }
886   } else if (Vendor == SIG_AMD) {
887     getAMDProcessorTypeAndSubtype(Family, Model, Features, &Type, &Subtype);
888     switch (Type) {
889     case AMD_i486:
890       return "i486";
891     case AMDPENTIUM:
892       switch (Subtype) {
893       case AMDPENTIUM_K6:
894         return "k6";
895       case AMDPENTIUM_K62:
896         return "k6-2";
897       case AMDPENTIUM_K63:
898         return "k6-3";
899       case AMDPENTIUM_GEODE:
900         return "geode";
901       default:
902         return "pentium";
903       }
904     case AMDATHLON:
905       switch (Subtype) {
906       case AMDATHLON_TBIRD:
907         return "athlon-tbird";
908       case AMDATHLON_MP:
909         return "athlon-mp";
910       case AMDATHLON_XP:
911         return "athlon-xp";
912       case AMDATHLON_K8SSE3:
913         return "k8-sse3";
914       case AMDATHLON_OPTERON:
915         return "opteron";
916       case AMDATHLON_FX:
917         return "athlon-fx";
918       case AMDATHLON_64:
919         return "athlon64";
920       default:
921         return "athlon";
922       }
923     case AMDFAM10H:
924       if(Subtype == AMDFAM10H_BARCELONA)
925         return "barcelona";
926       return "amdfam10";
927     case AMDFAM14H:
928       return "btver1";
929     case AMDFAM15H:
930       switch (Subtype) {
931       case AMDFAM15H_BDVER1:
932         return "bdver1";
933       case AMDFAM15H_BDVER2:
934         return "bdver2";
935       case AMDFAM15H_BDVER3:
936         return "bdver3";
937       case AMDFAM15H_BDVER4:
938         return "bdver4";
939       case AMD_BTVER1:
940         return "btver1";
941       default:
942         return "amdfam15";
943       }
944     case AMDFAM16H:
945       switch (Subtype) {
946       case AMD_BTVER1:
947         return "btver1";
948       case AMD_BTVER2:
949         return "btver2";
950       default:
951         return "amdfam16";
952       }
953     default:
954       return "generic";
955     }
956   }
957   return "generic";
958 }
959
960 #elif defined(__APPLE__) && (defined(__ppc__) || defined(__powerpc__))
961 StringRef sys::getHostCPUName() {
962   host_basic_info_data_t hostInfo;
963   mach_msg_type_number_t infoCount;
964
965   infoCount = HOST_BASIC_INFO_COUNT;
966   host_info(mach_host_self(), HOST_BASIC_INFO, (host_info_t)&hostInfo,
967             &infoCount);
968
969   if (hostInfo.cpu_type != CPU_TYPE_POWERPC)
970     return "generic";
971
972   switch (hostInfo.cpu_subtype) {
973   case CPU_SUBTYPE_POWERPC_601:
974     return "601";
975   case CPU_SUBTYPE_POWERPC_602:
976     return "602";
977   case CPU_SUBTYPE_POWERPC_603:
978     return "603";
979   case CPU_SUBTYPE_POWERPC_603e:
980     return "603e";
981   case CPU_SUBTYPE_POWERPC_603ev:
982     return "603ev";
983   case CPU_SUBTYPE_POWERPC_604:
984     return "604";
985   case CPU_SUBTYPE_POWERPC_604e:
986     return "604e";
987   case CPU_SUBTYPE_POWERPC_620:
988     return "620";
989   case CPU_SUBTYPE_POWERPC_750:
990     return "750";
991   case CPU_SUBTYPE_POWERPC_7400:
992     return "7400";
993   case CPU_SUBTYPE_POWERPC_7450:
994     return "7450";
995   case CPU_SUBTYPE_POWERPC_970:
996     return "970";
997   default:;
998   }
999
1000   return "generic";
1001 }
1002 #elif defined(__linux__) && (defined(__ppc__) || defined(__powerpc__))
1003 StringRef sys::getHostCPUName() {
1004   // Access to the Processor Version Register (PVR) on PowerPC is privileged,
1005   // and so we must use an operating-system interface to determine the current
1006   // processor type. On Linux, this is exposed through the /proc/cpuinfo file.
1007   const char *generic = "generic";
1008
1009   // The cpu line is second (after the 'processor: 0' line), so if this
1010   // buffer is too small then something has changed (or is wrong).
1011   char buffer[1024];
1012   ssize_t CPUInfoSize = readCpuInfo(buffer, sizeof(buffer));
1013   if (CPUInfoSize == -1)
1014     return generic;
1015
1016   const char *CPUInfoStart = buffer;
1017   const char *CPUInfoEnd = buffer + CPUInfoSize;
1018
1019   const char *CIP = CPUInfoStart;
1020
1021   const char *CPUStart = 0;
1022   size_t CPULen = 0;
1023
1024   // We need to find the first line which starts with cpu, spaces, and a colon.
1025   // After the colon, there may be some additional spaces and then the cpu type.
1026   while (CIP < CPUInfoEnd && CPUStart == 0) {
1027     if (CIP < CPUInfoEnd && *CIP == '\n')
1028       ++CIP;
1029
1030     if (CIP < CPUInfoEnd && *CIP == 'c') {
1031       ++CIP;
1032       if (CIP < CPUInfoEnd && *CIP == 'p') {
1033         ++CIP;
1034         if (CIP < CPUInfoEnd && *CIP == 'u') {
1035           ++CIP;
1036           while (CIP < CPUInfoEnd && (*CIP == ' ' || *CIP == '\t'))
1037             ++CIP;
1038
1039           if (CIP < CPUInfoEnd && *CIP == ':') {
1040             ++CIP;
1041             while (CIP < CPUInfoEnd && (*CIP == ' ' || *CIP == '\t'))
1042               ++CIP;
1043
1044             if (CIP < CPUInfoEnd) {
1045               CPUStart = CIP;
1046               while (CIP < CPUInfoEnd && (*CIP != ' ' && *CIP != '\t' &&
1047                                           *CIP != ',' && *CIP != '\n'))
1048                 ++CIP;
1049               CPULen = CIP - CPUStart;
1050             }
1051           }
1052         }
1053       }
1054     }
1055
1056     if (CPUStart == 0)
1057       while (CIP < CPUInfoEnd && *CIP != '\n')
1058         ++CIP;
1059   }
1060
1061   if (CPUStart == 0)
1062     return generic;
1063
1064   return StringSwitch<const char *>(StringRef(CPUStart, CPULen))
1065       .Case("604e", "604e")
1066       .Case("604", "604")
1067       .Case("7400", "7400")
1068       .Case("7410", "7400")
1069       .Case("7447", "7400")
1070       .Case("7455", "7450")
1071       .Case("G4", "g4")
1072       .Case("POWER4", "970")
1073       .Case("PPC970FX", "970")
1074       .Case("PPC970MP", "970")
1075       .Case("G5", "g5")
1076       .Case("POWER5", "g5")
1077       .Case("A2", "a2")
1078       .Case("POWER6", "pwr6")
1079       .Case("POWER7", "pwr7")
1080       .Case("POWER8", "pwr8")
1081       .Case("POWER8E", "pwr8")
1082       .Case("POWER8NVL", "pwr8")
1083       .Case("POWER9", "pwr9")
1084       .Default(generic);
1085 }
1086 #elif defined(__linux__) && defined(__arm__)
1087 StringRef sys::getHostCPUName() {
1088   // The cpuid register on arm is not accessible from user space. On Linux,
1089   // it is exposed through the /proc/cpuinfo file.
1090
1091   // Read 1024 bytes from /proc/cpuinfo, which should contain the CPU part line
1092   // in all cases.
1093   char buffer[1024];
1094   ssize_t CPUInfoSize = readCpuInfo(buffer, sizeof(buffer));
1095   if (CPUInfoSize == -1)
1096     return "generic";
1097
1098   StringRef Str(buffer, CPUInfoSize);
1099
1100   SmallVector<StringRef, 32> Lines;
1101   Str.split(Lines, "\n");
1102
1103   // Look for the CPU implementer line.
1104   StringRef Implementer;
1105   for (unsigned I = 0, E = Lines.size(); I != E; ++I)
1106     if (Lines[I].startswith("CPU implementer"))
1107       Implementer = Lines[I].substr(15).ltrim("\t :");
1108
1109   if (Implementer == "0x41") // ARM Ltd.
1110     // Look for the CPU part line.
1111     for (unsigned I = 0, E = Lines.size(); I != E; ++I)
1112       if (Lines[I].startswith("CPU part"))
1113         // The CPU part is a 3 digit hexadecimal number with a 0x prefix. The
1114         // values correspond to the "Part number" in the CP15/c0 register. The
1115         // contents are specified in the various processor manuals.
1116         return StringSwitch<const char *>(Lines[I].substr(8).ltrim("\t :"))
1117             .Case("0x926", "arm926ej-s")
1118             .Case("0xb02", "mpcore")
1119             .Case("0xb36", "arm1136j-s")
1120             .Case("0xb56", "arm1156t2-s")
1121             .Case("0xb76", "arm1176jz-s")
1122             .Case("0xc08", "cortex-a8")
1123             .Case("0xc09", "cortex-a9")
1124             .Case("0xc0f", "cortex-a15")
1125             .Case("0xc20", "cortex-m0")
1126             .Case("0xc23", "cortex-m3")
1127             .Case("0xc24", "cortex-m4")
1128             .Default("generic");
1129
1130   if (Implementer == "0x51") // Qualcomm Technologies, Inc.
1131     // Look for the CPU part line.
1132     for (unsigned I = 0, E = Lines.size(); I != E; ++I)
1133       if (Lines[I].startswith("CPU part"))
1134         // The CPU part is a 3 digit hexadecimal number with a 0x prefix. The
1135         // values correspond to the "Part number" in the CP15/c0 register. The
1136         // contents are specified in the various processor manuals.
1137         return StringSwitch<const char *>(Lines[I].substr(8).ltrim("\t :"))
1138             .Case("0x06f", "krait") // APQ8064
1139             .Default("generic");
1140
1141   return "generic";
1142 }
1143 #elif defined(__linux__) && defined(__s390x__)
1144 StringRef sys::getHostCPUName() {
1145   // STIDP is a privileged operation, so use /proc/cpuinfo instead.
1146
1147   // The "processor 0:" line comes after a fair amount of other information,
1148   // including a cache breakdown, but this should be plenty.
1149   char buffer[2048];
1150   ssize_t CPUInfoSize = readCpuInfo(buffer, sizeof(buffer));
1151   if (CPUInfoSize == -1)
1152     return "generic";
1153
1154   StringRef Str(buffer, CPUInfoSize);
1155   SmallVector<StringRef, 32> Lines;
1156   Str.split(Lines, "\n");
1157
1158   // Look for the CPU features.
1159   SmallVector<StringRef, 32> CPUFeatures;
1160   for (unsigned I = 0, E = Lines.size(); I != E; ++I)
1161     if (Lines[I].startswith("features")) {
1162       size_t Pos = Lines[I].find(":");
1163       if (Pos != StringRef::npos) {
1164         Lines[I].drop_front(Pos + 1).split(CPUFeatures, ' ');
1165         break;
1166       }
1167     }
1168
1169   // We need to check for the presence of vector support independently of
1170   // the machine type, since we may only use the vector register set when
1171   // supported by the kernel (and hypervisor).
1172   bool HaveVectorSupport = false;
1173   for (unsigned I = 0, E = CPUFeatures.size(); I != E; ++I) {
1174     if (CPUFeatures[I] == "vx")
1175       HaveVectorSupport = true;
1176   }
1177
1178   // Now check the processor machine type.
1179   for (unsigned I = 0, E = Lines.size(); I != E; ++I) {
1180     if (Lines[I].startswith("processor ")) {
1181       size_t Pos = Lines[I].find("machine = ");
1182       if (Pos != StringRef::npos) {
1183         Pos += sizeof("machine = ") - 1;
1184         unsigned int Id;
1185         if (!Lines[I].drop_front(Pos).getAsInteger(10, Id)) {
1186           if (Id >= 2964 && HaveVectorSupport)
1187             return "z13";
1188           if (Id >= 2827)
1189             return "zEC12";
1190           if (Id >= 2817)
1191             return "z196";
1192         }
1193       }
1194       break;
1195     }
1196   }
1197
1198   return "generic";
1199 }
1200 #else
1201 StringRef sys::getHostCPUName() { return "generic"; }
1202 #endif
1203
1204 #if defined(__linux__) && defined(__x86_64__)
1205 // On Linux, the number of physical cores can be computed from /proc/cpuinfo,
1206 // using the number of unique physical/core id pairs. The following
1207 // implementation reads the /proc/cpuinfo format on an x86_64 system.
1208 static int computeHostNumPhysicalCores() {
1209   // Read /proc/cpuinfo as a stream (until EOF reached). It cannot be
1210   // mmapped because it appears to have 0 size.
1211   llvm::ErrorOr<std::unique_ptr<llvm::MemoryBuffer>> Text =
1212       llvm::MemoryBuffer::getFileAsStream("/proc/cpuinfo");
1213   if (std::error_code EC = Text.getError()) {
1214     llvm::errs() << "Can't read "
1215                  << "/proc/cpuinfo: " << EC.message() << "\n";
1216   }
1217   SmallVector<StringRef, 8> strs;
1218   (*Text)->getBuffer().split(strs, "\n", /*MaxSplit=*/-1,
1219                              /*KeepEmpty=*/false);
1220   int CurPhysicalId = -1;
1221   int CurCoreId = -1;
1222   SmallSet<std::pair<int, int>, 32> UniqueItems;
1223   for (auto &Line : strs) {
1224     Line = Line.trim();
1225     if (!Line.startswith("physical id") && !Line.startswith("core id"))
1226       continue;
1227     std::pair<StringRef, StringRef> Data = Line.split(':');
1228     auto Name = Data.first.trim();
1229     auto Val = Data.second.trim();
1230     if (Name == "physical id") {
1231       assert(CurPhysicalId == -1 &&
1232              "Expected a core id before seeing another physical id");
1233       Val.getAsInteger(10, CurPhysicalId);
1234     }
1235     if (Name == "core id") {
1236       assert(CurCoreId == -1 &&
1237              "Expected a physical id before seeing another core id");
1238       Val.getAsInteger(10, CurCoreId);
1239     }
1240     if (CurPhysicalId != -1 && CurCoreId != -1) {
1241       UniqueItems.insert(std::make_pair(CurPhysicalId, CurCoreId));
1242       CurPhysicalId = -1;
1243       CurCoreId = -1;
1244     }
1245   }
1246   return UniqueItems.size();
1247 }
1248 #elif defined(__APPLE__) && defined(__x86_64__)
1249 #include <sys/param.h>
1250 #include <sys/sysctl.h>
1251
1252 // Gets the number of *physical cores* on the machine.
1253 static int computeHostNumPhysicalCores() {
1254   uint32_t count;
1255   size_t len = sizeof(count);
1256   sysctlbyname("hw.physicalcpu", &count, &len, NULL, 0);
1257   if (count < 1) {
1258     int nm[2];
1259     nm[0] = CTL_HW;
1260     nm[1] = HW_AVAILCPU;
1261     sysctl(nm, 2, &count, &len, NULL, 0);
1262     if (count < 1)
1263       return -1;
1264   }
1265   return count;
1266 }
1267 #else
1268 // On other systems, return -1 to indicate unknown.
1269 static int computeHostNumPhysicalCores() { return -1; }
1270 #endif
1271
1272 int sys::getHostNumPhysicalCores() {
1273   static int NumCores = computeHostNumPhysicalCores();
1274   return NumCores;
1275 }
1276
1277 #if defined(__i386__) || defined(_M_IX86) || \
1278     defined(__x86_64__) || defined(_M_X64)
1279 bool sys::getHostCPUFeatures(StringMap<bool> &Features) {
1280   unsigned EAX = 0, EBX = 0, ECX = 0, EDX = 0;
1281   unsigned MaxLevel;
1282   union {
1283     unsigned u[3];
1284     char c[12];
1285   } text;
1286
1287   if (getX86CpuIDAndInfo(0, &MaxLevel, text.u + 0, text.u + 2, text.u + 1) ||
1288       MaxLevel < 1)
1289     return false;
1290
1291   getX86CpuIDAndInfo(1, &EAX, &EBX, &ECX, &EDX);
1292
1293   Features["cmov"] = (EDX >> 15) & 1;
1294   Features["mmx"] = (EDX >> 23) & 1;
1295   Features["sse"] = (EDX >> 25) & 1;
1296   Features["sse2"] = (EDX >> 26) & 1;
1297   Features["sse3"] = (ECX >> 0) & 1;
1298   Features["ssse3"] = (ECX >> 9) & 1;
1299   Features["sse4.1"] = (ECX >> 19) & 1;
1300   Features["sse4.2"] = (ECX >> 20) & 1;
1301
1302   Features["pclmul"] = (ECX >> 1) & 1;
1303   Features["cx16"] = (ECX >> 13) & 1;
1304   Features["movbe"] = (ECX >> 22) & 1;
1305   Features["popcnt"] = (ECX >> 23) & 1;
1306   Features["aes"] = (ECX >> 25) & 1;
1307   Features["rdrnd"] = (ECX >> 30) & 1;
1308
1309   // If CPUID indicates support for XSAVE, XRESTORE and AVX, and XGETBV
1310   // indicates that the AVX registers will be saved and restored on context
1311   // switch, then we have full AVX support.
1312   bool HasAVXSave = ((ECX >> 27) & 1) && ((ECX >> 28) & 1) &&
1313                     !getX86XCR0(&EAX, &EDX) && ((EAX & 0x6) == 0x6);
1314   Features["avx"] = HasAVXSave;
1315   Features["fma"] = HasAVXSave && (ECX >> 12) & 1;
1316   Features["f16c"] = HasAVXSave && (ECX >> 29) & 1;
1317
1318   // Only enable XSAVE if OS has enabled support for saving YMM state.
1319   Features["xsave"] = HasAVXSave && (ECX >> 26) & 1;
1320
1321   // AVX512 requires additional context to be saved by the OS.
1322   bool HasAVX512Save = HasAVXSave && ((EAX & 0xe0) == 0xe0);
1323
1324   unsigned MaxExtLevel;
1325   getX86CpuIDAndInfo(0x80000000, &MaxExtLevel, &EBX, &ECX, &EDX);
1326
1327   bool HasExtLeaf1 = MaxExtLevel >= 0x80000001 &&
1328                      !getX86CpuIDAndInfo(0x80000001, &EAX, &EBX, &ECX, &EDX);
1329   Features["lzcnt"] = HasExtLeaf1 && ((ECX >> 5) & 1);
1330   Features["sse4a"] = HasExtLeaf1 && ((ECX >> 6) & 1);
1331   Features["prfchw"] = HasExtLeaf1 && ((ECX >> 8) & 1);
1332   Features["xop"] = HasExtLeaf1 && ((ECX >> 11) & 1) && HasAVXSave;
1333   Features["fma4"] = HasExtLeaf1 && ((ECX >> 16) & 1) && HasAVXSave;
1334   Features["tbm"] = HasExtLeaf1 && ((ECX >> 21) & 1);
1335   Features["mwaitx"] = HasExtLeaf1 && ((ECX >> 29) & 1);
1336
1337   bool HasLeaf7 =
1338       MaxLevel >= 7 && !getX86CpuIDAndInfoEx(0x7, 0x0, &EAX, &EBX, &ECX, &EDX);
1339
1340   // AVX2 is only supported if we have the OS save support from AVX.
1341   Features["avx2"] = HasAVXSave && HasLeaf7 && ((EBX >> 5) & 1);
1342
1343   Features["fsgsbase"] = HasLeaf7 && ((EBX >> 0) & 1);
1344   Features["sgx"] = HasLeaf7 && ((EBX >> 2) & 1);
1345   Features["bmi"] = HasLeaf7 && ((EBX >> 3) & 1);
1346   Features["hle"] = HasLeaf7 && ((EBX >> 4) & 1);
1347   Features["bmi2"] = HasLeaf7 && ((EBX >> 8) & 1);
1348   Features["invpcid"] = HasLeaf7 && ((EBX >> 10) & 1);
1349   Features["rtm"] = HasLeaf7 && ((EBX >> 11) & 1);
1350   Features["rdseed"] = HasLeaf7 && ((EBX >> 18) & 1);
1351   Features["adx"] = HasLeaf7 && ((EBX >> 19) & 1);
1352   Features["smap"] = HasLeaf7 && ((EBX >> 20) & 1);
1353   Features["pcommit"] = HasLeaf7 && ((EBX >> 22) & 1);
1354   Features["clflushopt"] = HasLeaf7 && ((EBX >> 23) & 1);
1355   Features["clwb"] = HasLeaf7 && ((EBX >> 24) & 1);
1356   Features["sha"] = HasLeaf7 && ((EBX >> 29) & 1);
1357
1358   // AVX512 is only supported if the OS supports the context save for it.
1359   Features["avx512f"] = HasLeaf7 && ((EBX >> 16) & 1) && HasAVX512Save;
1360   Features["avx512dq"] = HasLeaf7 && ((EBX >> 17) & 1) && HasAVX512Save;
1361   Features["avx512ifma"] = HasLeaf7 && ((EBX >> 21) & 1) && HasAVX512Save;
1362   Features["avx512pf"] = HasLeaf7 && ((EBX >> 26) & 1) && HasAVX512Save;
1363   Features["avx512er"] = HasLeaf7 && ((EBX >> 27) & 1) && HasAVX512Save;
1364   Features["avx512cd"] = HasLeaf7 && ((EBX >> 28) & 1) && HasAVX512Save;
1365   Features["avx512bw"] = HasLeaf7 && ((EBX >> 30) & 1) && HasAVX512Save;
1366   Features["avx512vl"] = HasLeaf7 && ((EBX >> 31) & 1) && HasAVX512Save;
1367
1368   Features["prefetchwt1"] = HasLeaf7 && (ECX & 1);
1369   Features["avx512vbmi"] = HasLeaf7 && ((ECX >> 1) & 1) && HasAVX512Save;
1370   // Enable protection keys
1371   Features["pku"] = HasLeaf7 && ((ECX >> 4) & 1);
1372
1373   bool HasLeafD = MaxLevel >= 0xd &&
1374                   !getX86CpuIDAndInfoEx(0xd, 0x1, &EAX, &EBX, &ECX, &EDX);
1375
1376   // Only enable XSAVE if OS has enabled support for saving YMM state.
1377   Features["xsaveopt"] = HasAVXSave && HasLeafD && ((EAX >> 0) & 1);
1378   Features["xsavec"] = HasAVXSave && HasLeafD && ((EAX >> 1) & 1);
1379   Features["xsaves"] = HasAVXSave && HasLeafD && ((EAX >> 3) & 1);
1380
1381   return true;
1382 }
1383 #elif defined(__linux__) && (defined(__arm__) || defined(__aarch64__))
1384 bool sys::getHostCPUFeatures(StringMap<bool> &Features) {
1385   // Read 1024 bytes from /proc/cpuinfo, which should contain the Features line
1386   // in all cases.
1387   char buffer[1024];
1388   ssize_t CPUInfoSize = readCpuInfo(buffer, sizeof(buffer));
1389   if (CPUInfoSize == -1)
1390     return false;
1391
1392   StringRef Str(buffer, CPUInfoSize);
1393
1394   SmallVector<StringRef, 32> Lines;
1395   Str.split(Lines, "\n");
1396
1397   SmallVector<StringRef, 32> CPUFeatures;
1398
1399   // Look for the CPU features.
1400   for (unsigned I = 0, E = Lines.size(); I != E; ++I)
1401     if (Lines[I].startswith("Features")) {
1402       Lines[I].split(CPUFeatures, ' ');
1403       break;
1404     }
1405
1406 #if defined(__aarch64__)
1407   // Keep track of which crypto features we have seen
1408   enum { CAP_AES = 0x1, CAP_PMULL = 0x2, CAP_SHA1 = 0x4, CAP_SHA2 = 0x8 };
1409   uint32_t crypto = 0;
1410 #endif
1411
1412   for (unsigned I = 0, E = CPUFeatures.size(); I != E; ++I) {
1413     StringRef LLVMFeatureStr = StringSwitch<StringRef>(CPUFeatures[I])
1414 #if defined(__aarch64__)
1415                                    .Case("asimd", "neon")
1416                                    .Case("fp", "fp-armv8")
1417                                    .Case("crc32", "crc")
1418 #else
1419                                    .Case("half", "fp16")
1420                                    .Case("neon", "neon")
1421                                    .Case("vfpv3", "vfp3")
1422                                    .Case("vfpv3d16", "d16")
1423                                    .Case("vfpv4", "vfp4")
1424                                    .Case("idiva", "hwdiv-arm")
1425                                    .Case("idivt", "hwdiv")
1426 #endif
1427                                    .Default("");
1428
1429 #if defined(__aarch64__)
1430     // We need to check crypto separately since we need all of the crypto
1431     // extensions to enable the subtarget feature
1432     if (CPUFeatures[I] == "aes")
1433       crypto |= CAP_AES;
1434     else if (CPUFeatures[I] == "pmull")
1435       crypto |= CAP_PMULL;
1436     else if (CPUFeatures[I] == "sha1")
1437       crypto |= CAP_SHA1;
1438     else if (CPUFeatures[I] == "sha2")
1439       crypto |= CAP_SHA2;
1440 #endif
1441
1442     if (LLVMFeatureStr != "")
1443       Features[LLVMFeatureStr] = true;
1444   }
1445
1446 #if defined(__aarch64__)
1447   // If we have all crypto bits we can add the feature
1448   if (crypto == (CAP_AES | CAP_PMULL | CAP_SHA1 | CAP_SHA2))
1449     Features["crypto"] = true;
1450 #endif
1451
1452   return true;
1453 }
1454 #else
1455 bool sys::getHostCPUFeatures(StringMap<bool> &Features) { return false; }
1456 #endif
1457
1458 std::string sys::getProcessTriple() {
1459   Triple PT(Triple::normalize(LLVM_HOST_TRIPLE));
1460
1461   if (sizeof(void *) == 8 && PT.isArch32Bit())
1462     PT = PT.get64BitArchVariant();
1463   if (sizeof(void *) == 4 && PT.isArch64Bit())
1464     PT = PT.get32BitArchVariant();
1465
1466   return PT.str();
1467 }