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