1 //===--- Targets.cpp - Implement target feature support -------------------===//
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 construction of a TargetInfo object from a
11 // target triple.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "clang/Basic/TargetInfo.h"
16 #include "clang/Basic/Builtins.h"
17 #include "clang/Basic/Diagnostic.h"
18 #include "clang/Basic/LangOptions.h"
19 #include "clang/Basic/MacroBuilder.h"
20 #include "clang/Basic/TargetBuiltins.h"
21 #include "clang/Basic/TargetOptions.h"
22 #include "clang/Basic/Version.h"
23 #include "llvm/ADT/APFloat.h"
24 #include "llvm/ADT/STLExtras.h"
25 #include "llvm/ADT/StringExtras.h"
26 #include "llvm/ADT/StringRef.h"
27 #include "llvm/ADT/StringSwitch.h"
28 #include "llvm/ADT/Triple.h"
29 #include "llvm/MC/MCSectionMachO.h"
30 #include "llvm/Support/ErrorHandling.h"
31 #include "llvm/Support/TargetParser.h"
32 #include <algorithm>
33 #include <memory>
34 
35 using namespace clang;
36 
37 //===----------------------------------------------------------------------===//
38 //  Common code shared among targets.
39 //===----------------------------------------------------------------------===//
40 
41 /// DefineStd - Define a macro name and standard variants.  For example if
42 /// MacroName is "unix", then this will define "__unix", "__unix__", and "unix"
43 /// when in GNU mode.
DefineStd(MacroBuilder & Builder,StringRef MacroName,const LangOptions & Opts)44 static void DefineStd(MacroBuilder &Builder, StringRef MacroName,
45                       const LangOptions &Opts) {
46   assert(MacroName[0] != '_' && "Identifier should be in the user's namespace");
47 
48   // If in GNU mode (e.g. -std=gnu99 but not -std=c99) define the raw identifier
49   // in the user's namespace.
50   if (Opts.GNUMode)
51     Builder.defineMacro(MacroName);
52 
53   // Define __unix.
54   Builder.defineMacro("__" + MacroName);
55 
56   // Define __unix__.
57   Builder.defineMacro("__" + MacroName + "__");
58 }
59 
defineCPUMacros(MacroBuilder & Builder,StringRef CPUName,bool Tuning=true)60 static void defineCPUMacros(MacroBuilder &Builder, StringRef CPUName,
61                             bool Tuning = true) {
62   Builder.defineMacro("__" + CPUName);
63   Builder.defineMacro("__" + CPUName + "__");
64   if (Tuning)
65     Builder.defineMacro("__tune_" + CPUName + "__");
66 }
67 
68 //===----------------------------------------------------------------------===//
69 // Defines specific to certain operating systems.
70 //===----------------------------------------------------------------------===//
71 
72 namespace {
73 template<typename TgtInfo>
74 class OSTargetInfo : public TgtInfo {
75 protected:
76   virtual void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
77                             MacroBuilder &Builder) const=0;
78 public:
OSTargetInfo(const llvm::Triple & Triple)79   OSTargetInfo(const llvm::Triple &Triple) : TgtInfo(Triple) {}
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const80   void getTargetDefines(const LangOptions &Opts,
81                         MacroBuilder &Builder) const override {
82     TgtInfo::getTargetDefines(Opts, Builder);
83     getOSDefines(Opts, TgtInfo::getTriple(), Builder);
84   }
85 
86 };
87 
88 // CloudABI Target
89 template <typename Target>
90 class CloudABITargetInfo : public OSTargetInfo<Target> {
91 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const92   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
93                     MacroBuilder &Builder) const override {
94     Builder.defineMacro("__CloudABI__");
95     Builder.defineMacro("__ELF__");
96 
97     // CloudABI uses ISO/IEC 10646:2012 for wchar_t, char16_t and char32_t.
98     Builder.defineMacro("__STDC_ISO_10646__", "201206L");
99     Builder.defineMacro("__STDC_UTF_16__");
100     Builder.defineMacro("__STDC_UTF_32__");
101   }
102 
103 public:
CloudABITargetInfo(const llvm::Triple & Triple)104   CloudABITargetInfo(const llvm::Triple &Triple)
105       : OSTargetInfo<Target>(Triple) {
106     this->UserLabelPrefix = "";
107   }
108 };
109 
getDarwinDefines(MacroBuilder & Builder,const LangOptions & Opts,const llvm::Triple & Triple,StringRef & PlatformName,VersionTuple & PlatformMinVersion)110 static void getDarwinDefines(MacroBuilder &Builder, const LangOptions &Opts,
111                              const llvm::Triple &Triple,
112                              StringRef &PlatformName,
113                              VersionTuple &PlatformMinVersion) {
114   Builder.defineMacro("__APPLE_CC__", "6000");
115   Builder.defineMacro("__APPLE__");
116   Builder.defineMacro("OBJC_NEW_PROPERTIES");
117   // AddressSanitizer doesn't play well with source fortification, which is on
118   // by default on Darwin.
119   if (Opts.Sanitize.has(SanitizerKind::Address))
120     Builder.defineMacro("_FORTIFY_SOURCE", "0");
121 
122   // Darwin defines __weak, __strong, and __unsafe_unretained even in C mode.
123   if (!Opts.ObjC1) {
124     // __weak is always defined, for use in blocks and with objc pointers.
125     Builder.defineMacro("__weak", "__attribute__((objc_gc(weak)))");
126     Builder.defineMacro("__strong", "");
127     Builder.defineMacro("__unsafe_unretained", "");
128   }
129 
130   if (Opts.Static)
131     Builder.defineMacro("__STATIC__");
132   else
133     Builder.defineMacro("__DYNAMIC__");
134 
135   if (Opts.POSIXThreads)
136     Builder.defineMacro("_REENTRANT");
137 
138   // Get the platform type and version number from the triple.
139   unsigned Maj, Min, Rev;
140   if (Triple.isMacOSX()) {
141     Triple.getMacOSXVersion(Maj, Min, Rev);
142     PlatformName = "macosx";
143   } else {
144     Triple.getOSVersion(Maj, Min, Rev);
145     PlatformName = llvm::Triple::getOSTypeName(Triple.getOS());
146   }
147 
148   // If -target arch-pc-win32-macho option specified, we're
149   // generating code for Win32 ABI. No need to emit
150   // __ENVIRONMENT_XX_OS_VERSION_MIN_REQUIRED__.
151   if (PlatformName == "win32") {
152     PlatformMinVersion = VersionTuple(Maj, Min, Rev);
153     return;
154   }
155 
156   // Set the appropriate OS version define.
157   if (Triple.isiOS()) {
158     assert(Maj < 10 && Min < 100 && Rev < 100 && "Invalid version!");
159     char Str[6];
160     Str[0] = '0' + Maj;
161     Str[1] = '0' + (Min / 10);
162     Str[2] = '0' + (Min % 10);
163     Str[3] = '0' + (Rev / 10);
164     Str[4] = '0' + (Rev % 10);
165     Str[5] = '\0';
166     if (Triple.isTvOS())
167       Builder.defineMacro("__ENVIRONMENT_TV_OS_VERSION_MIN_REQUIRED__", Str);
168     else
169       Builder.defineMacro("__ENVIRONMENT_IPHONE_OS_VERSION_MIN_REQUIRED__",
170                           Str);
171 
172   } else if (Triple.isWatchOS()) {
173     assert(Maj < 10 && Min < 100 && Rev < 100 && "Invalid version!");
174     char Str[6];
175     Str[0] = '0' + Maj;
176     Str[1] = '0' + (Min / 10);
177     Str[2] = '0' + (Min % 10);
178     Str[3] = '0' + (Rev / 10);
179     Str[4] = '0' + (Rev % 10);
180     Str[5] = '\0';
181     Builder.defineMacro("__ENVIRONMENT_WATCH_OS_VERSION_MIN_REQUIRED__", Str);
182   } else if (Triple.isMacOSX()) {
183     // Note that the Driver allows versions which aren't representable in the
184     // define (because we only get a single digit for the minor and micro
185     // revision numbers). So, we limit them to the maximum representable
186     // version.
187     assert(Maj < 100 && Min < 100 && Rev < 100 && "Invalid version!");
188     char Str[7];
189     if (Maj < 10 || (Maj == 10 && Min < 10)) {
190       Str[0] = '0' + (Maj / 10);
191       Str[1] = '0' + (Maj % 10);
192       Str[2] = '0' + std::min(Min, 9U);
193       Str[3] = '0' + std::min(Rev, 9U);
194       Str[4] = '\0';
195     } else {
196       // Handle versions > 10.9.
197       Str[0] = '0' + (Maj / 10);
198       Str[1] = '0' + (Maj % 10);
199       Str[2] = '0' + (Min / 10);
200       Str[3] = '0' + (Min % 10);
201       Str[4] = '0' + (Rev / 10);
202       Str[5] = '0' + (Rev % 10);
203       Str[6] = '\0';
204     }
205     Builder.defineMacro("__ENVIRONMENT_MAC_OS_X_VERSION_MIN_REQUIRED__", Str);
206   }
207 
208   // Tell users about the kernel if there is one.
209   if (Triple.isOSDarwin())
210     Builder.defineMacro("__MACH__");
211 
212   PlatformMinVersion = VersionTuple(Maj, Min, Rev);
213 }
214 
215 template<typename Target>
216 class DarwinTargetInfo : public OSTargetInfo<Target> {
217 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const218   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
219                     MacroBuilder &Builder) const override {
220     getDarwinDefines(Builder, Opts, Triple, this->PlatformName,
221                      this->PlatformMinVersion);
222   }
223 
224 public:
DarwinTargetInfo(const llvm::Triple & Triple)225   DarwinTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) {
226     this->TLSSupported = Triple.isMacOSX() && !Triple.isMacOSXVersionLT(10, 7);
227     this->MCountName = "\01mcount";
228   }
229 
isValidSectionSpecifier(StringRef SR) const230   std::string isValidSectionSpecifier(StringRef SR) const override {
231     // Let MCSectionMachO validate this.
232     StringRef Segment, Section;
233     unsigned TAA, StubSize;
234     bool HasTAA;
235     return llvm::MCSectionMachO::ParseSectionSpecifier(SR, Segment, Section,
236                                                        TAA, HasTAA, StubSize);
237   }
238 
getStaticInitSectionSpecifier() const239   const char *getStaticInitSectionSpecifier() const override {
240     // FIXME: We should return 0 when building kexts.
241     return "__TEXT,__StaticInit,regular,pure_instructions";
242   }
243 
244   /// Darwin does not support protected visibility.  Darwin's "default"
245   /// is very similar to ELF's "protected";  Darwin requires a "weak"
246   /// attribute on declarations that can be dynamically replaced.
hasProtectedVisibility() const247   bool hasProtectedVisibility() const override {
248     return false;
249   }
250 };
251 
252 
253 // DragonFlyBSD Target
254 template<typename Target>
255 class DragonFlyBSDTargetInfo : public OSTargetInfo<Target> {
256 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const257   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
258                     MacroBuilder &Builder) const override {
259     // DragonFly defines; list based off of gcc output
260     Builder.defineMacro("__DragonFly__");
261     Builder.defineMacro("__DragonFly_cc_version", "100001");
262     Builder.defineMacro("__ELF__");
263     Builder.defineMacro("__KPRINTF_ATTRIBUTE__");
264     Builder.defineMacro("__tune_i386__");
265     DefineStd(Builder, "unix", Opts);
266   }
267 public:
DragonFlyBSDTargetInfo(const llvm::Triple & Triple)268   DragonFlyBSDTargetInfo(const llvm::Triple &Triple)
269       : OSTargetInfo<Target>(Triple) {
270     this->UserLabelPrefix = "";
271 
272     switch (Triple.getArch()) {
273     default:
274     case llvm::Triple::x86:
275     case llvm::Triple::x86_64:
276       this->MCountName = ".mcount";
277       break;
278     }
279   }
280 };
281 
282 // FreeBSD Target
283 template<typename Target>
284 class FreeBSDTargetInfo : public OSTargetInfo<Target> {
285 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const286   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
287                     MacroBuilder &Builder) const override {
288     // FreeBSD defines; list based off of gcc output
289 
290     unsigned Release = Triple.getOSMajorVersion();
291     if (Release == 0U)
292       Release = 8;
293 
294     Builder.defineMacro("__FreeBSD__", Twine(Release));
295     Builder.defineMacro("__FreeBSD_cc_version", Twine(Release * 100000U + 1U));
296     Builder.defineMacro("__KPRINTF_ATTRIBUTE__");
297     DefineStd(Builder, "unix", Opts);
298     Builder.defineMacro("__ELF__");
299 
300     // On FreeBSD, wchar_t contains the number of the code point as
301     // used by the character set of the locale. These character sets are
302     // not necessarily a superset of ASCII.
303     //
304     // FIXME: This is wrong; the macro refers to the numerical values
305     // of wchar_t *literals*, which are not locale-dependent. However,
306     // FreeBSD systems apparently depend on us getting this wrong, and
307     // setting this to 1 is conforming even if all the basic source
308     // character literals have the same encoding as char and wchar_t.
309     Builder.defineMacro("__STDC_MB_MIGHT_NEQ_WC__", "1");
310   }
311 public:
FreeBSDTargetInfo(const llvm::Triple & Triple)312   FreeBSDTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) {
313     this->UserLabelPrefix = "";
314 
315     switch (Triple.getArch()) {
316     default:
317     case llvm::Triple::x86:
318     case llvm::Triple::x86_64:
319       this->MCountName = ".mcount";
320       break;
321     case llvm::Triple::mips:
322     case llvm::Triple::mipsel:
323     case llvm::Triple::ppc:
324     case llvm::Triple::ppc64:
325     case llvm::Triple::ppc64le:
326       this->MCountName = "_mcount";
327       break;
328     case llvm::Triple::arm:
329       this->MCountName = "__mcount";
330       break;
331     }
332   }
333 };
334 
335 // GNU/kFreeBSD Target
336 template<typename Target>
337 class KFreeBSDTargetInfo : public OSTargetInfo<Target> {
338 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const339   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
340                     MacroBuilder &Builder) const override {
341     // GNU/kFreeBSD defines; list based off of gcc output
342 
343     DefineStd(Builder, "unix", Opts);
344     Builder.defineMacro("__FreeBSD_kernel__");
345     Builder.defineMacro("__GLIBC__");
346     Builder.defineMacro("__ELF__");
347     if (Opts.POSIXThreads)
348       Builder.defineMacro("_REENTRANT");
349     if (Opts.CPlusPlus)
350       Builder.defineMacro("_GNU_SOURCE");
351   }
352 public:
KFreeBSDTargetInfo(const llvm::Triple & Triple)353   KFreeBSDTargetInfo(const llvm::Triple &Triple)
354       : OSTargetInfo<Target>(Triple) {
355     this->UserLabelPrefix = "";
356   }
357 };
358 
359 // Minix Target
360 template<typename Target>
361 class MinixTargetInfo : public OSTargetInfo<Target> {
362 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const363   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
364                     MacroBuilder &Builder) const override {
365     // Minix defines
366 
367     Builder.defineMacro("__minix", "3");
368     Builder.defineMacro("_EM_WSIZE", "4");
369     Builder.defineMacro("_EM_PSIZE", "4");
370     Builder.defineMacro("_EM_SSIZE", "2");
371     Builder.defineMacro("_EM_LSIZE", "4");
372     Builder.defineMacro("_EM_FSIZE", "4");
373     Builder.defineMacro("_EM_DSIZE", "8");
374     Builder.defineMacro("__ELF__");
375     DefineStd(Builder, "unix", Opts);
376   }
377 public:
MinixTargetInfo(const llvm::Triple & Triple)378   MinixTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) {
379     this->UserLabelPrefix = "";
380   }
381 };
382 
383 // Linux target
384 template<typename Target>
385 class LinuxTargetInfo : public OSTargetInfo<Target> {
386 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const387   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
388                     MacroBuilder &Builder) const override {
389     // Linux defines; list based off of gcc output
390     DefineStd(Builder, "unix", Opts);
391     DefineStd(Builder, "linux", Opts);
392     Builder.defineMacro("__gnu_linux__");
393     Builder.defineMacro("__ELF__");
394     if (Triple.isAndroid()) {
395       Builder.defineMacro("__ANDROID__", "1");
396       unsigned Maj, Min, Rev;
397       Triple.getEnvironmentVersion(Maj, Min, Rev);
398       this->PlatformName = "android";
399       this->PlatformMinVersion = VersionTuple(Maj, Min, Rev);
400     }
401     if (Opts.POSIXThreads)
402       Builder.defineMacro("_REENTRANT");
403     if (Opts.CPlusPlus)
404       Builder.defineMacro("_GNU_SOURCE");
405   }
406 public:
LinuxTargetInfo(const llvm::Triple & Triple)407   LinuxTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) {
408     this->UserLabelPrefix = "";
409     this->WIntType = TargetInfo::UnsignedInt;
410 
411     switch (Triple.getArch()) {
412     default:
413       break;
414     case llvm::Triple::ppc:
415     case llvm::Triple::ppc64:
416     case llvm::Triple::ppc64le:
417       this->MCountName = "_mcount";
418       break;
419     }
420   }
421 
getStaticInitSectionSpecifier() const422   const char *getStaticInitSectionSpecifier() const override {
423     return ".text.startup";
424   }
425 };
426 
427 // NetBSD Target
428 template<typename Target>
429 class NetBSDTargetInfo : public OSTargetInfo<Target> {
430 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const431   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
432                     MacroBuilder &Builder) const override {
433     // NetBSD defines; list based off of gcc output
434     Builder.defineMacro("__NetBSD__");
435     Builder.defineMacro("__unix__");
436     Builder.defineMacro("__ELF__");
437     if (Opts.POSIXThreads)
438       Builder.defineMacro("_POSIX_THREADS");
439 
440     switch (Triple.getArch()) {
441     default:
442       break;
443     case llvm::Triple::arm:
444     case llvm::Triple::armeb:
445     case llvm::Triple::thumb:
446     case llvm::Triple::thumbeb:
447       Builder.defineMacro("__ARM_DWARF_EH__");
448       break;
449     }
450   }
451 public:
NetBSDTargetInfo(const llvm::Triple & Triple)452   NetBSDTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) {
453     this->UserLabelPrefix = "";
454     this->MCountName = "_mcount";
455   }
456 };
457 
458 // OpenBSD Target
459 template<typename Target>
460 class OpenBSDTargetInfo : public OSTargetInfo<Target> {
461 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const462   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
463                     MacroBuilder &Builder) const override {
464     // OpenBSD defines; list based off of gcc output
465 
466     Builder.defineMacro("__OpenBSD__");
467     DefineStd(Builder, "unix", Opts);
468     Builder.defineMacro("__ELF__");
469     if (Opts.POSIXThreads)
470       Builder.defineMacro("_REENTRANT");
471   }
472 public:
OpenBSDTargetInfo(const llvm::Triple & Triple)473   OpenBSDTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) {
474     this->UserLabelPrefix = "";
475     this->TLSSupported = false;
476 
477       switch (Triple.getArch()) {
478         default:
479         case llvm::Triple::x86:
480         case llvm::Triple::x86_64:
481         case llvm::Triple::arm:
482         case llvm::Triple::sparc:
483           this->MCountName = "__mcount";
484           break;
485         case llvm::Triple::mips64:
486         case llvm::Triple::mips64el:
487         case llvm::Triple::ppc:
488         case llvm::Triple::sparcv9:
489           this->MCountName = "_mcount";
490           break;
491       }
492   }
493 };
494 
495 // Bitrig Target
496 template<typename Target>
497 class BitrigTargetInfo : public OSTargetInfo<Target> {
498 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const499   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
500                     MacroBuilder &Builder) const override {
501     // Bitrig defines; list based off of gcc output
502 
503     Builder.defineMacro("__Bitrig__");
504     DefineStd(Builder, "unix", Opts);
505     Builder.defineMacro("__ELF__");
506     if (Opts.POSIXThreads)
507       Builder.defineMacro("_REENTRANT");
508 
509     switch (Triple.getArch()) {
510     default:
511       break;
512     case llvm::Triple::arm:
513     case llvm::Triple::armeb:
514     case llvm::Triple::thumb:
515     case llvm::Triple::thumbeb:
516       Builder.defineMacro("__ARM_DWARF_EH__");
517       break;
518     }
519   }
520 public:
BitrigTargetInfo(const llvm::Triple & Triple)521   BitrigTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) {
522     this->UserLabelPrefix = "";
523     this->MCountName = "__mcount";
524   }
525 };
526 
527 // PSP Target
528 template<typename Target>
529 class PSPTargetInfo : public OSTargetInfo<Target> {
530 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const531   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
532                     MacroBuilder &Builder) const override {
533     // PSP defines; list based on the output of the pspdev gcc toolchain.
534     Builder.defineMacro("PSP");
535     Builder.defineMacro("_PSP");
536     Builder.defineMacro("__psp__");
537     Builder.defineMacro("__ELF__");
538   }
539 public:
PSPTargetInfo(const llvm::Triple & Triple)540   PSPTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) {
541     this->UserLabelPrefix = "";
542   }
543 };
544 
545 // PS3 PPU Target
546 template<typename Target>
547 class PS3PPUTargetInfo : public OSTargetInfo<Target> {
548 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const549   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
550                     MacroBuilder &Builder) const override {
551     // PS3 PPU defines.
552     Builder.defineMacro("__PPC__");
553     Builder.defineMacro("__PPU__");
554     Builder.defineMacro("__CELLOS_LV2__");
555     Builder.defineMacro("__ELF__");
556     Builder.defineMacro("__LP32__");
557     Builder.defineMacro("_ARCH_PPC64");
558     Builder.defineMacro("__powerpc64__");
559   }
560 public:
PS3PPUTargetInfo(const llvm::Triple & Triple)561   PS3PPUTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) {
562     this->UserLabelPrefix = "";
563     this->LongWidth = this->LongAlign = 32;
564     this->PointerWidth = this->PointerAlign = 32;
565     this->IntMaxType = TargetInfo::SignedLongLong;
566     this->Int64Type = TargetInfo::SignedLongLong;
567     this->SizeType = TargetInfo::UnsignedInt;
568     this->DataLayoutString = "E-m:e-p:32:32-i64:64-n32:64";
569   }
570 };
571 
572 template <typename Target>
573 class PS4OSTargetInfo : public OSTargetInfo<Target> {
574 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const575   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
576                     MacroBuilder &Builder) const override {
577     Builder.defineMacro("__FreeBSD__", "9");
578     Builder.defineMacro("__FreeBSD_cc_version", "900001");
579     Builder.defineMacro("__KPRINTF_ATTRIBUTE__");
580     DefineStd(Builder, "unix", Opts);
581     Builder.defineMacro("__ELF__");
582     Builder.defineMacro("__PS4__");
583   }
584 public:
PS4OSTargetInfo(const llvm::Triple & Triple)585   PS4OSTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) {
586     this->WCharType = this->UnsignedShort;
587 
588     // On PS4, TLS variable cannot be aligned to more than 32 bytes (256 bits).
589     this->MaxTLSAlign = 256;
590     this->UserLabelPrefix = "";
591 
592     switch (Triple.getArch()) {
593     default:
594     case llvm::Triple::x86_64:
595       this->MCountName = ".mcount";
596       break;
597     }
598   }
599 };
600 
601 // Solaris target
602 template<typename Target>
603 class SolarisTargetInfo : public OSTargetInfo<Target> {
604 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const605   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
606                     MacroBuilder &Builder) const override {
607     DefineStd(Builder, "sun", Opts);
608     DefineStd(Builder, "unix", Opts);
609     Builder.defineMacro("__ELF__");
610     Builder.defineMacro("__svr4__");
611     Builder.defineMacro("__SVR4");
612     // Solaris headers require _XOPEN_SOURCE to be set to 600 for C99 and
613     // newer, but to 500 for everything else.  feature_test.h has a check to
614     // ensure that you are not using C99 with an old version of X/Open or C89
615     // with a new version.
616     if (Opts.C99)
617       Builder.defineMacro("_XOPEN_SOURCE", "600");
618     else
619       Builder.defineMacro("_XOPEN_SOURCE", "500");
620     if (Opts.CPlusPlus)
621       Builder.defineMacro("__C99FEATURES__");
622     Builder.defineMacro("_LARGEFILE_SOURCE");
623     Builder.defineMacro("_LARGEFILE64_SOURCE");
624     Builder.defineMacro("__EXTENSIONS__");
625     Builder.defineMacro("_REENTRANT");
626   }
627 public:
SolarisTargetInfo(const llvm::Triple & Triple)628   SolarisTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) {
629     this->UserLabelPrefix = "";
630     this->WCharType = this->SignedInt;
631     // FIXME: WIntType should be SignedLong
632   }
633 };
634 
635 // Windows target
636 template<typename Target>
637 class WindowsTargetInfo : public OSTargetInfo<Target> {
638 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const639   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
640                     MacroBuilder &Builder) const override {
641     Builder.defineMacro("_WIN32");
642   }
getVisualStudioDefines(const LangOptions & Opts,MacroBuilder & Builder) const643   void getVisualStudioDefines(const LangOptions &Opts,
644                               MacroBuilder &Builder) const {
645     if (Opts.CPlusPlus) {
646       if (Opts.RTTIData)
647         Builder.defineMacro("_CPPRTTI");
648 
649       if (Opts.CXXExceptions)
650         Builder.defineMacro("_CPPUNWIND");
651     }
652 
653     if (Opts.Bool)
654       Builder.defineMacro("__BOOL_DEFINED");
655 
656     if (!Opts.CharIsSigned)
657       Builder.defineMacro("_CHAR_UNSIGNED");
658 
659     // FIXME: POSIXThreads isn't exactly the option this should be defined for,
660     //        but it works for now.
661     if (Opts.POSIXThreads)
662       Builder.defineMacro("_MT");
663 
664     if (Opts.MSCompatibilityVersion) {
665       Builder.defineMacro("_MSC_VER",
666                           Twine(Opts.MSCompatibilityVersion / 100000));
667       Builder.defineMacro("_MSC_FULL_VER", Twine(Opts.MSCompatibilityVersion));
668       // FIXME We cannot encode the revision information into 32-bits
669       Builder.defineMacro("_MSC_BUILD", Twine(1));
670 
671       if (Opts.CPlusPlus11 && Opts.isCompatibleWithMSVC(LangOptions::MSVC2015))
672         Builder.defineMacro("_HAS_CHAR16_T_LANGUAGE_SUPPORT", Twine(1));
673     }
674 
675     if (Opts.MicrosoftExt) {
676       Builder.defineMacro("_MSC_EXTENSIONS");
677 
678       if (Opts.CPlusPlus11) {
679         Builder.defineMacro("_RVALUE_REFERENCES_V2_SUPPORTED");
680         Builder.defineMacro("_RVALUE_REFERENCES_SUPPORTED");
681         Builder.defineMacro("_NATIVE_NULLPTR_SUPPORTED");
682       }
683     }
684 
685     Builder.defineMacro("_INTEGRAL_MAX_BITS", "64");
686   }
687 
688 public:
WindowsTargetInfo(const llvm::Triple & Triple)689   WindowsTargetInfo(const llvm::Triple &Triple)
690       : OSTargetInfo<Target>(Triple) {}
691 };
692 
693 template <typename Target>
694 class NaClTargetInfo : public OSTargetInfo<Target> {
695 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const696   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
697                     MacroBuilder &Builder) const override {
698     if (Opts.POSIXThreads)
699       Builder.defineMacro("_REENTRANT");
700     if (Opts.CPlusPlus)
701       Builder.defineMacro("_GNU_SOURCE");
702 
703     DefineStd(Builder, "unix", Opts);
704     Builder.defineMacro("__ELF__");
705     Builder.defineMacro("__native_client__");
706   }
707 
708 public:
NaClTargetInfo(const llvm::Triple & Triple)709   NaClTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) {
710     this->UserLabelPrefix = "";
711     this->LongAlign = 32;
712     this->LongWidth = 32;
713     this->PointerAlign = 32;
714     this->PointerWidth = 32;
715     this->IntMaxType = TargetInfo::SignedLongLong;
716     this->Int64Type = TargetInfo::SignedLongLong;
717     this->DoubleAlign = 64;
718     this->LongDoubleWidth = 64;
719     this->LongDoubleAlign = 64;
720     this->LongLongWidth = 64;
721     this->LongLongAlign = 64;
722     this->SizeType = TargetInfo::UnsignedInt;
723     this->PtrDiffType = TargetInfo::SignedInt;
724     this->IntPtrType = TargetInfo::SignedInt;
725     // RegParmMax is inherited from the underlying architecture
726     this->LongDoubleFormat = &llvm::APFloat::IEEEdouble;
727     if (Triple.getArch() == llvm::Triple::arm) {
728       // Handled in ARM's setABI().
729     } else if (Triple.getArch() == llvm::Triple::x86) {
730       this->DataLayoutString = "e-m:e-p:32:32-i64:64-n8:16:32-S128";
731     } else if (Triple.getArch() == llvm::Triple::x86_64) {
732       this->DataLayoutString = "e-m:e-p:32:32-i64:64-n8:16:32:64-S128";
733     } else if (Triple.getArch() == llvm::Triple::mipsel) {
734       // Handled on mips' setDataLayoutString.
735     } else {
736       assert(Triple.getArch() == llvm::Triple::le32);
737       this->DataLayoutString = "e-p:32:32-i64:64";
738     }
739   }
740 };
741 
742 // WebAssembly target
743 template <typename Target>
744 class WebAssemblyOSTargetInfo : public OSTargetInfo<Target> {
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const745   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
746                     MacroBuilder &Builder) const final {
747     // A common platform macro.
748     if (Opts.POSIXThreads)
749       Builder.defineMacro("_REENTRANT");
750     // Follow g++ convention and predefine _GNU_SOURCE for C++.
751     if (Opts.CPlusPlus)
752       Builder.defineMacro("_GNU_SOURCE");
753   }
754 
755   // As an optimization, group static init code together in a section.
getStaticInitSectionSpecifier() const756   const char *getStaticInitSectionSpecifier() const final {
757     return ".text.__startup";
758   }
759 
760 public:
WebAssemblyOSTargetInfo(const llvm::Triple & Triple)761   explicit WebAssemblyOSTargetInfo(const llvm::Triple &Triple)
762       : OSTargetInfo<Target>(Triple) {
763     this->MCountName = "__mcount";
764     this->UserLabelPrefix = "";
765     this->TheCXXABI.set(TargetCXXABI::WebAssembly);
766   }
767 };
768 
769 //===----------------------------------------------------------------------===//
770 // Specific target implementations.
771 //===----------------------------------------------------------------------===//
772 
773 // PPC abstract base class
774 class PPCTargetInfo : public TargetInfo {
775   static const Builtin::Info BuiltinInfo[];
776   static const char * const GCCRegNames[];
777   static const TargetInfo::GCCRegAlias GCCRegAliases[];
778   std::string CPU;
779 
780   // Target cpu features.
781   bool HasVSX;
782   bool HasP8Vector;
783   bool HasP8Crypto;
784   bool HasDirectMove;
785   bool HasQPX;
786   bool HasHTM;
787   bool HasBPERMD;
788   bool HasExtDiv;
789 
790 protected:
791   std::string ABI;
792 
793 public:
PPCTargetInfo(const llvm::Triple & Triple)794   PPCTargetInfo(const llvm::Triple &Triple)
795     : TargetInfo(Triple), HasVSX(false), HasP8Vector(false),
796       HasP8Crypto(false), HasDirectMove(false), HasQPX(false), HasHTM(false),
797       HasBPERMD(false), HasExtDiv(false) {
798     BigEndian = (Triple.getArch() != llvm::Triple::ppc64le);
799     SimdDefaultAlign = 128;
800     LongDoubleWidth = LongDoubleAlign = 128;
801     LongDoubleFormat = &llvm::APFloat::PPCDoubleDouble;
802   }
803 
804   /// \brief Flags for architecture specific defines.
805   typedef enum {
806     ArchDefineNone  = 0,
807     ArchDefineName  = 1 << 0, // <name> is substituted for arch name.
808     ArchDefinePpcgr = 1 << 1,
809     ArchDefinePpcsq = 1 << 2,
810     ArchDefine440   = 1 << 3,
811     ArchDefine603   = 1 << 4,
812     ArchDefine604   = 1 << 5,
813     ArchDefinePwr4  = 1 << 6,
814     ArchDefinePwr5  = 1 << 7,
815     ArchDefinePwr5x = 1 << 8,
816     ArchDefinePwr6  = 1 << 9,
817     ArchDefinePwr6x = 1 << 10,
818     ArchDefinePwr7  = 1 << 11,
819     ArchDefinePwr8  = 1 << 12,
820     ArchDefineA2    = 1 << 13,
821     ArchDefineA2q   = 1 << 14
822   } ArchDefineTypes;
823 
824   // Note: GCC recognizes the following additional cpus:
825   //  401, 403, 405, 405fp, 440fp, 464, 464fp, 476, 476fp, 505, 740, 801,
826   //  821, 823, 8540, 8548, e300c2, e300c3, e500mc64, e6500, 860, cell,
827   //  titan, rs64.
setCPU(const std::string & Name)828   bool setCPU(const std::string &Name) override {
829     bool CPUKnown = llvm::StringSwitch<bool>(Name)
830       .Case("generic", true)
831       .Case("440", true)
832       .Case("450", true)
833       .Case("601", true)
834       .Case("602", true)
835       .Case("603", true)
836       .Case("603e", true)
837       .Case("603ev", true)
838       .Case("604", true)
839       .Case("604e", true)
840       .Case("620", true)
841       .Case("630", true)
842       .Case("g3", true)
843       .Case("7400", true)
844       .Case("g4", true)
845       .Case("7450", true)
846       .Case("g4+", true)
847       .Case("750", true)
848       .Case("970", true)
849       .Case("g5", true)
850       .Case("a2", true)
851       .Case("a2q", true)
852       .Case("e500mc", true)
853       .Case("e5500", true)
854       .Case("power3", true)
855       .Case("pwr3", true)
856       .Case("power4", true)
857       .Case("pwr4", true)
858       .Case("power5", true)
859       .Case("pwr5", true)
860       .Case("power5x", true)
861       .Case("pwr5x", true)
862       .Case("power6", true)
863       .Case("pwr6", true)
864       .Case("power6x", true)
865       .Case("pwr6x", true)
866       .Case("power7", true)
867       .Case("pwr7", true)
868       .Case("power8", true)
869       .Case("pwr8", true)
870       .Case("powerpc", true)
871       .Case("ppc", true)
872       .Case("powerpc64", true)
873       .Case("ppc64", true)
874       .Case("powerpc64le", true)
875       .Case("ppc64le", true)
876       .Default(false);
877 
878     if (CPUKnown)
879       CPU = Name;
880 
881     return CPUKnown;
882   }
883 
884 
getABI() const885   StringRef getABI() const override { return ABI; }
886 
getTargetBuiltins() const887   ArrayRef<Builtin::Info> getTargetBuiltins() const override {
888     return llvm::makeArrayRef(BuiltinInfo,
889                              clang::PPC::LastTSBuiltin-Builtin::FirstTSBuiltin);
890   }
891 
isCLZForZeroUndef() const892   bool isCLZForZeroUndef() const override { return false; }
893 
894   void getTargetDefines(const LangOptions &Opts,
895                         MacroBuilder &Builder) const override;
896 
897   bool
898   initFeatureMap(llvm::StringMap<bool> &Features, DiagnosticsEngine &Diags,
899                  StringRef CPU,
900                  const std::vector<std::string> &FeaturesVec) const override;
901 
902   bool handleTargetFeatures(std::vector<std::string> &Features,
903                             DiagnosticsEngine &Diags) override;
904   bool hasFeature(StringRef Feature) const override;
905   void setFeatureEnabled(llvm::StringMap<bool> &Features, StringRef Name,
906                          bool Enabled) const override;
907 
908   ArrayRef<const char *> getGCCRegNames() const override;
909   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override;
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & Info) const910   bool validateAsmConstraint(const char *&Name,
911                              TargetInfo::ConstraintInfo &Info) const override {
912     switch (*Name) {
913     default: return false;
914     case 'O': // Zero
915       break;
916     case 'b': // Base register
917     case 'f': // Floating point register
918       Info.setAllowsRegister();
919       break;
920     // FIXME: The following are added to allow parsing.
921     // I just took a guess at what the actions should be.
922     // Also, is more specific checking needed?  I.e. specific registers?
923     case 'd': // Floating point register (containing 64-bit value)
924     case 'v': // Altivec vector register
925       Info.setAllowsRegister();
926       break;
927     case 'w':
928       switch (Name[1]) {
929         case 'd':// VSX vector register to hold vector double data
930         case 'f':// VSX vector register to hold vector float data
931         case 's':// VSX vector register to hold scalar float data
932         case 'a':// Any VSX register
933         case 'c':// An individual CR bit
934           break;
935         default:
936           return false;
937       }
938       Info.setAllowsRegister();
939       Name++; // Skip over 'w'.
940       break;
941     case 'h': // `MQ', `CTR', or `LINK' register
942     case 'q': // `MQ' register
943     case 'c': // `CTR' register
944     case 'l': // `LINK' register
945     case 'x': // `CR' register (condition register) number 0
946     case 'y': // `CR' register (condition register)
947     case 'z': // `XER[CA]' carry bit (part of the XER register)
948       Info.setAllowsRegister();
949       break;
950     case 'I': // Signed 16-bit constant
951     case 'J': // Unsigned 16-bit constant shifted left 16 bits
952               //  (use `L' instead for SImode constants)
953     case 'K': // Unsigned 16-bit constant
954     case 'L': // Signed 16-bit constant shifted left 16 bits
955     case 'M': // Constant larger than 31
956     case 'N': // Exact power of 2
957     case 'P': // Constant whose negation is a signed 16-bit constant
958     case 'G': // Floating point constant that can be loaded into a
959               // register with one instruction per word
960     case 'H': // Integer/Floating point constant that can be loaded
961               // into a register using three instructions
962       break;
963     case 'm': // Memory operand. Note that on PowerPC targets, m can
964               // include addresses that update the base register. It
965               // is therefore only safe to use `m' in an asm statement
966               // if that asm statement accesses the operand exactly once.
967               // The asm statement must also use `%U<opno>' as a
968               // placeholder for the "update" flag in the corresponding
969               // load or store instruction. For example:
970               // asm ("st%U0 %1,%0" : "=m" (mem) : "r" (val));
971               // is correct but:
972               // asm ("st %1,%0" : "=m" (mem) : "r" (val));
973               // is not. Use es rather than m if you don't want the base
974               // register to be updated.
975     case 'e':
976       if (Name[1] != 's')
977           return false;
978               // es: A "stable" memory operand; that is, one which does not
979               // include any automodification of the base register. Unlike
980               // `m', this constraint can be used in asm statements that
981               // might access the operand several times, or that might not
982               // access it at all.
983       Info.setAllowsMemory();
984       Name++; // Skip over 'e'.
985       break;
986     case 'Q': // Memory operand that is an offset from a register (it is
987               // usually better to use `m' or `es' in asm statements)
988     case 'Z': // Memory operand that is an indexed or indirect from a
989               // register (it is usually better to use `m' or `es' in
990               // asm statements)
991       Info.setAllowsMemory();
992       Info.setAllowsRegister();
993       break;
994     case 'R': // AIX TOC entry
995     case 'a': // Address operand that is an indexed or indirect from a
996               // register (`p' is preferable for asm statements)
997     case 'S': // Constant suitable as a 64-bit mask operand
998     case 'T': // Constant suitable as a 32-bit mask operand
999     case 'U': // System V Release 4 small data area reference
1000     case 't': // AND masks that can be performed by two rldic{l, r}
1001               // instructions
1002     case 'W': // Vector constant that does not require memory
1003     case 'j': // Vector constant that is all zeros.
1004       break;
1005     // End FIXME.
1006     }
1007     return true;
1008   }
convertConstraint(const char * & Constraint) const1009   std::string convertConstraint(const char *&Constraint) const override {
1010     std::string R;
1011     switch (*Constraint) {
1012     case 'e':
1013     case 'w':
1014       // Two-character constraint; add "^" hint for later parsing.
1015       R = std::string("^") + std::string(Constraint, 2);
1016       Constraint++;
1017       break;
1018     default:
1019       return TargetInfo::convertConstraint(Constraint);
1020     }
1021     return R;
1022   }
getClobbers() const1023   const char *getClobbers() const override {
1024     return "";
1025   }
getEHDataRegisterNumber(unsigned RegNo) const1026   int getEHDataRegisterNumber(unsigned RegNo) const override {
1027     if (RegNo == 0) return 3;
1028     if (RegNo == 1) return 4;
1029     return -1;
1030   }
1031 
hasSjLjLowering() const1032   bool hasSjLjLowering() const override {
1033     return true;
1034   }
1035 
useFloat128ManglingForLongDouble() const1036   bool useFloat128ManglingForLongDouble() const override {
1037     return LongDoubleWidth == 128 &&
1038            LongDoubleFormat == &llvm::APFloat::PPCDoubleDouble &&
1039            getTriple().isOSBinFormatELF();
1040   }
1041 };
1042 
1043 const Builtin::Info PPCTargetInfo::BuiltinInfo[] = {
1044 #define BUILTIN(ID, TYPE, ATTRS) \
1045   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr },
1046 #define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) \
1047   { #ID, TYPE, ATTRS, HEADER, ALL_LANGUAGES, nullptr },
1048 #include "clang/Basic/BuiltinsPPC.def"
1049 };
1050 
1051 /// handleTargetFeatures - Perform initialization based on the user
1052 /// configured set of features.
handleTargetFeatures(std::vector<std::string> & Features,DiagnosticsEngine & Diags)1053 bool PPCTargetInfo::handleTargetFeatures(std::vector<std::string> &Features,
1054                                          DiagnosticsEngine &Diags) {
1055   for (const auto &Feature : Features) {
1056     if (Feature == "+vsx") {
1057       HasVSX = true;
1058     } else if (Feature == "+bpermd") {
1059       HasBPERMD = true;
1060     } else if (Feature == "+extdiv") {
1061       HasExtDiv = true;
1062     } else if (Feature == "+power8-vector") {
1063       HasP8Vector = true;
1064     } else if (Feature == "+crypto") {
1065       HasP8Crypto = true;
1066     } else if (Feature == "+direct-move") {
1067       HasDirectMove = true;
1068     } else if (Feature == "+qpx") {
1069       HasQPX = true;
1070     } else if (Feature == "+htm") {
1071       HasHTM = true;
1072     }
1073     // TODO: Finish this list and add an assert that we've handled them
1074     // all.
1075   }
1076 
1077   return true;
1078 }
1079 
1080 /// PPCTargetInfo::getTargetDefines - Return a set of the PowerPC-specific
1081 /// #defines that are not tied to a specific subtarget.
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const1082 void PPCTargetInfo::getTargetDefines(const LangOptions &Opts,
1083                                      MacroBuilder &Builder) const {
1084   // Target identification.
1085   Builder.defineMacro("__ppc__");
1086   Builder.defineMacro("__PPC__");
1087   Builder.defineMacro("_ARCH_PPC");
1088   Builder.defineMacro("__powerpc__");
1089   Builder.defineMacro("__POWERPC__");
1090   if (PointerWidth == 64) {
1091     Builder.defineMacro("_ARCH_PPC64");
1092     Builder.defineMacro("__powerpc64__");
1093     Builder.defineMacro("__ppc64__");
1094     Builder.defineMacro("__PPC64__");
1095   }
1096 
1097   // Target properties.
1098   if (getTriple().getArch() == llvm::Triple::ppc64le) {
1099     Builder.defineMacro("_LITTLE_ENDIAN");
1100   } else {
1101     if (getTriple().getOS() != llvm::Triple::NetBSD &&
1102         getTriple().getOS() != llvm::Triple::OpenBSD)
1103       Builder.defineMacro("_BIG_ENDIAN");
1104   }
1105 
1106   // ABI options.
1107   if (ABI == "elfv1" || ABI == "elfv1-qpx")
1108     Builder.defineMacro("_CALL_ELF", "1");
1109   if (ABI == "elfv2")
1110     Builder.defineMacro("_CALL_ELF", "2");
1111 
1112   // Subtarget options.
1113   Builder.defineMacro("__NATURAL_ALIGNMENT__");
1114   Builder.defineMacro("__REGISTER_PREFIX__", "");
1115 
1116   // FIXME: Should be controlled by command line option.
1117   if (LongDoubleWidth == 128)
1118     Builder.defineMacro("__LONG_DOUBLE_128__");
1119 
1120   if (Opts.AltiVec) {
1121     Builder.defineMacro("__VEC__", "10206");
1122     Builder.defineMacro("__ALTIVEC__");
1123   }
1124 
1125   // CPU identification.
1126   ArchDefineTypes defs = (ArchDefineTypes)llvm::StringSwitch<int>(CPU)
1127     .Case("440",   ArchDefineName)
1128     .Case("450",   ArchDefineName | ArchDefine440)
1129     .Case("601",   ArchDefineName)
1130     .Case("602",   ArchDefineName | ArchDefinePpcgr)
1131     .Case("603",   ArchDefineName | ArchDefinePpcgr)
1132     .Case("603e",  ArchDefineName | ArchDefine603 | ArchDefinePpcgr)
1133     .Case("603ev", ArchDefineName | ArchDefine603 | ArchDefinePpcgr)
1134     .Case("604",   ArchDefineName | ArchDefinePpcgr)
1135     .Case("604e",  ArchDefineName | ArchDefine604 | ArchDefinePpcgr)
1136     .Case("620",   ArchDefineName | ArchDefinePpcgr)
1137     .Case("630",   ArchDefineName | ArchDefinePpcgr)
1138     .Case("7400",  ArchDefineName | ArchDefinePpcgr)
1139     .Case("7450",  ArchDefineName | ArchDefinePpcgr)
1140     .Case("750",   ArchDefineName | ArchDefinePpcgr)
1141     .Case("970",   ArchDefineName | ArchDefinePwr4 | ArchDefinePpcgr
1142                      | ArchDefinePpcsq)
1143     .Case("a2",    ArchDefineA2)
1144     .Case("a2q",   ArchDefineName | ArchDefineA2 | ArchDefineA2q)
1145     .Case("pwr3",  ArchDefinePpcgr)
1146     .Case("pwr4",  ArchDefineName | ArchDefinePpcgr | ArchDefinePpcsq)
1147     .Case("pwr5",  ArchDefineName | ArchDefinePwr4 | ArchDefinePpcgr
1148                      | ArchDefinePpcsq)
1149     .Case("pwr5x", ArchDefineName | ArchDefinePwr5 | ArchDefinePwr4
1150                      | ArchDefinePpcgr | ArchDefinePpcsq)
1151     .Case("pwr6",  ArchDefineName | ArchDefinePwr5x | ArchDefinePwr5
1152                      | ArchDefinePwr4 | ArchDefinePpcgr | ArchDefinePpcsq)
1153     .Case("pwr6x", ArchDefineName | ArchDefinePwr6 | ArchDefinePwr5x
1154                      | ArchDefinePwr5 | ArchDefinePwr4 | ArchDefinePpcgr
1155                      | ArchDefinePpcsq)
1156     .Case("pwr7",  ArchDefineName | ArchDefinePwr6x | ArchDefinePwr6
1157                      | ArchDefinePwr5x | ArchDefinePwr5 | ArchDefinePwr4
1158                      | ArchDefinePpcgr | ArchDefinePpcsq)
1159     .Case("pwr8",  ArchDefineName | ArchDefinePwr7 | ArchDefinePwr6x
1160                      | ArchDefinePwr6 | ArchDefinePwr5x | ArchDefinePwr5
1161                      | ArchDefinePwr4 | ArchDefinePpcgr | ArchDefinePpcsq)
1162     .Case("power3",  ArchDefinePpcgr)
1163     .Case("power4",  ArchDefinePwr4 | ArchDefinePpcgr | ArchDefinePpcsq)
1164     .Case("power5",  ArchDefinePwr5 | ArchDefinePwr4 | ArchDefinePpcgr
1165                        | ArchDefinePpcsq)
1166     .Case("power5x", ArchDefinePwr5x | ArchDefinePwr5 | ArchDefinePwr4
1167                        | ArchDefinePpcgr | ArchDefinePpcsq)
1168     .Case("power6",  ArchDefinePwr6 | ArchDefinePwr5x | ArchDefinePwr5
1169                        | ArchDefinePwr4 | ArchDefinePpcgr | ArchDefinePpcsq)
1170     .Case("power6x", ArchDefinePwr6x | ArchDefinePwr6 | ArchDefinePwr5x
1171                        | ArchDefinePwr5 | ArchDefinePwr4 | ArchDefinePpcgr
1172                        | ArchDefinePpcsq)
1173     .Case("power7",  ArchDefinePwr7 | ArchDefinePwr6x | ArchDefinePwr6
1174                        | ArchDefinePwr5x | ArchDefinePwr5 | ArchDefinePwr4
1175                        | ArchDefinePpcgr | ArchDefinePpcsq)
1176     .Case("power8",  ArchDefinePwr8 | ArchDefinePwr7 | ArchDefinePwr6x
1177                        | ArchDefinePwr6 | ArchDefinePwr5x | ArchDefinePwr5
1178                        | ArchDefinePwr4 | ArchDefinePpcgr | ArchDefinePpcsq)
1179     .Default(ArchDefineNone);
1180 
1181   if (defs & ArchDefineName)
1182     Builder.defineMacro(Twine("_ARCH_", StringRef(CPU).upper()));
1183   if (defs & ArchDefinePpcgr)
1184     Builder.defineMacro("_ARCH_PPCGR");
1185   if (defs & ArchDefinePpcsq)
1186     Builder.defineMacro("_ARCH_PPCSQ");
1187   if (defs & ArchDefine440)
1188     Builder.defineMacro("_ARCH_440");
1189   if (defs & ArchDefine603)
1190     Builder.defineMacro("_ARCH_603");
1191   if (defs & ArchDefine604)
1192     Builder.defineMacro("_ARCH_604");
1193   if (defs & ArchDefinePwr4)
1194     Builder.defineMacro("_ARCH_PWR4");
1195   if (defs & ArchDefinePwr5)
1196     Builder.defineMacro("_ARCH_PWR5");
1197   if (defs & ArchDefinePwr5x)
1198     Builder.defineMacro("_ARCH_PWR5X");
1199   if (defs & ArchDefinePwr6)
1200     Builder.defineMacro("_ARCH_PWR6");
1201   if (defs & ArchDefinePwr6x)
1202     Builder.defineMacro("_ARCH_PWR6X");
1203   if (defs & ArchDefinePwr7)
1204     Builder.defineMacro("_ARCH_PWR7");
1205   if (defs & ArchDefinePwr8)
1206     Builder.defineMacro("_ARCH_PWR8");
1207   if (defs & ArchDefineA2)
1208     Builder.defineMacro("_ARCH_A2");
1209   if (defs & ArchDefineA2q) {
1210     Builder.defineMacro("_ARCH_A2Q");
1211     Builder.defineMacro("_ARCH_QP");
1212   }
1213 
1214   if (getTriple().getVendor() == llvm::Triple::BGQ) {
1215     Builder.defineMacro("__bg__");
1216     Builder.defineMacro("__THW_BLUEGENE__");
1217     Builder.defineMacro("__bgq__");
1218     Builder.defineMacro("__TOS_BGQ__");
1219   }
1220 
1221   if (HasVSX)
1222     Builder.defineMacro("__VSX__");
1223   if (HasP8Vector)
1224     Builder.defineMacro("__POWER8_VECTOR__");
1225   if (HasP8Crypto)
1226     Builder.defineMacro("__CRYPTO__");
1227   if (HasHTM)
1228     Builder.defineMacro("__HTM__");
1229 
1230   Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_1");
1231   Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_2");
1232   Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4");
1233   if (PointerWidth == 64)
1234     Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8");
1235 
1236   // FIXME: The following are not yet generated here by Clang, but are
1237   //        generated by GCC:
1238   //
1239   //   _SOFT_FLOAT_
1240   //   __RECIP_PRECISION__
1241   //   __APPLE_ALTIVEC__
1242   //   __RECIP__
1243   //   __RECIPF__
1244   //   __RSQRTE__
1245   //   __RSQRTEF__
1246   //   _SOFT_DOUBLE_
1247   //   __NO_LWSYNC__
1248   //   __HAVE_BSWAP__
1249   //   __LONGDOUBLE128
1250   //   __CMODEL_MEDIUM__
1251   //   __CMODEL_LARGE__
1252   //   _CALL_SYSV
1253   //   _CALL_DARWIN
1254   //   __NO_FPRS__
1255 }
1256 
1257 // Handle explicit options being passed to the compiler here: if we've
1258 // explicitly turned off vsx and turned on power8-vector or direct-move then
1259 // go ahead and error since the customer has expressed a somewhat incompatible
1260 // set of options.
ppcUserFeaturesCheck(DiagnosticsEngine & Diags,const std::vector<std::string> & FeaturesVec)1261 static bool ppcUserFeaturesCheck(DiagnosticsEngine &Diags,
1262                                  const std::vector<std::string> &FeaturesVec) {
1263 
1264   if (std::find(FeaturesVec.begin(), FeaturesVec.end(), "-vsx") !=
1265       FeaturesVec.end()) {
1266     if (std::find(FeaturesVec.begin(), FeaturesVec.end(), "+power8-vector") !=
1267         FeaturesVec.end()) {
1268       Diags.Report(diag::err_opt_not_valid_with_opt) << "-mpower8-vector"
1269                                                      << "-mno-vsx";
1270       return false;
1271     }
1272 
1273     if (std::find(FeaturesVec.begin(), FeaturesVec.end(), "+direct-move") !=
1274         FeaturesVec.end()) {
1275       Diags.Report(diag::err_opt_not_valid_with_opt) << "-mdirect-move"
1276                                                      << "-mno-vsx";
1277       return false;
1278     }
1279   }
1280 
1281   return true;
1282 }
1283 
initFeatureMap(llvm::StringMap<bool> & Features,DiagnosticsEngine & Diags,StringRef CPU,const std::vector<std::string> & FeaturesVec) const1284 bool PPCTargetInfo::initFeatureMap(
1285     llvm::StringMap<bool> &Features, DiagnosticsEngine &Diags, StringRef CPU,
1286     const std::vector<std::string> &FeaturesVec) const {
1287   Features["altivec"] = llvm::StringSwitch<bool>(CPU)
1288     .Case("7400", true)
1289     .Case("g4", true)
1290     .Case("7450", true)
1291     .Case("g4+", true)
1292     .Case("970", true)
1293     .Case("g5", true)
1294     .Case("pwr6", true)
1295     .Case("pwr7", true)
1296     .Case("pwr8", true)
1297     .Case("ppc64", true)
1298     .Case("ppc64le", true)
1299     .Default(false);
1300 
1301   Features["qpx"] = (CPU == "a2q");
1302   Features["crypto"] = llvm::StringSwitch<bool>(CPU)
1303     .Case("ppc64le", true)
1304     .Case("pwr8", true)
1305     .Default(false);
1306   Features["power8-vector"] = llvm::StringSwitch<bool>(CPU)
1307     .Case("ppc64le", true)
1308     .Case("pwr8", true)
1309     .Default(false);
1310   Features["bpermd"] = llvm::StringSwitch<bool>(CPU)
1311     .Case("ppc64le", true)
1312     .Case("pwr8", true)
1313     .Case("pwr7", true)
1314     .Default(false);
1315   Features["extdiv"] = llvm::StringSwitch<bool>(CPU)
1316     .Case("ppc64le", true)
1317     .Case("pwr8", true)
1318     .Case("pwr7", true)
1319     .Default(false);
1320   Features["direct-move"] = llvm::StringSwitch<bool>(CPU)
1321     .Case("ppc64le", true)
1322     .Case("pwr8", true)
1323     .Default(false);
1324   Features["vsx"] = llvm::StringSwitch<bool>(CPU)
1325     .Case("ppc64le", true)
1326     .Case("pwr8", true)
1327     .Case("pwr7", true)
1328     .Default(false);
1329 
1330   if (!ppcUserFeaturesCheck(Diags, FeaturesVec))
1331     return false;
1332 
1333   return TargetInfo::initFeatureMap(Features, Diags, CPU, FeaturesVec);
1334 }
1335 
hasFeature(StringRef Feature) const1336 bool PPCTargetInfo::hasFeature(StringRef Feature) const {
1337   return llvm::StringSwitch<bool>(Feature)
1338     .Case("powerpc", true)
1339     .Case("vsx", HasVSX)
1340     .Case("power8-vector", HasP8Vector)
1341     .Case("crypto", HasP8Crypto)
1342     .Case("direct-move", HasDirectMove)
1343     .Case("qpx", HasQPX)
1344     .Case("htm", HasHTM)
1345     .Case("bpermd", HasBPERMD)
1346     .Case("extdiv", HasExtDiv)
1347     .Default(false);
1348 }
1349 
setFeatureEnabled(llvm::StringMap<bool> & Features,StringRef Name,bool Enabled) const1350 void PPCTargetInfo::setFeatureEnabled(llvm::StringMap<bool> &Features,
1351                                       StringRef Name, bool Enabled) const {
1352   // If we're enabling direct-move or power8-vector go ahead and enable vsx
1353   // as well. Do the inverse if we're disabling vsx. We'll diagnose any user
1354   // incompatible options.
1355   if (Enabled) {
1356     if (Name == "vsx") {
1357      Features[Name] = true;
1358     } else if (Name == "direct-move") {
1359       Features[Name] = Features["vsx"] = true;
1360     } else if (Name == "power8-vector") {
1361       Features[Name] = Features["vsx"] = true;
1362     } else {
1363       Features[Name] = true;
1364     }
1365   } else {
1366     if (Name == "vsx") {
1367       Features[Name] = Features["direct-move"] = Features["power8-vector"] =
1368           false;
1369     } else {
1370       Features[Name] = false;
1371     }
1372   }
1373 }
1374 
1375 const char * const PPCTargetInfo::GCCRegNames[] = {
1376   "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7",
1377   "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
1378   "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23",
1379   "r24", "r25", "r26", "r27", "r28", "r29", "r30", "r31",
1380   "f0", "f1", "f2", "f3", "f4", "f5", "f6", "f7",
1381   "f8", "f9", "f10", "f11", "f12", "f13", "f14", "f15",
1382   "f16", "f17", "f18", "f19", "f20", "f21", "f22", "f23",
1383   "f24", "f25", "f26", "f27", "f28", "f29", "f30", "f31",
1384   "mq", "lr", "ctr", "ap",
1385   "cr0", "cr1", "cr2", "cr3", "cr4", "cr5", "cr6", "cr7",
1386   "xer",
1387   "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7",
1388   "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15",
1389   "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23",
1390   "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31",
1391   "vrsave", "vscr",
1392   "spe_acc", "spefscr",
1393   "sfp"
1394 };
1395 
getGCCRegNames() const1396 ArrayRef<const char*> PPCTargetInfo::getGCCRegNames() const {
1397   return llvm::makeArrayRef(GCCRegNames);
1398 }
1399 
1400 const TargetInfo::GCCRegAlias PPCTargetInfo::GCCRegAliases[] = {
1401   // While some of these aliases do map to different registers
1402   // they still share the same register name.
1403   { { "0" }, "r0" },
1404   { { "1"}, "r1" },
1405   { { "2" }, "r2" },
1406   { { "3" }, "r3" },
1407   { { "4" }, "r4" },
1408   { { "5" }, "r5" },
1409   { { "6" }, "r6" },
1410   { { "7" }, "r7" },
1411   { { "8" }, "r8" },
1412   { { "9" }, "r9" },
1413   { { "10" }, "r10" },
1414   { { "11" }, "r11" },
1415   { { "12" }, "r12" },
1416   { { "13" }, "r13" },
1417   { { "14" }, "r14" },
1418   { { "15" }, "r15" },
1419   { { "16" }, "r16" },
1420   { { "17" }, "r17" },
1421   { { "18" }, "r18" },
1422   { { "19" }, "r19" },
1423   { { "20" }, "r20" },
1424   { { "21" }, "r21" },
1425   { { "22" }, "r22" },
1426   { { "23" }, "r23" },
1427   { { "24" }, "r24" },
1428   { { "25" }, "r25" },
1429   { { "26" }, "r26" },
1430   { { "27" }, "r27" },
1431   { { "28" }, "r28" },
1432   { { "29" }, "r29" },
1433   { { "30" }, "r30" },
1434   { { "31" }, "r31" },
1435   { { "fr0" }, "f0" },
1436   { { "fr1" }, "f1" },
1437   { { "fr2" }, "f2" },
1438   { { "fr3" }, "f3" },
1439   { { "fr4" }, "f4" },
1440   { { "fr5" }, "f5" },
1441   { { "fr6" }, "f6" },
1442   { { "fr7" }, "f7" },
1443   { { "fr8" }, "f8" },
1444   { { "fr9" }, "f9" },
1445   { { "fr10" }, "f10" },
1446   { { "fr11" }, "f11" },
1447   { { "fr12" }, "f12" },
1448   { { "fr13" }, "f13" },
1449   { { "fr14" }, "f14" },
1450   { { "fr15" }, "f15" },
1451   { { "fr16" }, "f16" },
1452   { { "fr17" }, "f17" },
1453   { { "fr18" }, "f18" },
1454   { { "fr19" }, "f19" },
1455   { { "fr20" }, "f20" },
1456   { { "fr21" }, "f21" },
1457   { { "fr22" }, "f22" },
1458   { { "fr23" }, "f23" },
1459   { { "fr24" }, "f24" },
1460   { { "fr25" }, "f25" },
1461   { { "fr26" }, "f26" },
1462   { { "fr27" }, "f27" },
1463   { { "fr28" }, "f28" },
1464   { { "fr29" }, "f29" },
1465   { { "fr30" }, "f30" },
1466   { { "fr31" }, "f31" },
1467   { { "cc" }, "cr0" },
1468 };
1469 
getGCCRegAliases() const1470 ArrayRef<TargetInfo::GCCRegAlias> PPCTargetInfo::getGCCRegAliases() const {
1471   return llvm::makeArrayRef(GCCRegAliases);
1472 }
1473 
1474 class PPC32TargetInfo : public PPCTargetInfo {
1475 public:
PPC32TargetInfo(const llvm::Triple & Triple)1476   PPC32TargetInfo(const llvm::Triple &Triple) : PPCTargetInfo(Triple) {
1477     DataLayoutString = "E-m:e-p:32:32-i64:64-n32";
1478 
1479     switch (getTriple().getOS()) {
1480     case llvm::Triple::Linux:
1481     case llvm::Triple::FreeBSD:
1482     case llvm::Triple::NetBSD:
1483       SizeType = UnsignedInt;
1484       PtrDiffType = SignedInt;
1485       IntPtrType = SignedInt;
1486       break;
1487     default:
1488       break;
1489     }
1490 
1491     if (getTriple().getOS() == llvm::Triple::FreeBSD) {
1492       LongDoubleWidth = LongDoubleAlign = 64;
1493       LongDoubleFormat = &llvm::APFloat::IEEEdouble;
1494     }
1495 
1496     // PPC32 supports atomics up to 4 bytes.
1497     MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 32;
1498   }
1499 
getBuiltinVaListKind() const1500   BuiltinVaListKind getBuiltinVaListKind() const override {
1501     // This is the ELF definition, and is overridden by the Darwin sub-target
1502     return TargetInfo::PowerABIBuiltinVaList;
1503   }
1504 };
1505 
1506 // Note: ABI differences may eventually require us to have a separate
1507 // TargetInfo for little endian.
1508 class PPC64TargetInfo : public PPCTargetInfo {
1509 public:
PPC64TargetInfo(const llvm::Triple & Triple)1510   PPC64TargetInfo(const llvm::Triple &Triple) : PPCTargetInfo(Triple) {
1511     LongWidth = LongAlign = PointerWidth = PointerAlign = 64;
1512     IntMaxType = SignedLong;
1513     Int64Type = SignedLong;
1514 
1515     if ((Triple.getArch() == llvm::Triple::ppc64le)) {
1516       DataLayoutString = "e-m:e-i64:64-n32:64";
1517       ABI = "elfv2";
1518     } else {
1519       DataLayoutString = "E-m:e-i64:64-n32:64";
1520       ABI = "elfv1";
1521     }
1522 
1523     switch (getTriple().getOS()) {
1524     case llvm::Triple::FreeBSD:
1525       LongDoubleWidth = LongDoubleAlign = 64;
1526       LongDoubleFormat = &llvm::APFloat::IEEEdouble;
1527       break;
1528     case llvm::Triple::NetBSD:
1529       IntMaxType = SignedLongLong;
1530       Int64Type = SignedLongLong;
1531       break;
1532     default:
1533       break;
1534     }
1535 
1536     // PPC64 supports atomics up to 8 bytes.
1537     MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 64;
1538   }
getBuiltinVaListKind() const1539   BuiltinVaListKind getBuiltinVaListKind() const override {
1540     return TargetInfo::CharPtrBuiltinVaList;
1541   }
1542   // PPC64 Linux-specific ABI options.
setABI(const std::string & Name)1543   bool setABI(const std::string &Name) override {
1544     if (Name == "elfv1" || Name == "elfv1-qpx" || Name == "elfv2") {
1545       ABI = Name;
1546       return true;
1547     }
1548     return false;
1549   }
1550 };
1551 
1552 class DarwinPPC32TargetInfo :
1553   public DarwinTargetInfo<PPC32TargetInfo> {
1554 public:
DarwinPPC32TargetInfo(const llvm::Triple & Triple)1555   DarwinPPC32TargetInfo(const llvm::Triple &Triple)
1556       : DarwinTargetInfo<PPC32TargetInfo>(Triple) {
1557     HasAlignMac68kSupport = true;
1558     BoolWidth = BoolAlign = 32; //XXX support -mone-byte-bool?
1559     PtrDiffType = SignedInt; // for http://llvm.org/bugs/show_bug.cgi?id=15726
1560     LongLongAlign = 32;
1561     SuitableAlign = 128;
1562     DataLayoutString = "E-m:o-p:32:32-f64:32:64-n32";
1563   }
getBuiltinVaListKind() const1564   BuiltinVaListKind getBuiltinVaListKind() const override {
1565     return TargetInfo::CharPtrBuiltinVaList;
1566   }
1567 };
1568 
1569 class DarwinPPC64TargetInfo :
1570   public DarwinTargetInfo<PPC64TargetInfo> {
1571 public:
DarwinPPC64TargetInfo(const llvm::Triple & Triple)1572   DarwinPPC64TargetInfo(const llvm::Triple &Triple)
1573       : DarwinTargetInfo<PPC64TargetInfo>(Triple) {
1574     HasAlignMac68kSupport = true;
1575     SuitableAlign = 128;
1576     DataLayoutString = "E-m:o-i64:64-n32:64";
1577   }
1578 };
1579 
1580 static const unsigned NVPTXAddrSpaceMap[] = {
1581     1, // opencl_global
1582     3, // opencl_local
1583     4, // opencl_constant
1584     // FIXME: generic has to be added to the target
1585     0, // opencl_generic
1586     1, // cuda_device
1587     4, // cuda_constant
1588     3, // cuda_shared
1589 };
1590 
1591 class NVPTXTargetInfo : public TargetInfo {
1592   static const char *const GCCRegNames[];
1593   static const Builtin::Info BuiltinInfo[];
1594 
1595   // The GPU profiles supported by the NVPTX backend
1596   enum GPUKind {
1597     GK_NONE,
1598     GK_SM20,
1599     GK_SM21,
1600     GK_SM30,
1601     GK_SM35,
1602     GK_SM37,
1603   } GPU;
1604 
1605 public:
NVPTXTargetInfo(const llvm::Triple & Triple)1606   NVPTXTargetInfo(const llvm::Triple &Triple) : TargetInfo(Triple) {
1607     BigEndian = false;
1608     TLSSupported = false;
1609     LongWidth = LongAlign = 64;
1610     AddrSpaceMap = &NVPTXAddrSpaceMap;
1611     UseAddrSpaceMapMangling = true;
1612     // Define available target features
1613     // These must be defined in sorted order!
1614     NoAsmVariants = true;
1615     // Set the default GPU to sm20
1616     GPU = GK_SM20;
1617   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const1618   void getTargetDefines(const LangOptions &Opts,
1619                         MacroBuilder &Builder) const override {
1620     Builder.defineMacro("__PTX__");
1621     Builder.defineMacro("__NVPTX__");
1622     if (Opts.CUDAIsDevice) {
1623       // Set __CUDA_ARCH__ for the GPU specified.
1624       std::string CUDAArchCode;
1625       switch (GPU) {
1626       case GK_SM20:
1627         CUDAArchCode = "200";
1628         break;
1629       case GK_SM21:
1630         CUDAArchCode = "210";
1631         break;
1632       case GK_SM30:
1633         CUDAArchCode = "300";
1634         break;
1635       case GK_SM35:
1636         CUDAArchCode = "350";
1637         break;
1638       case GK_SM37:
1639         CUDAArchCode = "370";
1640         break;
1641       default:
1642         llvm_unreachable("Unhandled target CPU");
1643       }
1644       Builder.defineMacro("__CUDA_ARCH__", CUDAArchCode);
1645     }
1646   }
getTargetBuiltins() const1647   ArrayRef<Builtin::Info> getTargetBuiltins() const override {
1648     return llvm::makeArrayRef(BuiltinInfo,
1649                          clang::NVPTX::LastTSBuiltin - Builtin::FirstTSBuiltin);
1650   }
hasFeature(StringRef Feature) const1651   bool hasFeature(StringRef Feature) const override {
1652     return Feature == "ptx" || Feature == "nvptx";
1653   }
1654 
1655   ArrayRef<const char *> getGCCRegNames() const override;
getGCCRegAliases() const1656   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override {
1657     // No aliases.
1658     return None;
1659   }
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & Info) const1660   bool validateAsmConstraint(const char *&Name,
1661                              TargetInfo::ConstraintInfo &Info) const override {
1662     switch (*Name) {
1663     default:
1664       return false;
1665     case 'c':
1666     case 'h':
1667     case 'r':
1668     case 'l':
1669     case 'f':
1670     case 'd':
1671       Info.setAllowsRegister();
1672       return true;
1673     }
1674   }
getClobbers() const1675   const char *getClobbers() const override {
1676     // FIXME: Is this really right?
1677     return "";
1678   }
getBuiltinVaListKind() const1679   BuiltinVaListKind getBuiltinVaListKind() const override {
1680     // FIXME: implement
1681     return TargetInfo::CharPtrBuiltinVaList;
1682   }
setCPU(const std::string & Name)1683   bool setCPU(const std::string &Name) override {
1684     GPU = llvm::StringSwitch<GPUKind>(Name)
1685               .Case("sm_20", GK_SM20)
1686               .Case("sm_21", GK_SM21)
1687               .Case("sm_30", GK_SM30)
1688               .Case("sm_35", GK_SM35)
1689               .Case("sm_37", GK_SM37)
1690               .Default(GK_NONE);
1691 
1692     return GPU != GK_NONE;
1693   }
1694 };
1695 
1696 const Builtin::Info NVPTXTargetInfo::BuiltinInfo[] = {
1697 #define BUILTIN(ID, TYPE, ATTRS)                                               \
1698   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr },
1699 #define LIBBUILTIN(ID, TYPE, ATTRS, HEADER)                                    \
1700   { #ID, TYPE, ATTRS, HEADER, ALL_LANGUAGES, nullptr },
1701 #include "clang/Basic/BuiltinsNVPTX.def"
1702 };
1703 
1704 const char *const NVPTXTargetInfo::GCCRegNames[] = {"r0"};
1705 
getGCCRegNames() const1706 ArrayRef<const char *> NVPTXTargetInfo::getGCCRegNames() const {
1707   return llvm::makeArrayRef(GCCRegNames);
1708 }
1709 
1710 class NVPTX32TargetInfo : public NVPTXTargetInfo {
1711 public:
NVPTX32TargetInfo(const llvm::Triple & Triple)1712   NVPTX32TargetInfo(const llvm::Triple &Triple) : NVPTXTargetInfo(Triple) {
1713     LongWidth = LongAlign = 32;
1714     PointerWidth = PointerAlign = 32;
1715     SizeType = TargetInfo::UnsignedInt;
1716     PtrDiffType = TargetInfo::SignedInt;
1717     IntPtrType = TargetInfo::SignedInt;
1718     DataLayoutString = "e-p:32:32-i64:64-v16:16-v32:32-n16:32:64";
1719   }
1720 };
1721 
1722 class NVPTX64TargetInfo : public NVPTXTargetInfo {
1723 public:
NVPTX64TargetInfo(const llvm::Triple & Triple)1724   NVPTX64TargetInfo(const llvm::Triple &Triple) : NVPTXTargetInfo(Triple) {
1725     PointerWidth = PointerAlign = 64;
1726     SizeType = TargetInfo::UnsignedLong;
1727     PtrDiffType = TargetInfo::SignedLong;
1728     IntPtrType = TargetInfo::SignedLong;
1729     DataLayoutString = "e-i64:64-v16:16-v32:32-n16:32:64";
1730   }
1731 };
1732 
1733 static const unsigned AMDGPUAddrSpaceMap[] = {
1734   1,    // opencl_global
1735   3,    // opencl_local
1736   2,    // opencl_constant
1737   4,    // opencl_generic
1738   1,    // cuda_device
1739   2,    // cuda_constant
1740   3     // cuda_shared
1741 };
1742 
1743 // If you edit the description strings, make sure you update
1744 // getPointerWidthV().
1745 
1746 static const char *const DataLayoutStringR600 =
1747   "e-p:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128"
1748   "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64";
1749 
1750 static const char *const DataLayoutStringR600DoubleOps =
1751   "e-p:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128"
1752   "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64";
1753 
1754 static const char *const DataLayoutStringSI =
1755   "e-p:32:32-p1:64:64-p2:64:64-p3:32:32-p4:64:64-p5:32:32-p24:64:64"
1756   "-i64:64-v16:16-v24:32-v32:32-v48:64-v96:128"
1757   "-v192:256-v256:256-v512:512-v1024:1024-v2048:2048-n32:64";
1758 
1759 class AMDGPUTargetInfo : public TargetInfo {
1760   static const Builtin::Info BuiltinInfo[];
1761   static const char * const GCCRegNames[];
1762 
1763   /// \brief The GPU profiles supported by the AMDGPU target.
1764   enum GPUKind {
1765     GK_NONE,
1766     GK_R600,
1767     GK_R600_DOUBLE_OPS,
1768     GK_R700,
1769     GK_R700_DOUBLE_OPS,
1770     GK_EVERGREEN,
1771     GK_EVERGREEN_DOUBLE_OPS,
1772     GK_NORTHERN_ISLANDS,
1773     GK_CAYMAN,
1774     GK_SOUTHERN_ISLANDS,
1775     GK_SEA_ISLANDS,
1776     GK_VOLCANIC_ISLANDS
1777   } GPU;
1778 
1779   bool hasFP64:1;
1780   bool hasFMAF:1;
1781   bool hasLDEXPF:1;
1782 
1783 public:
AMDGPUTargetInfo(const llvm::Triple & Triple)1784   AMDGPUTargetInfo(const llvm::Triple &Triple)
1785     : TargetInfo(Triple) {
1786 
1787     if (Triple.getArch() == llvm::Triple::amdgcn) {
1788       DataLayoutString = DataLayoutStringSI;
1789       GPU = GK_SOUTHERN_ISLANDS;
1790       hasFP64 = true;
1791       hasFMAF = true;
1792       hasLDEXPF = true;
1793     } else {
1794       DataLayoutString = DataLayoutStringR600;
1795       GPU = GK_R600;
1796       hasFP64 = false;
1797       hasFMAF = false;
1798       hasLDEXPF = false;
1799     }
1800     AddrSpaceMap = &AMDGPUAddrSpaceMap;
1801     UseAddrSpaceMapMangling = true;
1802   }
1803 
getPointerWidthV(unsigned AddrSpace) const1804   uint64_t getPointerWidthV(unsigned AddrSpace) const override {
1805     if (GPU <= GK_CAYMAN)
1806       return 32;
1807 
1808     switch(AddrSpace) {
1809       default:
1810         return 64;
1811       case 0:
1812       case 3:
1813       case 5:
1814         return 32;
1815     }
1816   }
1817 
getClobbers() const1818   const char * getClobbers() const override {
1819     return "";
1820   }
1821 
1822   ArrayRef<const char *> getGCCRegNames() const override;
1823 
getGCCRegAliases() const1824   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override {
1825     return None;
1826   }
1827 
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & Info) const1828   bool validateAsmConstraint(const char *&Name,
1829                              TargetInfo::ConstraintInfo &Info) const override {
1830     switch (*Name) {
1831     default: break;
1832     case 'v': // vgpr
1833     case 's': // sgpr
1834       Info.setAllowsRegister();
1835       return true;
1836     }
1837     return false;
1838   }
1839 
getTargetBuiltins() const1840   ArrayRef<Builtin::Info> getTargetBuiltins() const override {
1841     return llvm::makeArrayRef(BuiltinInfo,
1842                         clang::AMDGPU::LastTSBuiltin - Builtin::FirstTSBuiltin);
1843   }
1844 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const1845   void getTargetDefines(const LangOptions &Opts,
1846                         MacroBuilder &Builder) const override {
1847     Builder.defineMacro("__R600__");
1848     if (hasFMAF)
1849       Builder.defineMacro("__HAS_FMAF__");
1850     if (hasLDEXPF)
1851       Builder.defineMacro("__HAS_LDEXPF__");
1852     if (hasFP64 && Opts.OpenCL)
1853       Builder.defineMacro("cl_khr_fp64");
1854     if (Opts.OpenCL) {
1855       if (GPU >= GK_NORTHERN_ISLANDS) {
1856         Builder.defineMacro("cl_khr_byte_addressable_store");
1857         Builder.defineMacro("cl_khr_global_int32_base_atomics");
1858         Builder.defineMacro("cl_khr_global_int32_extended_atomics");
1859         Builder.defineMacro("cl_khr_local_int32_base_atomics");
1860         Builder.defineMacro("cl_khr_local_int32_extended_atomics");
1861       }
1862     }
1863   }
1864 
getBuiltinVaListKind() const1865   BuiltinVaListKind getBuiltinVaListKind() const override {
1866     return TargetInfo::CharPtrBuiltinVaList;
1867   }
1868 
setCPU(const std::string & Name)1869   bool setCPU(const std::string &Name) override {
1870     GPU = llvm::StringSwitch<GPUKind>(Name)
1871       .Case("r600" ,    GK_R600)
1872       .Case("rv610",    GK_R600)
1873       .Case("rv620",    GK_R600)
1874       .Case("rv630",    GK_R600)
1875       .Case("rv635",    GK_R600)
1876       .Case("rs780",    GK_R600)
1877       .Case("rs880",    GK_R600)
1878       .Case("rv670",    GK_R600_DOUBLE_OPS)
1879       .Case("rv710",    GK_R700)
1880       .Case("rv730",    GK_R700)
1881       .Case("rv740",    GK_R700_DOUBLE_OPS)
1882       .Case("rv770",    GK_R700_DOUBLE_OPS)
1883       .Case("palm",     GK_EVERGREEN)
1884       .Case("cedar",    GK_EVERGREEN)
1885       .Case("sumo",     GK_EVERGREEN)
1886       .Case("sumo2",    GK_EVERGREEN)
1887       .Case("redwood",  GK_EVERGREEN)
1888       .Case("juniper",  GK_EVERGREEN)
1889       .Case("hemlock",  GK_EVERGREEN_DOUBLE_OPS)
1890       .Case("cypress",  GK_EVERGREEN_DOUBLE_OPS)
1891       .Case("barts",    GK_NORTHERN_ISLANDS)
1892       .Case("turks",    GK_NORTHERN_ISLANDS)
1893       .Case("caicos",   GK_NORTHERN_ISLANDS)
1894       .Case("cayman",   GK_CAYMAN)
1895       .Case("aruba",    GK_CAYMAN)
1896       .Case("tahiti",   GK_SOUTHERN_ISLANDS)
1897       .Case("pitcairn", GK_SOUTHERN_ISLANDS)
1898       .Case("verde",    GK_SOUTHERN_ISLANDS)
1899       .Case("oland",    GK_SOUTHERN_ISLANDS)
1900       .Case("hainan",   GK_SOUTHERN_ISLANDS)
1901       .Case("bonaire",  GK_SEA_ISLANDS)
1902       .Case("kabini",   GK_SEA_ISLANDS)
1903       .Case("kaveri",   GK_SEA_ISLANDS)
1904       .Case("hawaii",   GK_SEA_ISLANDS)
1905       .Case("mullins",  GK_SEA_ISLANDS)
1906       .Case("tonga",    GK_VOLCANIC_ISLANDS)
1907       .Case("iceland",  GK_VOLCANIC_ISLANDS)
1908       .Case("carrizo",  GK_VOLCANIC_ISLANDS)
1909       .Default(GK_NONE);
1910 
1911     if (GPU == GK_NONE) {
1912       return false;
1913     }
1914 
1915     // Set the correct data layout
1916     switch (GPU) {
1917     case GK_NONE:
1918     case GK_R600:
1919     case GK_R700:
1920     case GK_EVERGREEN:
1921     case GK_NORTHERN_ISLANDS:
1922       DataLayoutString = DataLayoutStringR600;
1923       hasFP64 = false;
1924       hasFMAF = false;
1925       hasLDEXPF = false;
1926       break;
1927     case GK_R600_DOUBLE_OPS:
1928     case GK_R700_DOUBLE_OPS:
1929     case GK_EVERGREEN_DOUBLE_OPS:
1930     case GK_CAYMAN:
1931       DataLayoutString = DataLayoutStringR600DoubleOps;
1932       hasFP64 = true;
1933       hasFMAF = true;
1934       hasLDEXPF = false;
1935       break;
1936     case GK_SOUTHERN_ISLANDS:
1937     case GK_SEA_ISLANDS:
1938     case GK_VOLCANIC_ISLANDS:
1939       DataLayoutString = DataLayoutStringSI;
1940       hasFP64 = true;
1941       hasFMAF = true;
1942       hasLDEXPF = true;
1943       break;
1944     }
1945 
1946     return true;
1947   }
1948 };
1949 
1950 const Builtin::Info AMDGPUTargetInfo::BuiltinInfo[] = {
1951 #define BUILTIN(ID, TYPE, ATTRS)                \
1952   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr },
1953 #include "clang/Basic/BuiltinsAMDGPU.def"
1954 };
1955 const char * const AMDGPUTargetInfo::GCCRegNames[] = {
1956   "v0", "v1", "v2", "v3", "v4", "v5", "v6", "v7",
1957   "v8", "v9", "v10", "v11", "v12", "v13", "v14", "v15",
1958   "v16", "v17", "v18", "v19", "v20", "v21", "v22", "v23",
1959   "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31",
1960   "v32", "v33", "v34", "v35", "v36", "v37", "v38", "v39",
1961   "v40", "v41", "v42", "v43", "v44", "v45", "v46", "v47",
1962   "v48", "v49", "v50", "v51", "v52", "v53", "v54", "v55",
1963   "v56", "v57", "v58", "v59", "v60", "v61", "v62", "v63",
1964   "v64", "v65", "v66", "v67", "v68", "v69", "v70", "v71",
1965   "v72", "v73", "v74", "v75", "v76", "v77", "v78", "v79",
1966   "v80", "v81", "v82", "v83", "v84", "v85", "v86", "v87",
1967   "v88", "v89", "v90", "v91", "v92", "v93", "v94", "v95",
1968   "v96", "v97", "v98", "v99", "v100", "v101", "v102", "v103",
1969   "v104", "v105", "v106", "v107", "v108", "v109", "v110", "v111",
1970   "v112", "v113", "v114", "v115", "v116", "v117", "v118", "v119",
1971   "v120", "v121", "v122", "v123", "v124", "v125", "v126", "v127",
1972   "v128", "v129", "v130", "v131", "v132", "v133", "v134", "v135",
1973   "v136", "v137", "v138", "v139", "v140", "v141", "v142", "v143",
1974   "v144", "v145", "v146", "v147", "v148", "v149", "v150", "v151",
1975   "v152", "v153", "v154", "v155", "v156", "v157", "v158", "v159",
1976   "v160", "v161", "v162", "v163", "v164", "v165", "v166", "v167",
1977   "v168", "v169", "v170", "v171", "v172", "v173", "v174", "v175",
1978   "v176", "v177", "v178", "v179", "v180", "v181", "v182", "v183",
1979   "v184", "v185", "v186", "v187", "v188", "v189", "v190", "v191",
1980   "v192", "v193", "v194", "v195", "v196", "v197", "v198", "v199",
1981   "v200", "v201", "v202", "v203", "v204", "v205", "v206", "v207",
1982   "v208", "v209", "v210", "v211", "v212", "v213", "v214", "v215",
1983   "v216", "v217", "v218", "v219", "v220", "v221", "v222", "v223",
1984   "v224", "v225", "v226", "v227", "v228", "v229", "v230", "v231",
1985   "v232", "v233", "v234", "v235", "v236", "v237", "v238", "v239",
1986   "v240", "v241", "v242", "v243", "v244", "v245", "v246", "v247",
1987   "v248", "v249", "v250", "v251", "v252", "v253", "v254", "v255",
1988   "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7",
1989   "s8", "s9", "s10", "s11", "s12", "s13", "s14", "s15",
1990   "s16", "s17", "s18", "s19", "s20", "s21", "s22", "s23",
1991   "s24", "s25", "s26", "s27", "s28", "s29", "s30", "s31",
1992   "s32", "s33", "s34", "s35", "s36", "s37", "s38", "s39",
1993   "s40", "s41", "s42", "s43", "s44", "s45", "s46", "s47",
1994   "s48", "s49", "s50", "s51", "s52", "s53", "s54", "s55",
1995   "s56", "s57", "s58", "s59", "s60", "s61", "s62", "s63",
1996   "s64", "s65", "s66", "s67", "s68", "s69", "s70", "s71",
1997   "s72", "s73", "s74", "s75", "s76", "s77", "s78", "s79",
1998   "s80", "s81", "s82", "s83", "s84", "s85", "s86", "s87",
1999   "s88", "s89", "s90", "s91", "s92", "s93", "s94", "s95",
2000   "s96", "s97", "s98", "s99", "s100", "s101", "s102", "s103",
2001   "s104", "s105", "s106", "s107", "s108", "s109", "s110", "s111",
2002   "s112", "s113", "s114", "s115", "s116", "s117", "s118", "s119",
2003   "s120", "s121", "s122", "s123", "s124", "s125", "s126", "s127"
2004   "exec", "vcc", "scc", "m0", "flat_scr", "exec_lo", "exec_hi",
2005   "vcc_lo", "vcc_hi", "flat_scr_lo", "flat_scr_hi"
2006 };
2007 
getGCCRegNames() const2008 ArrayRef<const char *> AMDGPUTargetInfo::getGCCRegNames() const {
2009   return llvm::makeArrayRef(GCCRegNames);
2010 }
2011 
2012 // Namespace for x86 abstract base class
2013 const Builtin::Info BuiltinInfo[] = {
2014 #define BUILTIN(ID, TYPE, ATTRS)                                               \
2015   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr },
2016 #define LIBBUILTIN(ID, TYPE, ATTRS, HEADER)                                    \
2017   { #ID, TYPE, ATTRS, HEADER, ALL_LANGUAGES, nullptr },
2018 #define TARGET_BUILTIN(ID, TYPE, ATTRS, FEATURE)                               \
2019   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, FEATURE },
2020 #include "clang/Basic/BuiltinsX86.def"
2021 };
2022 
2023 static const char* const GCCRegNames[] = {
2024   "ax", "dx", "cx", "bx", "si", "di", "bp", "sp",
2025   "st", "st(1)", "st(2)", "st(3)", "st(4)", "st(5)", "st(6)", "st(7)",
2026   "argp", "flags", "fpcr", "fpsr", "dirflag", "frame",
2027   "xmm0", "xmm1", "xmm2", "xmm3", "xmm4", "xmm5", "xmm6", "xmm7",
2028   "mm0", "mm1", "mm2", "mm3", "mm4", "mm5", "mm6", "mm7",
2029   "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
2030   "xmm8", "xmm9", "xmm10", "xmm11", "xmm12", "xmm13", "xmm14", "xmm15",
2031   "ymm0", "ymm1", "ymm2", "ymm3", "ymm4", "ymm5", "ymm6", "ymm7",
2032   "ymm8", "ymm9", "ymm10", "ymm11", "ymm12", "ymm13", "ymm14", "ymm15",
2033 };
2034 
2035 const TargetInfo::AddlRegName AddlRegNames[] = {
2036   { { "al", "ah", "eax", "rax" }, 0 },
2037   { { "bl", "bh", "ebx", "rbx" }, 3 },
2038   { { "cl", "ch", "ecx", "rcx" }, 2 },
2039   { { "dl", "dh", "edx", "rdx" }, 1 },
2040   { { "esi", "rsi" }, 4 },
2041   { { "edi", "rdi" }, 5 },
2042   { { "esp", "rsp" }, 7 },
2043   { { "ebp", "rbp" }, 6 },
2044   { { "r8d", "r8w", "r8b" }, 38 },
2045   { { "r9d", "r9w", "r9b" }, 39 },
2046   { { "r10d", "r10w", "r10b" }, 40 },
2047   { { "r11d", "r11w", "r11b" }, 41 },
2048   { { "r12d", "r12w", "r12b" }, 42 },
2049   { { "r13d", "r13w", "r13b" }, 43 },
2050   { { "r14d", "r14w", "r14b" }, 44 },
2051   { { "r15d", "r15w", "r15b" }, 45 },
2052 };
2053 
2054 // X86 target abstract base class; x86-32 and x86-64 are very close, so
2055 // most of the implementation can be shared.
2056 class X86TargetInfo : public TargetInfo {
2057   enum X86SSEEnum {
2058     NoSSE, SSE1, SSE2, SSE3, SSSE3, SSE41, SSE42, AVX, AVX2, AVX512F
2059   } SSELevel = NoSSE;
2060   enum MMX3DNowEnum {
2061     NoMMX3DNow, MMX, AMD3DNow, AMD3DNowAthlon
2062   } MMX3DNowLevel = NoMMX3DNow;
2063   enum XOPEnum {
2064     NoXOP,
2065     SSE4A,
2066     FMA4,
2067     XOP
2068   } XOPLevel = NoXOP;
2069 
2070   bool HasAES = false;
2071   bool HasPCLMUL = false;
2072   bool HasLZCNT = false;
2073   bool HasRDRND = false;
2074   bool HasFSGSBASE = false;
2075   bool HasBMI = false;
2076   bool HasBMI2 = false;
2077   bool HasPOPCNT = false;
2078   bool HasRTM = false;
2079   bool HasPRFCHW = false;
2080   bool HasRDSEED = false;
2081   bool HasADX = false;
2082   bool HasTBM = false;
2083   bool HasFMA = false;
2084   bool HasF16C = false;
2085   bool HasAVX512CD = false;
2086   bool HasAVX512ER = false;
2087   bool HasAVX512PF = false;
2088   bool HasAVX512DQ = false;
2089   bool HasAVX512BW = false;
2090   bool HasAVX512VL = false;
2091   bool HasSHA = false;
2092   bool HasCX16 = false;
2093   bool HasFXSR = false;
2094   bool HasXSAVE = false;
2095   bool HasXSAVEOPT = false;
2096   bool HasXSAVEC = false;
2097   bool HasXSAVES = false;
2098 
2099   /// \brief Enumeration of all of the X86 CPUs supported by Clang.
2100   ///
2101   /// Each enumeration represents a particular CPU supported by Clang. These
2102   /// loosely correspond to the options passed to '-march' or '-mtune' flags.
2103   enum CPUKind {
2104     CK_Generic,
2105 
2106     /// \name i386
2107     /// i386-generation processors.
2108     //@{
2109     CK_i386,
2110     //@}
2111 
2112     /// \name i486
2113     /// i486-generation processors.
2114     //@{
2115     CK_i486,
2116     CK_WinChipC6,
2117     CK_WinChip2,
2118     CK_C3,
2119     //@}
2120 
2121     /// \name i586
2122     /// i586-generation processors, P5 microarchitecture based.
2123     //@{
2124     CK_i586,
2125     CK_Pentium,
2126     CK_PentiumMMX,
2127     //@}
2128 
2129     /// \name i686
2130     /// i686-generation processors, P6 / Pentium M microarchitecture based.
2131     //@{
2132     CK_i686,
2133     CK_PentiumPro,
2134     CK_Pentium2,
2135     CK_Pentium3,
2136     CK_Pentium3M,
2137     CK_PentiumM,
2138     CK_C3_2,
2139 
2140     /// This enumerator is a bit odd, as GCC no longer accepts -march=yonah.
2141     /// Clang however has some logic to suport this.
2142     // FIXME: Warn, deprecate, and potentially remove this.
2143     CK_Yonah,
2144     //@}
2145 
2146     /// \name Netburst
2147     /// Netburst microarchitecture based processors.
2148     //@{
2149     CK_Pentium4,
2150     CK_Pentium4M,
2151     CK_Prescott,
2152     CK_Nocona,
2153     //@}
2154 
2155     /// \name Core
2156     /// Core microarchitecture based processors.
2157     //@{
2158     CK_Core2,
2159 
2160     /// This enumerator, like \see CK_Yonah, is a bit odd. It is another
2161     /// codename which GCC no longer accepts as an option to -march, but Clang
2162     /// has some logic for recognizing it.
2163     // FIXME: Warn, deprecate, and potentially remove this.
2164     CK_Penryn,
2165     //@}
2166 
2167     /// \name Atom
2168     /// Atom processors
2169     //@{
2170     CK_Bonnell,
2171     CK_Silvermont,
2172     //@}
2173 
2174     /// \name Nehalem
2175     /// Nehalem microarchitecture based processors.
2176     CK_Nehalem,
2177 
2178     /// \name Westmere
2179     /// Westmere microarchitecture based processors.
2180     CK_Westmere,
2181 
2182     /// \name Sandy Bridge
2183     /// Sandy Bridge microarchitecture based processors.
2184     CK_SandyBridge,
2185 
2186     /// \name Ivy Bridge
2187     /// Ivy Bridge microarchitecture based processors.
2188     CK_IvyBridge,
2189 
2190     /// \name Haswell
2191     /// Haswell microarchitecture based processors.
2192     CK_Haswell,
2193 
2194     /// \name Broadwell
2195     /// Broadwell microarchitecture based processors.
2196     CK_Broadwell,
2197 
2198     /// \name Skylake
2199     /// Skylake microarchitecture based processors.
2200     CK_Skylake,
2201 
2202     /// \name Knights Landing
2203     /// Knights Landing processor.
2204     CK_KNL,
2205 
2206     /// \name K6
2207     /// K6 architecture processors.
2208     //@{
2209     CK_K6,
2210     CK_K6_2,
2211     CK_K6_3,
2212     //@}
2213 
2214     /// \name K7
2215     /// K7 architecture processors.
2216     //@{
2217     CK_Athlon,
2218     CK_AthlonThunderbird,
2219     CK_Athlon4,
2220     CK_AthlonXP,
2221     CK_AthlonMP,
2222     //@}
2223 
2224     /// \name K8
2225     /// K8 architecture processors.
2226     //@{
2227     CK_Athlon64,
2228     CK_Athlon64SSE3,
2229     CK_AthlonFX,
2230     CK_K8,
2231     CK_K8SSE3,
2232     CK_Opteron,
2233     CK_OpteronSSE3,
2234     CK_AMDFAM10,
2235     //@}
2236 
2237     /// \name Bobcat
2238     /// Bobcat architecture processors.
2239     //@{
2240     CK_BTVER1,
2241     CK_BTVER2,
2242     //@}
2243 
2244     /// \name Bulldozer
2245     /// Bulldozer architecture processors.
2246     //@{
2247     CK_BDVER1,
2248     CK_BDVER2,
2249     CK_BDVER3,
2250     CK_BDVER4,
2251     //@}
2252 
2253     /// This specification is deprecated and will be removed in the future.
2254     /// Users should prefer \see CK_K8.
2255     // FIXME: Warn on this when the CPU is set to it.
2256     //@{
2257     CK_x86_64,
2258     //@}
2259 
2260     /// \name Geode
2261     /// Geode processors.
2262     //@{
2263     CK_Geode
2264     //@}
2265   } CPU = CK_Generic;
2266 
getCPUKind(StringRef CPU) const2267   CPUKind getCPUKind(StringRef CPU) const {
2268     return llvm::StringSwitch<CPUKind>(CPU)
2269         .Case("i386", CK_i386)
2270         .Case("i486", CK_i486)
2271         .Case("winchip-c6", CK_WinChipC6)
2272         .Case("winchip2", CK_WinChip2)
2273         .Case("c3", CK_C3)
2274         .Case("i586", CK_i586)
2275         .Case("pentium", CK_Pentium)
2276         .Case("pentium-mmx", CK_PentiumMMX)
2277         .Case("i686", CK_i686)
2278         .Case("pentiumpro", CK_PentiumPro)
2279         .Case("pentium2", CK_Pentium2)
2280         .Case("pentium3", CK_Pentium3)
2281         .Case("pentium3m", CK_Pentium3M)
2282         .Case("pentium-m", CK_PentiumM)
2283         .Case("c3-2", CK_C3_2)
2284         .Case("yonah", CK_Yonah)
2285         .Case("pentium4", CK_Pentium4)
2286         .Case("pentium4m", CK_Pentium4M)
2287         .Case("prescott", CK_Prescott)
2288         .Case("nocona", CK_Nocona)
2289         .Case("core2", CK_Core2)
2290         .Case("penryn", CK_Penryn)
2291         .Case("bonnell", CK_Bonnell)
2292         .Case("atom", CK_Bonnell) // Legacy name.
2293         .Case("silvermont", CK_Silvermont)
2294         .Case("slm", CK_Silvermont) // Legacy name.
2295         .Case("nehalem", CK_Nehalem)
2296         .Case("corei7", CK_Nehalem) // Legacy name.
2297         .Case("westmere", CK_Westmere)
2298         .Case("sandybridge", CK_SandyBridge)
2299         .Case("corei7-avx", CK_SandyBridge) // Legacy name.
2300         .Case("ivybridge", CK_IvyBridge)
2301         .Case("core-avx-i", CK_IvyBridge) // Legacy name.
2302         .Case("haswell", CK_Haswell)
2303         .Case("core-avx2", CK_Haswell) // Legacy name.
2304         .Case("broadwell", CK_Broadwell)
2305         .Case("skylake", CK_Skylake)
2306         .Case("skx", CK_Skylake) // Legacy name.
2307         .Case("knl", CK_KNL)
2308         .Case("k6", CK_K6)
2309         .Case("k6-2", CK_K6_2)
2310         .Case("k6-3", CK_K6_3)
2311         .Case("athlon", CK_Athlon)
2312         .Case("athlon-tbird", CK_AthlonThunderbird)
2313         .Case("athlon-4", CK_Athlon4)
2314         .Case("athlon-xp", CK_AthlonXP)
2315         .Case("athlon-mp", CK_AthlonMP)
2316         .Case("athlon64", CK_Athlon64)
2317         .Case("athlon64-sse3", CK_Athlon64SSE3)
2318         .Case("athlon-fx", CK_AthlonFX)
2319         .Case("k8", CK_K8)
2320         .Case("k8-sse3", CK_K8SSE3)
2321         .Case("opteron", CK_Opteron)
2322         .Case("opteron-sse3", CK_OpteronSSE3)
2323         .Case("barcelona", CK_AMDFAM10)
2324         .Case("amdfam10", CK_AMDFAM10)
2325         .Case("btver1", CK_BTVER1)
2326         .Case("btver2", CK_BTVER2)
2327         .Case("bdver1", CK_BDVER1)
2328         .Case("bdver2", CK_BDVER2)
2329         .Case("bdver3", CK_BDVER3)
2330         .Case("bdver4", CK_BDVER4)
2331         .Case("x86-64", CK_x86_64)
2332         .Case("geode", CK_Geode)
2333         .Default(CK_Generic);
2334   }
2335 
2336   enum FPMathKind {
2337     FP_Default,
2338     FP_SSE,
2339     FP_387
2340   } FPMath = FP_Default;
2341 
2342 public:
X86TargetInfo(const llvm::Triple & Triple)2343   X86TargetInfo(const llvm::Triple &Triple) : TargetInfo(Triple) {
2344     BigEndian = false;
2345     LongDoubleFormat = &llvm::APFloat::x87DoubleExtended;
2346   }
getFloatEvalMethod() const2347   unsigned getFloatEvalMethod() const override {
2348     // X87 evaluates with 80 bits "long double" precision.
2349     return SSELevel == NoSSE ? 2 : 0;
2350   }
getTargetBuiltins() const2351   ArrayRef<Builtin::Info> getTargetBuiltins() const override {
2352     return llvm::makeArrayRef(BuiltinInfo,
2353                              clang::X86::LastTSBuiltin-Builtin::FirstTSBuiltin);
2354   }
getGCCRegNames() const2355   ArrayRef<const char *> getGCCRegNames() const override {
2356     return llvm::makeArrayRef(GCCRegNames);
2357   }
getGCCRegAliases() const2358   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override {
2359     return None;
2360   }
getGCCAddlRegNames() const2361   ArrayRef<TargetInfo::AddlRegName> getGCCAddlRegNames() const override {
2362     return llvm::makeArrayRef(AddlRegNames);
2363   }
2364   bool validateCpuSupports(StringRef Name) const override;
2365   bool validateAsmConstraint(const char *&Name,
2366                              TargetInfo::ConstraintInfo &info) const override;
2367 
validateGlobalRegisterVariable(StringRef RegName,unsigned RegSize,bool & HasSizeMismatch) const2368   bool validateGlobalRegisterVariable(StringRef RegName,
2369                                       unsigned RegSize,
2370                                       bool &HasSizeMismatch) const override {
2371     // esp and ebp are the only 32-bit registers the x86 backend can currently
2372     // handle.
2373     if (RegName.equals("esp") || RegName.equals("ebp")) {
2374       // Check that the register size is 32-bit.
2375       HasSizeMismatch = RegSize != 32;
2376       return true;
2377     }
2378 
2379     return false;
2380   }
2381 
2382   bool validateOutputSize(StringRef Constraint, unsigned Size) const override;
2383 
2384   bool validateInputSize(StringRef Constraint, unsigned Size) const override;
2385 
2386   virtual bool validateOperandSize(StringRef Constraint, unsigned Size) const;
2387 
2388   std::string convertConstraint(const char *&Constraint) const override;
getClobbers() const2389   const char *getClobbers() const override {
2390     return "~{dirflag},~{fpsr},~{flags}";
2391   }
2392   void getTargetDefines(const LangOptions &Opts,
2393                         MacroBuilder &Builder) const override;
2394   static void setSSELevel(llvm::StringMap<bool> &Features, X86SSEEnum Level,
2395                           bool Enabled);
2396   static void setMMXLevel(llvm::StringMap<bool> &Features, MMX3DNowEnum Level,
2397                           bool Enabled);
2398   static void setXOPLevel(llvm::StringMap<bool> &Features, XOPEnum Level,
2399                           bool Enabled);
setFeatureEnabled(llvm::StringMap<bool> & Features,StringRef Name,bool Enabled) const2400   void setFeatureEnabled(llvm::StringMap<bool> &Features,
2401                          StringRef Name, bool Enabled) const override {
2402     setFeatureEnabledImpl(Features, Name, Enabled);
2403   }
2404   // This exists purely to cut down on the number of virtual calls in
2405   // initFeatureMap which calls this repeatedly.
2406   static void setFeatureEnabledImpl(llvm::StringMap<bool> &Features,
2407                                     StringRef Name, bool Enabled);
2408   bool
2409   initFeatureMap(llvm::StringMap<bool> &Features, DiagnosticsEngine &Diags,
2410                  StringRef CPU,
2411                  const std::vector<std::string> &FeaturesVec) const override;
2412   bool hasFeature(StringRef Feature) const override;
2413   bool handleTargetFeatures(std::vector<std::string> &Features,
2414                             DiagnosticsEngine &Diags) override;
getABI() const2415   StringRef getABI() const override {
2416     if (getTriple().getArch() == llvm::Triple::x86_64 && SSELevel >= AVX512F)
2417       return "avx512";
2418     if (getTriple().getArch() == llvm::Triple::x86_64 && SSELevel >= AVX)
2419       return "avx";
2420     if (getTriple().getArch() == llvm::Triple::x86 &&
2421              MMX3DNowLevel == NoMMX3DNow)
2422       return "no-mmx";
2423     return "";
2424   }
setCPU(const std::string & Name)2425   bool setCPU(const std::string &Name) override {
2426     CPU = getCPUKind(Name);
2427 
2428     // Perform any per-CPU checks necessary to determine if this CPU is
2429     // acceptable.
2430     // FIXME: This results in terrible diagnostics. Clang just says the CPU is
2431     // invalid without explaining *why*.
2432     switch (CPU) {
2433     case CK_Generic:
2434       // No processor selected!
2435       return false;
2436 
2437     case CK_i386:
2438     case CK_i486:
2439     case CK_WinChipC6:
2440     case CK_WinChip2:
2441     case CK_C3:
2442     case CK_i586:
2443     case CK_Pentium:
2444     case CK_PentiumMMX:
2445     case CK_i686:
2446     case CK_PentiumPro:
2447     case CK_Pentium2:
2448     case CK_Pentium3:
2449     case CK_Pentium3M:
2450     case CK_PentiumM:
2451     case CK_Yonah:
2452     case CK_C3_2:
2453     case CK_Pentium4:
2454     case CK_Pentium4M:
2455     case CK_Prescott:
2456     case CK_K6:
2457     case CK_K6_2:
2458     case CK_K6_3:
2459     case CK_Athlon:
2460     case CK_AthlonThunderbird:
2461     case CK_Athlon4:
2462     case CK_AthlonXP:
2463     case CK_AthlonMP:
2464     case CK_Geode:
2465       // Only accept certain architectures when compiling in 32-bit mode.
2466       if (getTriple().getArch() != llvm::Triple::x86)
2467         return false;
2468 
2469       // Fallthrough
2470     case CK_Nocona:
2471     case CK_Core2:
2472     case CK_Penryn:
2473     case CK_Bonnell:
2474     case CK_Silvermont:
2475     case CK_Nehalem:
2476     case CK_Westmere:
2477     case CK_SandyBridge:
2478     case CK_IvyBridge:
2479     case CK_Haswell:
2480     case CK_Broadwell:
2481     case CK_Skylake:
2482     case CK_KNL:
2483     case CK_Athlon64:
2484     case CK_Athlon64SSE3:
2485     case CK_AthlonFX:
2486     case CK_K8:
2487     case CK_K8SSE3:
2488     case CK_Opteron:
2489     case CK_OpteronSSE3:
2490     case CK_AMDFAM10:
2491     case CK_BTVER1:
2492     case CK_BTVER2:
2493     case CK_BDVER1:
2494     case CK_BDVER2:
2495     case CK_BDVER3:
2496     case CK_BDVER4:
2497     case CK_x86_64:
2498       return true;
2499     }
2500     llvm_unreachable("Unhandled CPU kind");
2501   }
2502 
2503   bool setFPMath(StringRef Name) override;
2504 
checkCallingConvention(CallingConv CC) const2505   CallingConvCheckResult checkCallingConvention(CallingConv CC) const override {
2506     // We accept all non-ARM calling conventions
2507     return (CC == CC_X86ThisCall ||
2508             CC == CC_X86FastCall ||
2509             CC == CC_X86StdCall ||
2510             CC == CC_X86VectorCall ||
2511             CC == CC_C ||
2512             CC == CC_X86Pascal ||
2513             CC == CC_IntelOclBicc) ? CCCR_OK : CCCR_Warning;
2514   }
2515 
getDefaultCallingConv(CallingConvMethodType MT) const2516   CallingConv getDefaultCallingConv(CallingConvMethodType MT) const override {
2517     return MT == CCMT_Member ? CC_X86ThisCall : CC_C;
2518   }
2519 
hasSjLjLowering() const2520   bool hasSjLjLowering() const override {
2521     return true;
2522   }
2523 };
2524 
setFPMath(StringRef Name)2525 bool X86TargetInfo::setFPMath(StringRef Name) {
2526   if (Name == "387") {
2527     FPMath = FP_387;
2528     return true;
2529   }
2530   if (Name == "sse") {
2531     FPMath = FP_SSE;
2532     return true;
2533   }
2534   return false;
2535 }
2536 
initFeatureMap(llvm::StringMap<bool> & Features,DiagnosticsEngine & Diags,StringRef CPU,const std::vector<std::string> & FeaturesVec) const2537 bool X86TargetInfo::initFeatureMap(
2538     llvm::StringMap<bool> &Features, DiagnosticsEngine &Diags, StringRef CPU,
2539     const std::vector<std::string> &FeaturesVec) const {
2540   // FIXME: This *really* should not be here.
2541   // X86_64 always has SSE2.
2542   if (getTriple().getArch() == llvm::Triple::x86_64)
2543     setFeatureEnabledImpl(Features, "sse2", true);
2544 
2545   switch (getCPUKind(CPU)) {
2546   case CK_Generic:
2547   case CK_i386:
2548   case CK_i486:
2549   case CK_i586:
2550   case CK_Pentium:
2551   case CK_i686:
2552   case CK_PentiumPro:
2553     break;
2554   case CK_PentiumMMX:
2555   case CK_Pentium2:
2556   case CK_K6:
2557   case CK_WinChipC6:
2558     setFeatureEnabledImpl(Features, "mmx", true);
2559     break;
2560   case CK_Pentium3:
2561   case CK_Pentium3M:
2562   case CK_C3_2:
2563     setFeatureEnabledImpl(Features, "sse", true);
2564     setFeatureEnabledImpl(Features, "fxsr", true);
2565     break;
2566   case CK_PentiumM:
2567   case CK_Pentium4:
2568   case CK_Pentium4M:
2569   case CK_x86_64:
2570     setFeatureEnabledImpl(Features, "sse2", true);
2571     setFeatureEnabledImpl(Features, "fxsr", true);
2572     break;
2573   case CK_Yonah:
2574   case CK_Prescott:
2575   case CK_Nocona:
2576     setFeatureEnabledImpl(Features, "sse3", true);
2577     setFeatureEnabledImpl(Features, "fxsr", true);
2578     setFeatureEnabledImpl(Features, "cx16", true);
2579     break;
2580   case CK_Core2:
2581   case CK_Bonnell:
2582     setFeatureEnabledImpl(Features, "ssse3", true);
2583     setFeatureEnabledImpl(Features, "fxsr", true);
2584     setFeatureEnabledImpl(Features, "cx16", true);
2585     break;
2586   case CK_Penryn:
2587     setFeatureEnabledImpl(Features, "sse4.1", true);
2588     setFeatureEnabledImpl(Features, "fxsr", true);
2589     setFeatureEnabledImpl(Features, "cx16", true);
2590     break;
2591   case CK_Skylake:
2592     setFeatureEnabledImpl(Features, "avx512f", true);
2593     setFeatureEnabledImpl(Features, "avx512cd", true);
2594     setFeatureEnabledImpl(Features, "avx512dq", true);
2595     setFeatureEnabledImpl(Features, "avx512bw", true);
2596     setFeatureEnabledImpl(Features, "avx512vl", true);
2597     setFeatureEnabledImpl(Features, "xsavec", true);
2598     setFeatureEnabledImpl(Features, "xsaves", true);
2599     // FALLTHROUGH
2600   case CK_Broadwell:
2601     setFeatureEnabledImpl(Features, "rdseed", true);
2602     setFeatureEnabledImpl(Features, "adx", true);
2603     // FALLTHROUGH
2604   case CK_Haswell:
2605     setFeatureEnabledImpl(Features, "avx2", true);
2606     setFeatureEnabledImpl(Features, "lzcnt", true);
2607     setFeatureEnabledImpl(Features, "bmi", true);
2608     setFeatureEnabledImpl(Features, "bmi2", true);
2609     setFeatureEnabledImpl(Features, "rtm", true);
2610     setFeatureEnabledImpl(Features, "fma", true);
2611     // FALLTHROUGH
2612   case CK_IvyBridge:
2613     setFeatureEnabledImpl(Features, "rdrnd", true);
2614     setFeatureEnabledImpl(Features, "f16c", true);
2615     setFeatureEnabledImpl(Features, "fsgsbase", true);
2616     // FALLTHROUGH
2617   case CK_SandyBridge:
2618     setFeatureEnabledImpl(Features, "avx", true);
2619     setFeatureEnabledImpl(Features, "xsave", true);
2620     setFeatureEnabledImpl(Features, "xsaveopt", true);
2621     // FALLTHROUGH
2622   case CK_Westmere:
2623   case CK_Silvermont:
2624     setFeatureEnabledImpl(Features, "aes", true);
2625     setFeatureEnabledImpl(Features, "pclmul", true);
2626     // FALLTHROUGH
2627   case CK_Nehalem:
2628     setFeatureEnabledImpl(Features, "sse4.2", true);
2629     setFeatureEnabledImpl(Features, "fxsr", true);
2630     setFeatureEnabledImpl(Features, "cx16", true);
2631     break;
2632   case CK_KNL:
2633     setFeatureEnabledImpl(Features, "avx512f", true);
2634     setFeatureEnabledImpl(Features, "avx512cd", true);
2635     setFeatureEnabledImpl(Features, "avx512er", true);
2636     setFeatureEnabledImpl(Features, "avx512pf", true);
2637     setFeatureEnabledImpl(Features, "fxsr", true);
2638     setFeatureEnabledImpl(Features, "rdseed", true);
2639     setFeatureEnabledImpl(Features, "adx", true);
2640     setFeatureEnabledImpl(Features, "lzcnt", true);
2641     setFeatureEnabledImpl(Features, "bmi", true);
2642     setFeatureEnabledImpl(Features, "bmi2", true);
2643     setFeatureEnabledImpl(Features, "rtm", true);
2644     setFeatureEnabledImpl(Features, "fma", true);
2645     setFeatureEnabledImpl(Features, "rdrnd", true);
2646     setFeatureEnabledImpl(Features, "f16c", true);
2647     setFeatureEnabledImpl(Features, "fsgsbase", true);
2648     setFeatureEnabledImpl(Features, "aes", true);
2649     setFeatureEnabledImpl(Features, "pclmul", true);
2650     setFeatureEnabledImpl(Features, "cx16", true);
2651     setFeatureEnabledImpl(Features, "xsaveopt", true);
2652     setFeatureEnabledImpl(Features, "xsave", true);
2653     break;
2654   case CK_K6_2:
2655   case CK_K6_3:
2656   case CK_WinChip2:
2657   case CK_C3:
2658     setFeatureEnabledImpl(Features, "3dnow", true);
2659     break;
2660   case CK_Athlon:
2661   case CK_AthlonThunderbird:
2662   case CK_Geode:
2663     setFeatureEnabledImpl(Features, "3dnowa", true);
2664     break;
2665   case CK_Athlon4:
2666   case CK_AthlonXP:
2667   case CK_AthlonMP:
2668     setFeatureEnabledImpl(Features, "sse", true);
2669     setFeatureEnabledImpl(Features, "3dnowa", true);
2670     setFeatureEnabledImpl(Features, "fxsr", true);
2671     break;
2672   case CK_K8:
2673   case CK_Opteron:
2674   case CK_Athlon64:
2675   case CK_AthlonFX:
2676     setFeatureEnabledImpl(Features, "sse2", true);
2677     setFeatureEnabledImpl(Features, "3dnowa", true);
2678     setFeatureEnabledImpl(Features, "fxsr", true);
2679     break;
2680   case CK_AMDFAM10:
2681     setFeatureEnabledImpl(Features, "sse4a", true);
2682     setFeatureEnabledImpl(Features, "lzcnt", true);
2683     setFeatureEnabledImpl(Features, "popcnt", true);
2684     // FALLTHROUGH
2685   case CK_K8SSE3:
2686   case CK_OpteronSSE3:
2687   case CK_Athlon64SSE3:
2688     setFeatureEnabledImpl(Features, "sse3", true);
2689     setFeatureEnabledImpl(Features, "3dnowa", true);
2690     setFeatureEnabledImpl(Features, "fxsr", true);
2691     break;
2692   case CK_BTVER2:
2693     setFeatureEnabledImpl(Features, "avx", true);
2694     setFeatureEnabledImpl(Features, "aes", true);
2695     setFeatureEnabledImpl(Features, "pclmul", true);
2696     setFeatureEnabledImpl(Features, "bmi", true);
2697     setFeatureEnabledImpl(Features, "f16c", true);
2698     setFeatureEnabledImpl(Features, "xsaveopt", true);
2699     // FALLTHROUGH
2700   case CK_BTVER1:
2701     setFeatureEnabledImpl(Features, "ssse3", true);
2702     setFeatureEnabledImpl(Features, "sse4a", true);
2703     setFeatureEnabledImpl(Features, "lzcnt", true);
2704     setFeatureEnabledImpl(Features, "popcnt", true);
2705     setFeatureEnabledImpl(Features, "prfchw", true);
2706     setFeatureEnabledImpl(Features, "cx16", true);
2707     setFeatureEnabledImpl(Features, "fxsr", true);
2708     setFeatureEnabledImpl(Features, "xsave", true);
2709     break;
2710   case CK_BDVER4:
2711     setFeatureEnabledImpl(Features, "avx2", true);
2712     setFeatureEnabledImpl(Features, "bmi2", true);
2713     // FALLTHROUGH
2714   case CK_BDVER3:
2715     setFeatureEnabledImpl(Features, "fsgsbase", true);
2716     setFeatureEnabledImpl(Features, "xsaveopt", true);
2717     // FALLTHROUGH
2718   case CK_BDVER2:
2719     setFeatureEnabledImpl(Features, "bmi", true);
2720     setFeatureEnabledImpl(Features, "fma", true);
2721     setFeatureEnabledImpl(Features, "f16c", true);
2722     setFeatureEnabledImpl(Features, "tbm", true);
2723     // FALLTHROUGH
2724   case CK_BDVER1:
2725     // xop implies avx, sse4a and fma4.
2726     setFeatureEnabledImpl(Features, "xop", true);
2727     setFeatureEnabledImpl(Features, "lzcnt", true);
2728     setFeatureEnabledImpl(Features, "aes", true);
2729     setFeatureEnabledImpl(Features, "pclmul", true);
2730     setFeatureEnabledImpl(Features, "prfchw", true);
2731     setFeatureEnabledImpl(Features, "cx16", true);
2732     setFeatureEnabledImpl(Features, "fxsr", true);
2733     setFeatureEnabledImpl(Features, "xsave", true);
2734     break;
2735   }
2736   if (!TargetInfo::initFeatureMap(Features, Diags, CPU, FeaturesVec))
2737     return false;
2738 
2739   // Can't do this earlier because we need to be able to explicitly enable
2740   // or disable these features and the things that they depend upon.
2741 
2742   // Enable popcnt if sse4.2 is enabled and popcnt is not explicitly disabled.
2743   auto I = Features.find("sse4.2");
2744   if (I != Features.end() && I->getValue() &&
2745       std::find(FeaturesVec.begin(), FeaturesVec.end(), "-popcnt") ==
2746           FeaturesVec.end())
2747     Features["popcnt"] = true;
2748 
2749   // Enable prfchw if 3DNow! is enabled and prfchw is not explicitly disabled.
2750   I = Features.find("3dnow");
2751   if (I != Features.end() && I->getValue() &&
2752       std::find(FeaturesVec.begin(), FeaturesVec.end(), "-prfchw") ==
2753           FeaturesVec.end())
2754     Features["prfchw"] = true;
2755 
2756   // Additionally, if SSE is enabled and mmx is not explicitly disabled,
2757   // then enable MMX.
2758   I = Features.find("sse");
2759   if (I != Features.end() && I->getValue() &&
2760       std::find(FeaturesVec.begin(), FeaturesVec.end(), "-mmx") ==
2761           FeaturesVec.end())
2762     Features["mmx"] = true;
2763 
2764   return true;
2765 }
2766 
setSSELevel(llvm::StringMap<bool> & Features,X86SSEEnum Level,bool Enabled)2767 void X86TargetInfo::setSSELevel(llvm::StringMap<bool> &Features,
2768                                 X86SSEEnum Level, bool Enabled) {
2769   if (Enabled) {
2770     switch (Level) {
2771     case AVX512F:
2772       Features["avx512f"] = true;
2773     case AVX2:
2774       Features["avx2"] = true;
2775     case AVX:
2776       Features["avx"] = true;
2777       Features["xsave"] = true;
2778     case SSE42:
2779       Features["sse4.2"] = true;
2780     case SSE41:
2781       Features["sse4.1"] = true;
2782     case SSSE3:
2783       Features["ssse3"] = true;
2784     case SSE3:
2785       Features["sse3"] = true;
2786     case SSE2:
2787       Features["sse2"] = true;
2788     case SSE1:
2789       Features["sse"] = true;
2790     case NoSSE:
2791       break;
2792     }
2793     return;
2794   }
2795 
2796   switch (Level) {
2797   case NoSSE:
2798   case SSE1:
2799     Features["sse"] = false;
2800   case SSE2:
2801     Features["sse2"] = Features["pclmul"] = Features["aes"] =
2802       Features["sha"] = false;
2803   case SSE3:
2804     Features["sse3"] = false;
2805     setXOPLevel(Features, NoXOP, false);
2806   case SSSE3:
2807     Features["ssse3"] = false;
2808   case SSE41:
2809     Features["sse4.1"] = false;
2810   case SSE42:
2811     Features["sse4.2"] = false;
2812   case AVX:
2813     Features["fma"] = Features["avx"] = Features["f16c"] = Features["xsave"] =
2814       Features["xsaveopt"] = false;
2815     setXOPLevel(Features, FMA4, false);
2816   case AVX2:
2817     Features["avx2"] = false;
2818   case AVX512F:
2819     Features["avx512f"] = Features["avx512cd"] = Features["avx512er"] =
2820       Features["avx512pf"] = Features["avx512dq"] = Features["avx512bw"] =
2821       Features["avx512vl"] = false;
2822   }
2823 }
2824 
setMMXLevel(llvm::StringMap<bool> & Features,MMX3DNowEnum Level,bool Enabled)2825 void X86TargetInfo::setMMXLevel(llvm::StringMap<bool> &Features,
2826                                 MMX3DNowEnum Level, bool Enabled) {
2827   if (Enabled) {
2828     switch (Level) {
2829     case AMD3DNowAthlon:
2830       Features["3dnowa"] = true;
2831     case AMD3DNow:
2832       Features["3dnow"] = true;
2833     case MMX:
2834       Features["mmx"] = true;
2835     case NoMMX3DNow:
2836       break;
2837     }
2838     return;
2839   }
2840 
2841   switch (Level) {
2842   case NoMMX3DNow:
2843   case MMX:
2844     Features["mmx"] = false;
2845   case AMD3DNow:
2846     Features["3dnow"] = false;
2847   case AMD3DNowAthlon:
2848     Features["3dnowa"] = false;
2849   }
2850 }
2851 
setXOPLevel(llvm::StringMap<bool> & Features,XOPEnum Level,bool Enabled)2852 void X86TargetInfo::setXOPLevel(llvm::StringMap<bool> &Features, XOPEnum Level,
2853                                 bool Enabled) {
2854   if (Enabled) {
2855     switch (Level) {
2856     case XOP:
2857       Features["xop"] = true;
2858     case FMA4:
2859       Features["fma4"] = true;
2860       setSSELevel(Features, AVX, true);
2861     case SSE4A:
2862       Features["sse4a"] = true;
2863       setSSELevel(Features, SSE3, true);
2864     case NoXOP:
2865       break;
2866     }
2867     return;
2868   }
2869 
2870   switch (Level) {
2871   case NoXOP:
2872   case SSE4A:
2873     Features["sse4a"] = false;
2874   case FMA4:
2875     Features["fma4"] = false;
2876   case XOP:
2877     Features["xop"] = false;
2878   }
2879 }
2880 
setFeatureEnabledImpl(llvm::StringMap<bool> & Features,StringRef Name,bool Enabled)2881 void X86TargetInfo::setFeatureEnabledImpl(llvm::StringMap<bool> &Features,
2882                                           StringRef Name, bool Enabled) {
2883   // This is a bit of a hack to deal with the sse4 target feature when used
2884   // as part of the target attribute. We handle sse4 correctly everywhere
2885   // else. See below for more information on how we handle the sse4 options.
2886   if (Name != "sse4")
2887     Features[Name] = Enabled;
2888 
2889   if (Name == "mmx") {
2890     setMMXLevel(Features, MMX, Enabled);
2891   } else if (Name == "sse") {
2892     setSSELevel(Features, SSE1, Enabled);
2893   } else if (Name == "sse2") {
2894     setSSELevel(Features, SSE2, Enabled);
2895   } else if (Name == "sse3") {
2896     setSSELevel(Features, SSE3, Enabled);
2897   } else if (Name == "ssse3") {
2898     setSSELevel(Features, SSSE3, Enabled);
2899   } else if (Name == "sse4.2") {
2900     setSSELevel(Features, SSE42, Enabled);
2901   } else if (Name == "sse4.1") {
2902     setSSELevel(Features, SSE41, Enabled);
2903   } else if (Name == "3dnow") {
2904     setMMXLevel(Features, AMD3DNow, Enabled);
2905   } else if (Name == "3dnowa") {
2906     setMMXLevel(Features, AMD3DNowAthlon, Enabled);
2907   } else if (Name == "aes") {
2908     if (Enabled)
2909       setSSELevel(Features, SSE2, Enabled);
2910   } else if (Name == "pclmul") {
2911     if (Enabled)
2912       setSSELevel(Features, SSE2, Enabled);
2913   } else if (Name == "avx") {
2914     setSSELevel(Features, AVX, Enabled);
2915   } else if (Name == "avx2") {
2916     setSSELevel(Features, AVX2, Enabled);
2917   } else if (Name == "avx512f") {
2918     setSSELevel(Features, AVX512F, Enabled);
2919   } else if (Name == "avx512cd" || Name == "avx512er" || Name == "avx512pf"
2920           || Name == "avx512dq" || Name == "avx512bw" || Name == "avx512vl") {
2921     if (Enabled)
2922       setSSELevel(Features, AVX512F, Enabled);
2923   } else if (Name == "fma") {
2924     if (Enabled)
2925       setSSELevel(Features, AVX, Enabled);
2926   } else if (Name == "fma4") {
2927     setXOPLevel(Features, FMA4, Enabled);
2928   } else if (Name == "xop") {
2929     setXOPLevel(Features, XOP, Enabled);
2930   } else if (Name == "sse4a") {
2931     setXOPLevel(Features, SSE4A, Enabled);
2932   } else if (Name == "f16c") {
2933     if (Enabled)
2934       setSSELevel(Features, AVX, Enabled);
2935   } else if (Name == "sha") {
2936     if (Enabled)
2937       setSSELevel(Features, SSE2, Enabled);
2938   } else if (Name == "sse4") {
2939     // We can get here via the __target__ attribute since that's not controlled
2940     // via the -msse4/-mno-sse4 command line alias. Handle this the same way
2941     // here - turn on the sse4.2 if enabled, turn off the sse4.1 level if
2942     // disabled.
2943     if (Enabled)
2944       setSSELevel(Features, SSE42, Enabled);
2945     else
2946       setSSELevel(Features, SSE41, Enabled);
2947   } else if (Name == "xsave") {
2948     if (Enabled)
2949       setSSELevel(Features, AVX, Enabled);
2950     else
2951       Features["xsaveopt"] = false;
2952   } else if (Name == "xsaveopt" || Name == "xsavec" || Name == "xsaves") {
2953     if (Enabled) {
2954       Features["xsave"] = true;
2955       setSSELevel(Features, AVX, Enabled);
2956     }
2957   }
2958 }
2959 
2960 /// handleTargetFeatures - Perform initialization based on the user
2961 /// configured set of features.
handleTargetFeatures(std::vector<std::string> & Features,DiagnosticsEngine & Diags)2962 bool X86TargetInfo::handleTargetFeatures(std::vector<std::string> &Features,
2963                                          DiagnosticsEngine &Diags) {
2964   for (const auto &Feature : Features) {
2965     if (Feature[0] != '+')
2966       continue;
2967 
2968     if (Feature == "+aes") {
2969       HasAES = true;
2970     } else if (Feature == "+pclmul") {
2971       HasPCLMUL = true;
2972     } else if (Feature == "+lzcnt") {
2973       HasLZCNT = true;
2974     } else if (Feature == "+rdrnd") {
2975       HasRDRND = true;
2976     } else if (Feature == "+fsgsbase") {
2977       HasFSGSBASE = true;
2978     } else if (Feature == "+bmi") {
2979       HasBMI = true;
2980     } else if (Feature == "+bmi2") {
2981       HasBMI2 = true;
2982     } else if (Feature == "+popcnt") {
2983       HasPOPCNT = true;
2984     } else if (Feature == "+rtm") {
2985       HasRTM = true;
2986     } else if (Feature == "+prfchw") {
2987       HasPRFCHW = true;
2988     } else if (Feature == "+rdseed") {
2989       HasRDSEED = true;
2990     } else if (Feature == "+adx") {
2991       HasADX = true;
2992     } else if (Feature == "+tbm") {
2993       HasTBM = true;
2994     } else if (Feature == "+fma") {
2995       HasFMA = true;
2996     } else if (Feature == "+f16c") {
2997       HasF16C = true;
2998     } else if (Feature == "+avx512cd") {
2999       HasAVX512CD = true;
3000     } else if (Feature == "+avx512er") {
3001       HasAVX512ER = true;
3002     } else if (Feature == "+avx512pf") {
3003       HasAVX512PF = true;
3004     } else if (Feature == "+avx512dq") {
3005       HasAVX512DQ = true;
3006     } else if (Feature == "+avx512bw") {
3007       HasAVX512BW = true;
3008     } else if (Feature == "+avx512vl") {
3009       HasAVX512VL = true;
3010     } else if (Feature == "+sha") {
3011       HasSHA = true;
3012     } else if (Feature == "+cx16") {
3013       HasCX16 = true;
3014     } else if (Feature == "+fxsr") {
3015       HasFXSR = true;
3016     } else if (Feature == "+xsave") {
3017       HasXSAVE = true;
3018     } else if (Feature == "+xsaveopt") {
3019       HasXSAVEOPT = true;
3020     } else if (Feature == "+xsavec") {
3021       HasXSAVEC = true;
3022     } else if (Feature == "+xsaves") {
3023       HasXSAVES = true;
3024     }
3025 
3026     X86SSEEnum Level = llvm::StringSwitch<X86SSEEnum>(Feature)
3027       .Case("+avx512f", AVX512F)
3028       .Case("+avx2", AVX2)
3029       .Case("+avx", AVX)
3030       .Case("+sse4.2", SSE42)
3031       .Case("+sse4.1", SSE41)
3032       .Case("+ssse3", SSSE3)
3033       .Case("+sse3", SSE3)
3034       .Case("+sse2", SSE2)
3035       .Case("+sse", SSE1)
3036       .Default(NoSSE);
3037     SSELevel = std::max(SSELevel, Level);
3038 
3039     MMX3DNowEnum ThreeDNowLevel =
3040       llvm::StringSwitch<MMX3DNowEnum>(Feature)
3041         .Case("+3dnowa", AMD3DNowAthlon)
3042         .Case("+3dnow", AMD3DNow)
3043         .Case("+mmx", MMX)
3044         .Default(NoMMX3DNow);
3045     MMX3DNowLevel = std::max(MMX3DNowLevel, ThreeDNowLevel);
3046 
3047     XOPEnum XLevel = llvm::StringSwitch<XOPEnum>(Feature)
3048         .Case("+xop", XOP)
3049         .Case("+fma4", FMA4)
3050         .Case("+sse4a", SSE4A)
3051         .Default(NoXOP);
3052     XOPLevel = std::max(XOPLevel, XLevel);
3053   }
3054 
3055   // LLVM doesn't have a separate switch for fpmath, so only accept it if it
3056   // matches the selected sse level.
3057   if ((FPMath == FP_SSE && SSELevel < SSE1) ||
3058       (FPMath == FP_387 && SSELevel >= SSE1)) {
3059     Diags.Report(diag::err_target_unsupported_fpmath) <<
3060       (FPMath == FP_SSE ? "sse" : "387");
3061     return false;
3062   }
3063 
3064   SimdDefaultAlign =
3065       hasFeature("avx512f") ? 512 : hasFeature("avx") ? 256 : 128;
3066   return true;
3067 }
3068 
3069 /// X86TargetInfo::getTargetDefines - Return the set of the X86-specific macro
3070 /// definitions for this particular subtarget.
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const3071 void X86TargetInfo::getTargetDefines(const LangOptions &Opts,
3072                                      MacroBuilder &Builder) const {
3073   // Target identification.
3074   if (getTriple().getArch() == llvm::Triple::x86_64) {
3075     Builder.defineMacro("__amd64__");
3076     Builder.defineMacro("__amd64");
3077     Builder.defineMacro("__x86_64");
3078     Builder.defineMacro("__x86_64__");
3079     if (getTriple().getArchName() == "x86_64h") {
3080       Builder.defineMacro("__x86_64h");
3081       Builder.defineMacro("__x86_64h__");
3082     }
3083   } else {
3084     DefineStd(Builder, "i386", Opts);
3085   }
3086 
3087   // Subtarget options.
3088   // FIXME: We are hard-coding the tune parameters based on the CPU, but they
3089   // truly should be based on -mtune options.
3090   switch (CPU) {
3091   case CK_Generic:
3092     break;
3093   case CK_i386:
3094     // The rest are coming from the i386 define above.
3095     Builder.defineMacro("__tune_i386__");
3096     break;
3097   case CK_i486:
3098   case CK_WinChipC6:
3099   case CK_WinChip2:
3100   case CK_C3:
3101     defineCPUMacros(Builder, "i486");
3102     break;
3103   case CK_PentiumMMX:
3104     Builder.defineMacro("__pentium_mmx__");
3105     Builder.defineMacro("__tune_pentium_mmx__");
3106     // Fallthrough
3107   case CK_i586:
3108   case CK_Pentium:
3109     defineCPUMacros(Builder, "i586");
3110     defineCPUMacros(Builder, "pentium");
3111     break;
3112   case CK_Pentium3:
3113   case CK_Pentium3M:
3114   case CK_PentiumM:
3115     Builder.defineMacro("__tune_pentium3__");
3116     // Fallthrough
3117   case CK_Pentium2:
3118   case CK_C3_2:
3119     Builder.defineMacro("__tune_pentium2__");
3120     // Fallthrough
3121   case CK_PentiumPro:
3122     Builder.defineMacro("__tune_i686__");
3123     Builder.defineMacro("__tune_pentiumpro__");
3124     // Fallthrough
3125   case CK_i686:
3126     Builder.defineMacro("__i686");
3127     Builder.defineMacro("__i686__");
3128     // Strangely, __tune_i686__ isn't defined by GCC when CPU == i686.
3129     Builder.defineMacro("__pentiumpro");
3130     Builder.defineMacro("__pentiumpro__");
3131     break;
3132   case CK_Pentium4:
3133   case CK_Pentium4M:
3134     defineCPUMacros(Builder, "pentium4");
3135     break;
3136   case CK_Yonah:
3137   case CK_Prescott:
3138   case CK_Nocona:
3139     defineCPUMacros(Builder, "nocona");
3140     break;
3141   case CK_Core2:
3142   case CK_Penryn:
3143     defineCPUMacros(Builder, "core2");
3144     break;
3145   case CK_Bonnell:
3146     defineCPUMacros(Builder, "atom");
3147     break;
3148   case CK_Silvermont:
3149     defineCPUMacros(Builder, "slm");
3150     break;
3151   case CK_Nehalem:
3152   case CK_Westmere:
3153   case CK_SandyBridge:
3154   case CK_IvyBridge:
3155   case CK_Haswell:
3156   case CK_Broadwell:
3157     // FIXME: Historically, we defined this legacy name, it would be nice to
3158     // remove it at some point. We've never exposed fine-grained names for
3159     // recent primary x86 CPUs, and we should keep it that way.
3160     defineCPUMacros(Builder, "corei7");
3161     break;
3162   case CK_Skylake:
3163     // FIXME: Historically, we defined this legacy name, it would be nice to
3164     // remove it at some point. This is the only fine-grained CPU macro in the
3165     // main intel CPU line, and it would be better to not have these and force
3166     // people to use ISA macros.
3167     defineCPUMacros(Builder, "skx");
3168     break;
3169   case CK_KNL:
3170     defineCPUMacros(Builder, "knl");
3171     break;
3172   case CK_K6_2:
3173     Builder.defineMacro("__k6_2__");
3174     Builder.defineMacro("__tune_k6_2__");
3175     // Fallthrough
3176   case CK_K6_3:
3177     if (CPU != CK_K6_2) {  // In case of fallthrough
3178       // FIXME: GCC may be enabling these in cases where some other k6
3179       // architecture is specified but -m3dnow is explicitly provided. The
3180       // exact semantics need to be determined and emulated here.
3181       Builder.defineMacro("__k6_3__");
3182       Builder.defineMacro("__tune_k6_3__");
3183     }
3184     // Fallthrough
3185   case CK_K6:
3186     defineCPUMacros(Builder, "k6");
3187     break;
3188   case CK_Athlon:
3189   case CK_AthlonThunderbird:
3190   case CK_Athlon4:
3191   case CK_AthlonXP:
3192   case CK_AthlonMP:
3193     defineCPUMacros(Builder, "athlon");
3194     if (SSELevel != NoSSE) {
3195       Builder.defineMacro("__athlon_sse__");
3196       Builder.defineMacro("__tune_athlon_sse__");
3197     }
3198     break;
3199   case CK_K8:
3200   case CK_K8SSE3:
3201   case CK_x86_64:
3202   case CK_Opteron:
3203   case CK_OpteronSSE3:
3204   case CK_Athlon64:
3205   case CK_Athlon64SSE3:
3206   case CK_AthlonFX:
3207     defineCPUMacros(Builder, "k8");
3208     break;
3209   case CK_AMDFAM10:
3210     defineCPUMacros(Builder, "amdfam10");
3211     break;
3212   case CK_BTVER1:
3213     defineCPUMacros(Builder, "btver1");
3214     break;
3215   case CK_BTVER2:
3216     defineCPUMacros(Builder, "btver2");
3217     break;
3218   case CK_BDVER1:
3219     defineCPUMacros(Builder, "bdver1");
3220     break;
3221   case CK_BDVER2:
3222     defineCPUMacros(Builder, "bdver2");
3223     break;
3224   case CK_BDVER3:
3225     defineCPUMacros(Builder, "bdver3");
3226     break;
3227   case CK_BDVER4:
3228     defineCPUMacros(Builder, "bdver4");
3229     break;
3230   case CK_Geode:
3231     defineCPUMacros(Builder, "geode");
3232     break;
3233   }
3234 
3235   // Target properties.
3236   Builder.defineMacro("__REGISTER_PREFIX__", "");
3237 
3238   // Define __NO_MATH_INLINES on linux/x86 so that we don't get inline
3239   // functions in glibc header files that use FP Stack inline asm which the
3240   // backend can't deal with (PR879).
3241   Builder.defineMacro("__NO_MATH_INLINES");
3242 
3243   if (HasAES)
3244     Builder.defineMacro("__AES__");
3245 
3246   if (HasPCLMUL)
3247     Builder.defineMacro("__PCLMUL__");
3248 
3249   if (HasLZCNT)
3250     Builder.defineMacro("__LZCNT__");
3251 
3252   if (HasRDRND)
3253     Builder.defineMacro("__RDRND__");
3254 
3255   if (HasFSGSBASE)
3256     Builder.defineMacro("__FSGSBASE__");
3257 
3258   if (HasBMI)
3259     Builder.defineMacro("__BMI__");
3260 
3261   if (HasBMI2)
3262     Builder.defineMacro("__BMI2__");
3263 
3264   if (HasPOPCNT)
3265     Builder.defineMacro("__POPCNT__");
3266 
3267   if (HasRTM)
3268     Builder.defineMacro("__RTM__");
3269 
3270   if (HasPRFCHW)
3271     Builder.defineMacro("__PRFCHW__");
3272 
3273   if (HasRDSEED)
3274     Builder.defineMacro("__RDSEED__");
3275 
3276   if (HasADX)
3277     Builder.defineMacro("__ADX__");
3278 
3279   if (HasTBM)
3280     Builder.defineMacro("__TBM__");
3281 
3282   switch (XOPLevel) {
3283   case XOP:
3284     Builder.defineMacro("__XOP__");
3285   case FMA4:
3286     Builder.defineMacro("__FMA4__");
3287   case SSE4A:
3288     Builder.defineMacro("__SSE4A__");
3289   case NoXOP:
3290     break;
3291   }
3292 
3293   if (HasFMA)
3294     Builder.defineMacro("__FMA__");
3295 
3296   if (HasF16C)
3297     Builder.defineMacro("__F16C__");
3298 
3299   if (HasAVX512CD)
3300     Builder.defineMacro("__AVX512CD__");
3301   if (HasAVX512ER)
3302     Builder.defineMacro("__AVX512ER__");
3303   if (HasAVX512PF)
3304     Builder.defineMacro("__AVX512PF__");
3305   if (HasAVX512DQ)
3306     Builder.defineMacro("__AVX512DQ__");
3307   if (HasAVX512BW)
3308     Builder.defineMacro("__AVX512BW__");
3309   if (HasAVX512VL)
3310     Builder.defineMacro("__AVX512VL__");
3311 
3312   if (HasSHA)
3313     Builder.defineMacro("__SHA__");
3314 
3315   if (HasFXSR)
3316     Builder.defineMacro("__FXSR__");
3317   if (HasXSAVE)
3318     Builder.defineMacro("__XSAVE__");
3319   if (HasXSAVEOPT)
3320     Builder.defineMacro("__XSAVEOPT__");
3321   if (HasXSAVEC)
3322     Builder.defineMacro("__XSAVEC__");
3323   if (HasXSAVES)
3324     Builder.defineMacro("__XSAVES__");
3325 
3326   if (HasCX16)
3327     Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_16");
3328 
3329   // Each case falls through to the previous one here.
3330   switch (SSELevel) {
3331   case AVX512F:
3332     Builder.defineMacro("__AVX512F__");
3333   case AVX2:
3334     Builder.defineMacro("__AVX2__");
3335   case AVX:
3336     Builder.defineMacro("__AVX__");
3337   case SSE42:
3338     Builder.defineMacro("__SSE4_2__");
3339   case SSE41:
3340     Builder.defineMacro("__SSE4_1__");
3341   case SSSE3:
3342     Builder.defineMacro("__SSSE3__");
3343   case SSE3:
3344     Builder.defineMacro("__SSE3__");
3345   case SSE2:
3346     Builder.defineMacro("__SSE2__");
3347     Builder.defineMacro("__SSE2_MATH__");  // -mfp-math=sse always implied.
3348   case SSE1:
3349     Builder.defineMacro("__SSE__");
3350     Builder.defineMacro("__SSE_MATH__");   // -mfp-math=sse always implied.
3351   case NoSSE:
3352     break;
3353   }
3354 
3355   if (Opts.MicrosoftExt && getTriple().getArch() == llvm::Triple::x86) {
3356     switch (SSELevel) {
3357     case AVX512F:
3358     case AVX2:
3359     case AVX:
3360     case SSE42:
3361     case SSE41:
3362     case SSSE3:
3363     case SSE3:
3364     case SSE2:
3365       Builder.defineMacro("_M_IX86_FP", Twine(2));
3366       break;
3367     case SSE1:
3368       Builder.defineMacro("_M_IX86_FP", Twine(1));
3369       break;
3370     default:
3371       Builder.defineMacro("_M_IX86_FP", Twine(0));
3372     }
3373   }
3374 
3375   // Each case falls through to the previous one here.
3376   switch (MMX3DNowLevel) {
3377   case AMD3DNowAthlon:
3378     Builder.defineMacro("__3dNOW_A__");
3379   case AMD3DNow:
3380     Builder.defineMacro("__3dNOW__");
3381   case MMX:
3382     Builder.defineMacro("__MMX__");
3383   case NoMMX3DNow:
3384     break;
3385   }
3386 
3387   if (CPU >= CK_i486) {
3388     Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_1");
3389     Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_2");
3390     Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4");
3391   }
3392   if (CPU >= CK_i586)
3393     Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8");
3394 }
3395 
hasFeature(StringRef Feature) const3396 bool X86TargetInfo::hasFeature(StringRef Feature) const {
3397   return llvm::StringSwitch<bool>(Feature)
3398       .Case("aes", HasAES)
3399       .Case("avx", SSELevel >= AVX)
3400       .Case("avx2", SSELevel >= AVX2)
3401       .Case("avx512f", SSELevel >= AVX512F)
3402       .Case("avx512cd", HasAVX512CD)
3403       .Case("avx512er", HasAVX512ER)
3404       .Case("avx512pf", HasAVX512PF)
3405       .Case("avx512dq", HasAVX512DQ)
3406       .Case("avx512bw", HasAVX512BW)
3407       .Case("avx512vl", HasAVX512VL)
3408       .Case("bmi", HasBMI)
3409       .Case("bmi2", HasBMI2)
3410       .Case("cx16", HasCX16)
3411       .Case("f16c", HasF16C)
3412       .Case("fma", HasFMA)
3413       .Case("fma4", XOPLevel >= FMA4)
3414       .Case("fsgsbase", HasFSGSBASE)
3415       .Case("fxsr", HasFXSR)
3416       .Case("lzcnt", HasLZCNT)
3417       .Case("mm3dnow", MMX3DNowLevel >= AMD3DNow)
3418       .Case("mm3dnowa", MMX3DNowLevel >= AMD3DNowAthlon)
3419       .Case("mmx", MMX3DNowLevel >= MMX)
3420       .Case("pclmul", HasPCLMUL)
3421       .Case("popcnt", HasPOPCNT)
3422       .Case("prfchw", HasPRFCHW)
3423       .Case("rdrnd", HasRDRND)
3424       .Case("rdseed", HasRDSEED)
3425       .Case("rtm", HasRTM)
3426       .Case("sha", HasSHA)
3427       .Case("sse", SSELevel >= SSE1)
3428       .Case("sse2", SSELevel >= SSE2)
3429       .Case("sse3", SSELevel >= SSE3)
3430       .Case("ssse3", SSELevel >= SSSE3)
3431       .Case("sse4.1", SSELevel >= SSE41)
3432       .Case("sse4.2", SSELevel >= SSE42)
3433       .Case("sse4a", XOPLevel >= SSE4A)
3434       .Case("tbm", HasTBM)
3435       .Case("x86", true)
3436       .Case("x86_32", getTriple().getArch() == llvm::Triple::x86)
3437       .Case("x86_64", getTriple().getArch() == llvm::Triple::x86_64)
3438       .Case("xop", XOPLevel >= XOP)
3439       .Case("xsave", HasXSAVE)
3440       .Case("xsavec", HasXSAVEC)
3441       .Case("xsaves", HasXSAVES)
3442       .Case("xsaveopt", HasXSAVEOPT)
3443       .Default(false);
3444 }
3445 
3446 // We can't use a generic validation scheme for the features accepted here
3447 // versus subtarget features accepted in the target attribute because the
3448 // bitfield structure that's initialized in the runtime only supports the
3449 // below currently rather than the full range of subtarget features. (See
3450 // X86TargetInfo::hasFeature for a somewhat comprehensive list).
validateCpuSupports(StringRef FeatureStr) const3451 bool X86TargetInfo::validateCpuSupports(StringRef FeatureStr) const {
3452   return llvm::StringSwitch<bool>(FeatureStr)
3453       .Case("cmov", true)
3454       .Case("mmx", true)
3455       .Case("popcnt", true)
3456       .Case("sse", true)
3457       .Case("sse2", true)
3458       .Case("sse3", true)
3459       .Case("sse4.1", true)
3460       .Case("sse4.2", true)
3461       .Case("avx", true)
3462       .Case("avx2", true)
3463       .Case("sse4a", true)
3464       .Case("fma4", true)
3465       .Case("xop", true)
3466       .Case("fma", true)
3467       .Case("avx512f", true)
3468       .Case("bmi", true)
3469       .Case("bmi2", true)
3470       .Default(false);
3471 }
3472 
3473 bool
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & Info) const3474 X86TargetInfo::validateAsmConstraint(const char *&Name,
3475                                      TargetInfo::ConstraintInfo &Info) const {
3476   switch (*Name) {
3477   default: return false;
3478   // Constant constraints.
3479   case 'e': // 32-bit signed integer constant for use with sign-extending x86_64
3480             // instructions.
3481   case 'Z': // 32-bit unsigned integer constant for use with zero-extending
3482             // x86_64 instructions.
3483   case 's':
3484     Info.setRequiresImmediate();
3485     return true;
3486   case 'I':
3487     Info.setRequiresImmediate(0, 31);
3488     return true;
3489   case 'J':
3490     Info.setRequiresImmediate(0, 63);
3491     return true;
3492   case 'K':
3493     Info.setRequiresImmediate(-128, 127);
3494     return true;
3495   case 'L':
3496     Info.setRequiresImmediate({ int(0xff), int(0xffff), int(0xffffffff) });
3497     return true;
3498   case 'M':
3499     Info.setRequiresImmediate(0, 3);
3500     return true;
3501   case 'N':
3502     Info.setRequiresImmediate(0, 255);
3503     return true;
3504   case 'O':
3505     Info.setRequiresImmediate(0, 127);
3506     return true;
3507   // Register constraints.
3508   case 'Y': // 'Y' is the first character for several 2-character constraints.
3509     // Shift the pointer to the second character of the constraint.
3510     Name++;
3511     switch (*Name) {
3512     default:
3513       return false;
3514     case '0': // First SSE register.
3515     case 't': // Any SSE register, when SSE2 is enabled.
3516     case 'i': // Any SSE register, when SSE2 and inter-unit moves enabled.
3517     case 'm': // Any MMX register, when inter-unit moves enabled.
3518       Info.setAllowsRegister();
3519       return true;
3520     }
3521   case 'f': // Any x87 floating point stack register.
3522     // Constraint 'f' cannot be used for output operands.
3523     if (Info.ConstraintStr[0] == '=')
3524       return false;
3525     Info.setAllowsRegister();
3526     return true;
3527   case 'a': // eax.
3528   case 'b': // ebx.
3529   case 'c': // ecx.
3530   case 'd': // edx.
3531   case 'S': // esi.
3532   case 'D': // edi.
3533   case 'A': // edx:eax.
3534   case 't': // Top of floating point stack.
3535   case 'u': // Second from top of floating point stack.
3536   case 'q': // Any register accessible as [r]l: a, b, c, and d.
3537   case 'y': // Any MMX register.
3538   case 'x': // Any SSE register.
3539   case 'Q': // Any register accessible as [r]h: a, b, c, and d.
3540   case 'R': // "Legacy" registers: ax, bx, cx, dx, di, si, sp, bp.
3541   case 'l': // "Index" registers: any general register that can be used as an
3542             // index in a base+index memory access.
3543     Info.setAllowsRegister();
3544     return true;
3545   // Floating point constant constraints.
3546   case 'C': // SSE floating point constant.
3547   case 'G': // x87 floating point constant.
3548     return true;
3549   }
3550 }
3551 
validateOutputSize(StringRef Constraint,unsigned Size) const3552 bool X86TargetInfo::validateOutputSize(StringRef Constraint,
3553                                        unsigned Size) const {
3554   // Strip off constraint modifiers.
3555   while (Constraint[0] == '=' ||
3556          Constraint[0] == '+' ||
3557          Constraint[0] == '&')
3558     Constraint = Constraint.substr(1);
3559 
3560   return validateOperandSize(Constraint, Size);
3561 }
3562 
validateInputSize(StringRef Constraint,unsigned Size) const3563 bool X86TargetInfo::validateInputSize(StringRef Constraint,
3564                                       unsigned Size) const {
3565   return validateOperandSize(Constraint, Size);
3566 }
3567 
validateOperandSize(StringRef Constraint,unsigned Size) const3568 bool X86TargetInfo::validateOperandSize(StringRef Constraint,
3569                                         unsigned Size) const {
3570   switch (Constraint[0]) {
3571   default: break;
3572   case 'y':
3573     return Size <= 64;
3574   case 'f':
3575   case 't':
3576   case 'u':
3577     return Size <= 128;
3578   case 'x':
3579     if (SSELevel >= AVX512F)
3580       // 512-bit zmm registers can be used if target supports AVX512F.
3581       return Size <= 512U;
3582     else if (SSELevel >= AVX)
3583       // 256-bit ymm registers can be used if target supports AVX.
3584       return Size <= 256U;
3585     return Size <= 128U;
3586   case 'Y':
3587     // 'Y' is the first character for several 2-character constraints.
3588     switch (Constraint[1]) {
3589     default: break;
3590     case 'm':
3591       // 'Ym' is synonymous with 'y'.
3592       return Size <= 64;
3593     case 'i':
3594     case 't':
3595       // 'Yi' and 'Yt' are synonymous with 'x' when SSE2 is enabled.
3596       if (SSELevel >= AVX512F)
3597         return Size <= 512U;
3598       else if (SSELevel >= AVX)
3599         return Size <= 256U;
3600       return SSELevel >= SSE2 && Size <= 128U;
3601     }
3602 
3603   }
3604 
3605   return true;
3606 }
3607 
3608 std::string
convertConstraint(const char * & Constraint) const3609 X86TargetInfo::convertConstraint(const char *&Constraint) const {
3610   switch (*Constraint) {
3611   case 'a': return std::string("{ax}");
3612   case 'b': return std::string("{bx}");
3613   case 'c': return std::string("{cx}");
3614   case 'd': return std::string("{dx}");
3615   case 'S': return std::string("{si}");
3616   case 'D': return std::string("{di}");
3617   case 'p': // address
3618     return std::string("im");
3619   case 't': // top of floating point stack.
3620     return std::string("{st}");
3621   case 'u': // second from top of floating point stack.
3622     return std::string("{st(1)}"); // second from top of floating point stack.
3623   default:
3624     return std::string(1, *Constraint);
3625   }
3626 }
3627 
3628 // X86-32 generic target
3629 class X86_32TargetInfo : public X86TargetInfo {
3630 public:
X86_32TargetInfo(const llvm::Triple & Triple)3631   X86_32TargetInfo(const llvm::Triple &Triple) : X86TargetInfo(Triple) {
3632     DoubleAlign = LongLongAlign = 32;
3633     LongDoubleWidth = 96;
3634     LongDoubleAlign = 32;
3635     SuitableAlign = 128;
3636     DataLayoutString = "e-m:e-p:32:32-f64:32:64-f80:32-n8:16:32-S128";
3637     SizeType = UnsignedInt;
3638     PtrDiffType = SignedInt;
3639     IntPtrType = SignedInt;
3640     RegParmMax = 3;
3641 
3642     // Use fpret for all types.
3643     RealTypeUsesObjCFPRet = ((1 << TargetInfo::Float) |
3644                              (1 << TargetInfo::Double) |
3645                              (1 << TargetInfo::LongDouble));
3646 
3647     // x86-32 has atomics up to 8 bytes
3648     // FIXME: Check that we actually have cmpxchg8b before setting
3649     // MaxAtomicInlineWidth. (cmpxchg8b is an i586 instruction.)
3650     MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 64;
3651   }
getBuiltinVaListKind() const3652   BuiltinVaListKind getBuiltinVaListKind() const override {
3653     return TargetInfo::CharPtrBuiltinVaList;
3654   }
3655 
getEHDataRegisterNumber(unsigned RegNo) const3656   int getEHDataRegisterNumber(unsigned RegNo) const override {
3657     if (RegNo == 0) return 0;
3658     if (RegNo == 1) return 2;
3659     return -1;
3660   }
validateOperandSize(StringRef Constraint,unsigned Size) const3661   bool validateOperandSize(StringRef Constraint,
3662                            unsigned Size) const override {
3663     switch (Constraint[0]) {
3664     default: break;
3665     case 'R':
3666     case 'q':
3667     case 'Q':
3668     case 'a':
3669     case 'b':
3670     case 'c':
3671     case 'd':
3672     case 'S':
3673     case 'D':
3674       return Size <= 32;
3675     case 'A':
3676       return Size <= 64;
3677     }
3678 
3679     return X86TargetInfo::validateOperandSize(Constraint, Size);
3680   }
3681 };
3682 
3683 class NetBSDI386TargetInfo : public NetBSDTargetInfo<X86_32TargetInfo> {
3684 public:
NetBSDI386TargetInfo(const llvm::Triple & Triple)3685   NetBSDI386TargetInfo(const llvm::Triple &Triple)
3686       : NetBSDTargetInfo<X86_32TargetInfo>(Triple) {}
3687 
getFloatEvalMethod() const3688   unsigned getFloatEvalMethod() const override {
3689     unsigned Major, Minor, Micro;
3690     getTriple().getOSVersion(Major, Minor, Micro);
3691     // New NetBSD uses the default rounding mode.
3692     if (Major >= 7 || (Major == 6 && Minor == 99 && Micro >= 26) || Major == 0)
3693       return X86_32TargetInfo::getFloatEvalMethod();
3694     // NetBSD before 6.99.26 defaults to "double" rounding.
3695     return 1;
3696   }
3697 };
3698 
3699 class OpenBSDI386TargetInfo : public OpenBSDTargetInfo<X86_32TargetInfo> {
3700 public:
OpenBSDI386TargetInfo(const llvm::Triple & Triple)3701   OpenBSDI386TargetInfo(const llvm::Triple &Triple)
3702       : OpenBSDTargetInfo<X86_32TargetInfo>(Triple) {
3703     SizeType = UnsignedLong;
3704     IntPtrType = SignedLong;
3705     PtrDiffType = SignedLong;
3706   }
3707 };
3708 
3709 class BitrigI386TargetInfo : public BitrigTargetInfo<X86_32TargetInfo> {
3710 public:
BitrigI386TargetInfo(const llvm::Triple & Triple)3711   BitrigI386TargetInfo(const llvm::Triple &Triple)
3712       : BitrigTargetInfo<X86_32TargetInfo>(Triple) {
3713     SizeType = UnsignedLong;
3714     IntPtrType = SignedLong;
3715     PtrDiffType = SignedLong;
3716   }
3717 };
3718 
3719 class DarwinI386TargetInfo : public DarwinTargetInfo<X86_32TargetInfo> {
3720 public:
DarwinI386TargetInfo(const llvm::Triple & Triple)3721   DarwinI386TargetInfo(const llvm::Triple &Triple)
3722       : DarwinTargetInfo<X86_32TargetInfo>(Triple) {
3723     LongDoubleWidth = 128;
3724     LongDoubleAlign = 128;
3725     SuitableAlign = 128;
3726     MaxVectorAlign = 256;
3727     // The watchOS simulator uses the builtin bool type for Objective-C.
3728     llvm::Triple T = llvm::Triple(Triple);
3729     if (T.isWatchOS())
3730       UseSignedCharForObjCBool = false;
3731     SizeType = UnsignedLong;
3732     IntPtrType = SignedLong;
3733     DataLayoutString = "e-m:o-p:32:32-f64:32:64-f80:128-n8:16:32-S128";
3734     HasAlignMac68kSupport = true;
3735   }
3736 
handleTargetFeatures(std::vector<std::string> & Features,DiagnosticsEngine & Diags)3737   bool handleTargetFeatures(std::vector<std::string> &Features,
3738                             DiagnosticsEngine &Diags) override {
3739     if (!DarwinTargetInfo<X86_32TargetInfo>::handleTargetFeatures(Features,
3740                                                                   Diags))
3741       return false;
3742     // We now know the features we have: we can decide how to align vectors.
3743     MaxVectorAlign =
3744         hasFeature("avx512f") ? 512 : hasFeature("avx") ? 256 : 128;
3745     return true;
3746   }
3747 };
3748 
3749 // x86-32 Windows target
3750 class WindowsX86_32TargetInfo : public WindowsTargetInfo<X86_32TargetInfo> {
3751 public:
WindowsX86_32TargetInfo(const llvm::Triple & Triple)3752   WindowsX86_32TargetInfo(const llvm::Triple &Triple)
3753       : WindowsTargetInfo<X86_32TargetInfo>(Triple) {
3754     WCharType = UnsignedShort;
3755     DoubleAlign = LongLongAlign = 64;
3756     bool IsWinCOFF =
3757         getTriple().isOSWindows() && getTriple().isOSBinFormatCOFF();
3758     DataLayoutString = IsWinCOFF
3759                            ? "e-m:x-p:32:32-i64:64-f80:32-n8:16:32-a:0:32-S32"
3760                            : "e-m:e-p:32:32-i64:64-f80:32-n8:16:32-a:0:32-S32";
3761   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const3762   void getTargetDefines(const LangOptions &Opts,
3763                         MacroBuilder &Builder) const override {
3764     WindowsTargetInfo<X86_32TargetInfo>::getTargetDefines(Opts, Builder);
3765   }
3766 };
3767 
3768 // x86-32 Windows Visual Studio target
3769 class MicrosoftX86_32TargetInfo : public WindowsX86_32TargetInfo {
3770 public:
MicrosoftX86_32TargetInfo(const llvm::Triple & Triple)3771   MicrosoftX86_32TargetInfo(const llvm::Triple &Triple)
3772       : WindowsX86_32TargetInfo(Triple) {
3773     LongDoubleWidth = LongDoubleAlign = 64;
3774     LongDoubleFormat = &llvm::APFloat::IEEEdouble;
3775   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const3776   void getTargetDefines(const LangOptions &Opts,
3777                         MacroBuilder &Builder) const override {
3778     WindowsX86_32TargetInfo::getTargetDefines(Opts, Builder);
3779     WindowsX86_32TargetInfo::getVisualStudioDefines(Opts, Builder);
3780     // The value of the following reflects processor type.
3781     // 300=386, 400=486, 500=Pentium, 600=Blend (default)
3782     // We lost the original triple, so we use the default.
3783     Builder.defineMacro("_M_IX86", "600");
3784   }
3785 };
3786 
addCygMingDefines(const LangOptions & Opts,MacroBuilder & Builder)3787 static void addCygMingDefines(const LangOptions &Opts, MacroBuilder &Builder) {
3788   // Mingw and cygwin define __declspec(a) to __attribute__((a)).  Clang
3789   // supports __declspec natively under -fms-extensions, but we define a no-op
3790   // __declspec macro anyway for pre-processor compatibility.
3791   if (Opts.MicrosoftExt)
3792     Builder.defineMacro("__declspec", "__declspec");
3793   else
3794     Builder.defineMacro("__declspec(a)", "__attribute__((a))");
3795 
3796   if (!Opts.MicrosoftExt) {
3797     // Provide macros for all the calling convention keywords.  Provide both
3798     // single and double underscore prefixed variants.  These are available on
3799     // x64 as well as x86, even though they have no effect.
3800     const char *CCs[] = {"cdecl", "stdcall", "fastcall", "thiscall", "pascal"};
3801     for (const char *CC : CCs) {
3802       std::string GCCSpelling = "__attribute__((__";
3803       GCCSpelling += CC;
3804       GCCSpelling += "__))";
3805       Builder.defineMacro(Twine("_") + CC, GCCSpelling);
3806       Builder.defineMacro(Twine("__") + CC, GCCSpelling);
3807     }
3808   }
3809 }
3810 
addMinGWDefines(const LangOptions & Opts,MacroBuilder & Builder)3811 static void addMinGWDefines(const LangOptions &Opts, MacroBuilder &Builder) {
3812   Builder.defineMacro("__MSVCRT__");
3813   Builder.defineMacro("__MINGW32__");
3814   addCygMingDefines(Opts, Builder);
3815 }
3816 
3817 // x86-32 MinGW target
3818 class MinGWX86_32TargetInfo : public WindowsX86_32TargetInfo {
3819 public:
MinGWX86_32TargetInfo(const llvm::Triple & Triple)3820   MinGWX86_32TargetInfo(const llvm::Triple &Triple)
3821       : WindowsX86_32TargetInfo(Triple) {}
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const3822   void getTargetDefines(const LangOptions &Opts,
3823                         MacroBuilder &Builder) const override {
3824     WindowsX86_32TargetInfo::getTargetDefines(Opts, Builder);
3825     DefineStd(Builder, "WIN32", Opts);
3826     DefineStd(Builder, "WINNT", Opts);
3827     Builder.defineMacro("_X86_");
3828     addMinGWDefines(Opts, Builder);
3829   }
3830 };
3831 
3832 // x86-32 Cygwin target
3833 class CygwinX86_32TargetInfo : public X86_32TargetInfo {
3834 public:
CygwinX86_32TargetInfo(const llvm::Triple & Triple)3835   CygwinX86_32TargetInfo(const llvm::Triple &Triple)
3836       : X86_32TargetInfo(Triple) {
3837     WCharType = UnsignedShort;
3838     DoubleAlign = LongLongAlign = 64;
3839     DataLayoutString = "e-m:x-p:32:32-i64:64-f80:32-n8:16:32-a:0:32-S32";
3840   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const3841   void getTargetDefines(const LangOptions &Opts,
3842                         MacroBuilder &Builder) const override {
3843     X86_32TargetInfo::getTargetDefines(Opts, Builder);
3844     Builder.defineMacro("_X86_");
3845     Builder.defineMacro("__CYGWIN__");
3846     Builder.defineMacro("__CYGWIN32__");
3847     addCygMingDefines(Opts, Builder);
3848     DefineStd(Builder, "unix", Opts);
3849     if (Opts.CPlusPlus)
3850       Builder.defineMacro("_GNU_SOURCE");
3851   }
3852 };
3853 
3854 // x86-32 Haiku target
3855 class HaikuX86_32TargetInfo : public X86_32TargetInfo {
3856 public:
HaikuX86_32TargetInfo(const llvm::Triple & Triple)3857   HaikuX86_32TargetInfo(const llvm::Triple &Triple) : X86_32TargetInfo(Triple) {
3858     SizeType = UnsignedLong;
3859     IntPtrType = SignedLong;
3860     PtrDiffType = SignedLong;
3861     ProcessIDType = SignedLong;
3862     this->UserLabelPrefix = "";
3863     this->TLSSupported = false;
3864   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const3865   void getTargetDefines(const LangOptions &Opts,
3866                         MacroBuilder &Builder) const override {
3867     X86_32TargetInfo::getTargetDefines(Opts, Builder);
3868     Builder.defineMacro("__INTEL__");
3869     Builder.defineMacro("__HAIKU__");
3870   }
3871 };
3872 
3873 // X86-32 MCU target
3874 class MCUX86_32TargetInfo : public X86_32TargetInfo {
3875 public:
MCUX86_32TargetInfo(const llvm::Triple & Triple)3876   MCUX86_32TargetInfo(const llvm::Triple &Triple) : X86_32TargetInfo(Triple) {
3877     LongDoubleWidth = 64;
3878     LongDoubleFormat = &llvm::APFloat::IEEEdouble;
3879   }
3880 
checkCallingConvention(CallingConv CC) const3881   CallingConvCheckResult checkCallingConvention(CallingConv CC) const override {
3882     // On MCU we support only C calling convention.
3883     return CC == CC_C ? CCCR_OK : CCCR_Warning;
3884   }
3885 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const3886   void getTargetDefines(const LangOptions &Opts,
3887                         MacroBuilder &Builder) const override {
3888     X86_32TargetInfo::getTargetDefines(Opts, Builder);
3889     Builder.defineMacro("__iamcu");
3890     Builder.defineMacro("__iamcu__");
3891   }
3892 };
3893 
3894 // RTEMS Target
3895 template<typename Target>
3896 class RTEMSTargetInfo : public OSTargetInfo<Target> {
3897 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const3898   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
3899                     MacroBuilder &Builder) const override {
3900     // RTEMS defines; list based off of gcc output
3901 
3902     Builder.defineMacro("__rtems__");
3903     Builder.defineMacro("__ELF__");
3904   }
3905 
3906 public:
RTEMSTargetInfo(const llvm::Triple & Triple)3907   RTEMSTargetInfo(const llvm::Triple &Triple) : OSTargetInfo<Target>(Triple) {
3908     this->UserLabelPrefix = "";
3909 
3910     switch (Triple.getArch()) {
3911     default:
3912     case llvm::Triple::x86:
3913       // this->MCountName = ".mcount";
3914       break;
3915     case llvm::Triple::mips:
3916     case llvm::Triple::mipsel:
3917     case llvm::Triple::ppc:
3918     case llvm::Triple::ppc64:
3919     case llvm::Triple::ppc64le:
3920       // this->MCountName = "_mcount";
3921       break;
3922     case llvm::Triple::arm:
3923       // this->MCountName = "__mcount";
3924       break;
3925     }
3926   }
3927 };
3928 
3929 // x86-32 RTEMS target
3930 class RTEMSX86_32TargetInfo : public X86_32TargetInfo {
3931 public:
RTEMSX86_32TargetInfo(const llvm::Triple & Triple)3932   RTEMSX86_32TargetInfo(const llvm::Triple &Triple) : X86_32TargetInfo(Triple) {
3933     SizeType = UnsignedLong;
3934     IntPtrType = SignedLong;
3935     PtrDiffType = SignedLong;
3936     this->UserLabelPrefix = "";
3937   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const3938   void getTargetDefines(const LangOptions &Opts,
3939                         MacroBuilder &Builder) const override {
3940     X86_32TargetInfo::getTargetDefines(Opts, Builder);
3941     Builder.defineMacro("__INTEL__");
3942     Builder.defineMacro("__rtems__");
3943   }
3944 };
3945 
3946 // x86-64 generic target
3947 class X86_64TargetInfo : public X86TargetInfo {
3948 public:
X86_64TargetInfo(const llvm::Triple & Triple)3949   X86_64TargetInfo(const llvm::Triple &Triple) : X86TargetInfo(Triple) {
3950     const bool IsX32 = getTriple().getEnvironment() == llvm::Triple::GNUX32;
3951     bool IsWinCOFF =
3952         getTriple().isOSWindows() && getTriple().isOSBinFormatCOFF();
3953     LongWidth = LongAlign = PointerWidth = PointerAlign = IsX32 ? 32 : 64;
3954     LongDoubleWidth = 128;
3955     LongDoubleAlign = 128;
3956     LargeArrayMinWidth = 128;
3957     LargeArrayAlign = 128;
3958     SuitableAlign = 128;
3959     SizeType    = IsX32 ? UnsignedInt      : UnsignedLong;
3960     PtrDiffType = IsX32 ? SignedInt        : SignedLong;
3961     IntPtrType  = IsX32 ? SignedInt        : SignedLong;
3962     IntMaxType  = IsX32 ? SignedLongLong   : SignedLong;
3963     Int64Type   = IsX32 ? SignedLongLong   : SignedLong;
3964     RegParmMax = 6;
3965 
3966     // Pointers are 32-bit in x32.
3967     DataLayoutString = IsX32 ? "e-m:e-p:32:32-i64:64-f80:128-n8:16:32:64-S128"
3968                              : IsWinCOFF
3969                                    ? "e-m:w-i64:64-f80:128-n8:16:32:64-S128"
3970                                    : "e-m:e-i64:64-f80:128-n8:16:32:64-S128";
3971 
3972     // Use fpret only for long double.
3973     RealTypeUsesObjCFPRet = (1 << TargetInfo::LongDouble);
3974 
3975     // Use fp2ret for _Complex long double.
3976     ComplexLongDoubleUsesFP2Ret = true;
3977 
3978     // Make __builtin_ms_va_list available.
3979     HasBuiltinMSVaList = true;
3980 
3981     // x86-64 has atomics up to 16 bytes.
3982     MaxAtomicPromoteWidth = 128;
3983     MaxAtomicInlineWidth = 128;
3984   }
getBuiltinVaListKind() const3985   BuiltinVaListKind getBuiltinVaListKind() const override {
3986     return TargetInfo::X86_64ABIBuiltinVaList;
3987   }
3988 
getEHDataRegisterNumber(unsigned RegNo) const3989   int getEHDataRegisterNumber(unsigned RegNo) const override {
3990     if (RegNo == 0) return 0;
3991     if (RegNo == 1) return 1;
3992     return -1;
3993   }
3994 
checkCallingConvention(CallingConv CC) const3995   CallingConvCheckResult checkCallingConvention(CallingConv CC) const override {
3996     return (CC == CC_C ||
3997             CC == CC_X86VectorCall ||
3998             CC == CC_IntelOclBicc ||
3999             CC == CC_X86_64Win64) ? CCCR_OK : CCCR_Warning;
4000   }
4001 
getDefaultCallingConv(CallingConvMethodType MT) const4002   CallingConv getDefaultCallingConv(CallingConvMethodType MT) const override {
4003     return CC_C;
4004   }
4005 
4006   // for x32 we need it here explicitly
hasInt128Type() const4007   bool hasInt128Type() const override { return true; }
4008 
validateGlobalRegisterVariable(StringRef RegName,unsigned RegSize,bool & HasSizeMismatch) const4009   bool validateGlobalRegisterVariable(StringRef RegName,
4010                                       unsigned RegSize,
4011                                       bool &HasSizeMismatch) const override {
4012     // rsp and rbp are the only 64-bit registers the x86 backend can currently
4013     // handle.
4014     if (RegName.equals("rsp") || RegName.equals("rbp")) {
4015       // Check that the register size is 64-bit.
4016       HasSizeMismatch = RegSize != 64;
4017       return true;
4018     }
4019 
4020     // Check if the register is a 32-bit register the backend can handle.
4021     return X86TargetInfo::validateGlobalRegisterVariable(RegName, RegSize,
4022                                                          HasSizeMismatch);
4023   }
4024 };
4025 
4026 // x86-64 Windows target
4027 class WindowsX86_64TargetInfo : public WindowsTargetInfo<X86_64TargetInfo> {
4028 public:
WindowsX86_64TargetInfo(const llvm::Triple & Triple)4029   WindowsX86_64TargetInfo(const llvm::Triple &Triple)
4030       : WindowsTargetInfo<X86_64TargetInfo>(Triple) {
4031     WCharType = UnsignedShort;
4032     LongWidth = LongAlign = 32;
4033     DoubleAlign = LongLongAlign = 64;
4034     IntMaxType = SignedLongLong;
4035     Int64Type = SignedLongLong;
4036     SizeType = UnsignedLongLong;
4037     PtrDiffType = SignedLongLong;
4038     IntPtrType = SignedLongLong;
4039     this->UserLabelPrefix = "";
4040   }
4041 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const4042   void getTargetDefines(const LangOptions &Opts,
4043                                 MacroBuilder &Builder) const override {
4044     WindowsTargetInfo<X86_64TargetInfo>::getTargetDefines(Opts, Builder);
4045     Builder.defineMacro("_WIN64");
4046   }
4047 
getBuiltinVaListKind() const4048   BuiltinVaListKind getBuiltinVaListKind() const override {
4049     return TargetInfo::CharPtrBuiltinVaList;
4050   }
4051 
checkCallingConvention(CallingConv CC) const4052   CallingConvCheckResult checkCallingConvention(CallingConv CC) const override {
4053     switch (CC) {
4054     case CC_X86StdCall:
4055     case CC_X86ThisCall:
4056     case CC_X86FastCall:
4057       return CCCR_Ignore;
4058     case CC_C:
4059     case CC_X86VectorCall:
4060     case CC_IntelOclBicc:
4061     case CC_X86_64SysV:
4062       return CCCR_OK;
4063     default:
4064       return CCCR_Warning;
4065     }
4066   }
4067 };
4068 
4069 // x86-64 Windows Visual Studio target
4070 class MicrosoftX86_64TargetInfo : public WindowsX86_64TargetInfo {
4071 public:
MicrosoftX86_64TargetInfo(const llvm::Triple & Triple)4072   MicrosoftX86_64TargetInfo(const llvm::Triple &Triple)
4073       : WindowsX86_64TargetInfo(Triple) {
4074     LongDoubleWidth = LongDoubleAlign = 64;
4075     LongDoubleFormat = &llvm::APFloat::IEEEdouble;
4076   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const4077   void getTargetDefines(const LangOptions &Opts,
4078                         MacroBuilder &Builder) const override {
4079     WindowsX86_64TargetInfo::getTargetDefines(Opts, Builder);
4080     WindowsX86_64TargetInfo::getVisualStudioDefines(Opts, Builder);
4081     Builder.defineMacro("_M_X64", "100");
4082     Builder.defineMacro("_M_AMD64", "100");
4083   }
4084 };
4085 
4086 // x86-64 MinGW target
4087 class MinGWX86_64TargetInfo : public WindowsX86_64TargetInfo {
4088 public:
MinGWX86_64TargetInfo(const llvm::Triple & Triple)4089   MinGWX86_64TargetInfo(const llvm::Triple &Triple)
4090       : WindowsX86_64TargetInfo(Triple) {
4091     // Mingw64 rounds long double size and alignment up to 16 bytes, but sticks
4092     // with x86 FP ops. Weird.
4093     LongDoubleWidth = LongDoubleAlign = 128;
4094     LongDoubleFormat = &llvm::APFloat::x87DoubleExtended;
4095   }
4096 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const4097   void getTargetDefines(const LangOptions &Opts,
4098                         MacroBuilder &Builder) const override {
4099     WindowsX86_64TargetInfo::getTargetDefines(Opts, Builder);
4100     DefineStd(Builder, "WIN64", Opts);
4101     Builder.defineMacro("__MINGW64__");
4102     addMinGWDefines(Opts, Builder);
4103 
4104     // GCC defines this macro when it is using __gxx_personality_seh0.
4105     if (!Opts.SjLjExceptions)
4106       Builder.defineMacro("__SEH__");
4107   }
4108 };
4109 
4110 // x86-64 Cygwin target
4111 class CygwinX86_64TargetInfo : public X86_64TargetInfo {
4112 public:
CygwinX86_64TargetInfo(const llvm::Triple & Triple)4113   CygwinX86_64TargetInfo(const llvm::Triple &Triple)
4114       : X86_64TargetInfo(Triple) {
4115     TLSSupported = false;
4116     WCharType = UnsignedShort;
4117   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const4118   void getTargetDefines(const LangOptions &Opts,
4119                         MacroBuilder &Builder) const override {
4120     X86_64TargetInfo::getTargetDefines(Opts, Builder);
4121     Builder.defineMacro("__x86_64__");
4122     Builder.defineMacro("__CYGWIN__");
4123     Builder.defineMacro("__CYGWIN64__");
4124     addCygMingDefines(Opts, Builder);
4125     DefineStd(Builder, "unix", Opts);
4126     if (Opts.CPlusPlus)
4127       Builder.defineMacro("_GNU_SOURCE");
4128 
4129     // GCC defines this macro when it is using __gxx_personality_seh0.
4130     if (!Opts.SjLjExceptions)
4131       Builder.defineMacro("__SEH__");
4132   }
4133 };
4134 
4135 class DarwinX86_64TargetInfo : public DarwinTargetInfo<X86_64TargetInfo> {
4136 public:
DarwinX86_64TargetInfo(const llvm::Triple & Triple)4137   DarwinX86_64TargetInfo(const llvm::Triple &Triple)
4138       : DarwinTargetInfo<X86_64TargetInfo>(Triple) {
4139     Int64Type = SignedLongLong;
4140     // The 64-bit iOS simulator uses the builtin bool type for Objective-C.
4141     llvm::Triple T = llvm::Triple(Triple);
4142     if (T.isiOS())
4143       UseSignedCharForObjCBool = false;
4144     DataLayoutString = "e-m:o-i64:64-f80:128-n8:16:32:64-S128";
4145   }
4146 
handleTargetFeatures(std::vector<std::string> & Features,DiagnosticsEngine & Diags)4147   bool handleTargetFeatures(std::vector<std::string> &Features,
4148                             DiagnosticsEngine &Diags) override {
4149     if (!DarwinTargetInfo<X86_64TargetInfo>::handleTargetFeatures(Features,
4150                                                                   Diags))
4151       return false;
4152     // We now know the features we have: we can decide how to align vectors.
4153     MaxVectorAlign =
4154         hasFeature("avx512f") ? 512 : hasFeature("avx") ? 256 : 128;
4155     return true;
4156   }
4157 };
4158 
4159 class OpenBSDX86_64TargetInfo : public OpenBSDTargetInfo<X86_64TargetInfo> {
4160 public:
OpenBSDX86_64TargetInfo(const llvm::Triple & Triple)4161   OpenBSDX86_64TargetInfo(const llvm::Triple &Triple)
4162       : OpenBSDTargetInfo<X86_64TargetInfo>(Triple) {
4163     IntMaxType = SignedLongLong;
4164     Int64Type = SignedLongLong;
4165   }
4166 };
4167 
4168 class BitrigX86_64TargetInfo : public BitrigTargetInfo<X86_64TargetInfo> {
4169 public:
BitrigX86_64TargetInfo(const llvm::Triple & Triple)4170   BitrigX86_64TargetInfo(const llvm::Triple &Triple)
4171       : BitrigTargetInfo<X86_64TargetInfo>(Triple) {
4172     IntMaxType = SignedLongLong;
4173     Int64Type = SignedLongLong;
4174   }
4175 };
4176 
4177 class ARMTargetInfo : public TargetInfo {
4178   // Possible FPU choices.
4179   enum FPUMode {
4180     VFP2FPU = (1 << 0),
4181     VFP3FPU = (1 << 1),
4182     VFP4FPU = (1 << 2),
4183     NeonFPU = (1 << 3),
4184     FPARMV8 = (1 << 4)
4185   };
4186 
4187   // Possible HWDiv features.
4188   enum HWDivMode {
4189     HWDivThumb = (1 << 0),
4190     HWDivARM = (1 << 1)
4191   };
4192 
FPUModeIsVFP(FPUMode Mode)4193   static bool FPUModeIsVFP(FPUMode Mode) {
4194     return Mode & (VFP2FPU | VFP3FPU | VFP4FPU | NeonFPU | FPARMV8);
4195   }
4196 
4197   static const TargetInfo::GCCRegAlias GCCRegAliases[];
4198   static const char * const GCCRegNames[];
4199 
4200   std::string ABI, CPU;
4201 
4202   StringRef CPUProfile;
4203   StringRef CPUAttr;
4204 
4205   enum {
4206     FP_Default,
4207     FP_VFP,
4208     FP_Neon
4209   } FPMath;
4210 
4211   unsigned ArchISA;
4212   unsigned ArchKind = llvm::ARM::AK_ARMV4T;
4213   unsigned ArchProfile;
4214   unsigned ArchVersion;
4215 
4216   unsigned FPU : 5;
4217 
4218   unsigned IsAAPCS : 1;
4219   unsigned HWDiv : 2;
4220 
4221   // Initialized via features.
4222   unsigned SoftFloat : 1;
4223   unsigned SoftFloatABI : 1;
4224 
4225   unsigned CRC : 1;
4226   unsigned Crypto : 1;
4227   unsigned DSP : 1;
4228   unsigned Unaligned : 1;
4229 
4230   enum {
4231     LDREX_B = (1 << 0), /// byte (8-bit)
4232     LDREX_H = (1 << 1), /// half (16-bit)
4233     LDREX_W = (1 << 2), /// word (32-bit)
4234     LDREX_D = (1 << 3), /// double (64-bit)
4235   };
4236 
4237   uint32_t LDREX;
4238 
4239   // ACLE 6.5.1 Hardware floating point
4240   enum {
4241     HW_FP_HP = (1 << 1), /// half (16-bit)
4242     HW_FP_SP = (1 << 2), /// single (32-bit)
4243     HW_FP_DP = (1 << 3), /// double (64-bit)
4244   };
4245   uint32_t HW_FP;
4246 
4247   static const Builtin::Info BuiltinInfo[];
4248 
setABIAAPCS()4249   void setABIAAPCS() {
4250     IsAAPCS = true;
4251 
4252     DoubleAlign = LongLongAlign = LongDoubleAlign = SuitableAlign = 64;
4253     const llvm::Triple &T = getTriple();
4254 
4255     // size_t is unsigned long on MachO-derived environments, NetBSD and Bitrig.
4256     if (T.isOSBinFormatMachO() || T.getOS() == llvm::Triple::NetBSD ||
4257         T.getOS() == llvm::Triple::Bitrig)
4258       SizeType = UnsignedLong;
4259     else
4260       SizeType = UnsignedInt;
4261 
4262     switch (T.getOS()) {
4263     case llvm::Triple::NetBSD:
4264       WCharType = SignedInt;
4265       break;
4266     case llvm::Triple::Win32:
4267       WCharType = UnsignedShort;
4268       break;
4269     case llvm::Triple::Linux:
4270     default:
4271       // AAPCS 7.1.1, ARM-Linux ABI 2.4: type of wchar_t is unsigned int.
4272       WCharType = UnsignedInt;
4273       break;
4274     }
4275 
4276     UseBitFieldTypeAlignment = true;
4277 
4278     ZeroLengthBitfieldBoundary = 0;
4279 
4280     // Thumb1 add sp, #imm requires the immediate value be multiple of 4,
4281     // so set preferred for small types to 32.
4282     if (T.isOSBinFormatMachO()) {
4283       DataLayoutString =
4284           BigEndian ? "E-m:o-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64"
4285                     : "e-m:o-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64";
4286     } else if (T.isOSWindows()) {
4287       assert(!BigEndian && "Windows on ARM does not support big endian");
4288       DataLayoutString = "e"
4289                          "-m:w"
4290                          "-p:32:32"
4291                          "-i64:64"
4292                          "-v128:64:128"
4293                          "-a:0:32"
4294                          "-n32"
4295                          "-S64";
4296     } else if (T.isOSNaCl()) {
4297       assert(!BigEndian && "NaCl on ARM does not support big endian");
4298       DataLayoutString = "e-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S128";
4299     } else {
4300       DataLayoutString =
4301           BigEndian ? "E-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64"
4302                     : "e-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64";
4303     }
4304 
4305     // FIXME: Enumerated types are variable width in straight AAPCS.
4306   }
4307 
setABIAPCS(bool IsAAPCS16)4308   void setABIAPCS(bool IsAAPCS16) {
4309     const llvm::Triple &T = getTriple();
4310 
4311     IsAAPCS = false;
4312 
4313     if (IsAAPCS16)
4314       DoubleAlign = LongLongAlign = LongDoubleAlign = SuitableAlign = 64;
4315     else
4316       DoubleAlign = LongLongAlign = LongDoubleAlign = SuitableAlign = 32;
4317 
4318     // size_t is unsigned int on FreeBSD.
4319     if (T.getOS() == llvm::Triple::FreeBSD)
4320       SizeType = UnsignedInt;
4321     else
4322       SizeType = UnsignedLong;
4323 
4324     // Revert to using SignedInt on apcs-gnu to comply with existing behaviour.
4325     WCharType = SignedInt;
4326 
4327     // Do not respect the alignment of bit-field types when laying out
4328     // structures. This corresponds to PCC_BITFIELD_TYPE_MATTERS in gcc.
4329     UseBitFieldTypeAlignment = false;
4330 
4331     /// gcc forces the alignment to 4 bytes, regardless of the type of the
4332     /// zero length bitfield.  This corresponds to EMPTY_FIELD_BOUNDARY in
4333     /// gcc.
4334     ZeroLengthBitfieldBoundary = 32;
4335 
4336     if (T.isOSBinFormatMachO() && IsAAPCS16) {
4337       assert(!BigEndian && "AAPCS16 does not support big-endian");
4338       DataLayoutString = "e-m:o-p:32:32-i64:64-a:0:32-n32-S128";
4339     } else if (T.isOSBinFormatMachO())
4340       DataLayoutString =
4341           BigEndian
4342               ? "E-m:o-p:32:32-f64:32:64-v64:32:64-v128:32:128-a:0:32-n32-S32"
4343               : "e-m:o-p:32:32-f64:32:64-v64:32:64-v128:32:128-a:0:32-n32-S32";
4344     else
4345       DataLayoutString =
4346           BigEndian
4347               ? "E-m:e-p:32:32-f64:32:64-v64:32:64-v128:32:128-a:0:32-n32-S32"
4348               : "e-m:e-p:32:32-f64:32:64-v64:32:64-v128:32:128-a:0:32-n32-S32";
4349 
4350     // FIXME: Override "preferred align" for double and long long.
4351   }
4352 
setArchInfo()4353   void setArchInfo() {
4354     StringRef ArchName = getTriple().getArchName();
4355 
4356     ArchISA     = llvm::ARM::parseArchISA(ArchName);
4357     CPU         = llvm::ARM::getDefaultCPU(ArchName);
4358     unsigned AK = llvm::ARM::parseArch(ArchName);
4359     if (AK != llvm::ARM::AK_INVALID)
4360       ArchKind = AK;
4361     setArchInfo(ArchKind);
4362   }
4363 
setArchInfo(unsigned Kind)4364   void setArchInfo(unsigned Kind) {
4365     StringRef SubArch;
4366 
4367     // cache TargetParser info
4368     ArchKind    = Kind;
4369     SubArch     = llvm::ARM::getSubArch(ArchKind);
4370     ArchProfile = llvm::ARM::parseArchProfile(SubArch);
4371     ArchVersion = llvm::ARM::parseArchVersion(SubArch);
4372 
4373     // cache CPU related strings
4374     CPUAttr    = getCPUAttr();
4375     CPUProfile = getCPUProfile();
4376   }
4377 
setAtomic()4378   void setAtomic() {
4379     // when triple does not specify a sub arch,
4380     // then we are not using inline atomics
4381     bool ShouldUseInlineAtomic =
4382                    (ArchISA == llvm::ARM::IK_ARM   && ArchVersion >= 6) ||
4383                    (ArchISA == llvm::ARM::IK_THUMB && ArchVersion >= 7);
4384     // Cortex M does not support 8 byte atomics, while general Thumb2 does.
4385     if (ArchProfile == llvm::ARM::PK_M) {
4386       MaxAtomicPromoteWidth = 32;
4387       if (ShouldUseInlineAtomic)
4388         MaxAtomicInlineWidth = 32;
4389     }
4390     else {
4391       MaxAtomicPromoteWidth = 64;
4392       if (ShouldUseInlineAtomic)
4393         MaxAtomicInlineWidth = 64;
4394     }
4395   }
4396 
isThumb() const4397   bool isThumb() const {
4398     return (ArchISA == llvm::ARM::IK_THUMB);
4399   }
4400 
supportsThumb() const4401   bool supportsThumb() const {
4402     return CPUAttr.count('T') || ArchVersion >= 6;
4403   }
4404 
supportsThumb2() const4405   bool supportsThumb2() const {
4406     return CPUAttr.equals("6T2") || ArchVersion >= 7;
4407   }
4408 
getCPUAttr() const4409   StringRef getCPUAttr() const {
4410     // For most sub-arches, the build attribute CPU name is enough.
4411     // For Cortex variants, it's slightly different.
4412     switch(ArchKind) {
4413     default:
4414       return llvm::ARM::getCPUAttr(ArchKind);
4415     case llvm::ARM::AK_ARMV6M:
4416       return "6M";
4417     case llvm::ARM::AK_ARMV7S:
4418       return "7S";
4419     case llvm::ARM::AK_ARMV7A:
4420       return "7A";
4421     case llvm::ARM::AK_ARMV7R:
4422       return "7R";
4423     case llvm::ARM::AK_ARMV7M:
4424       return "7M";
4425     case llvm::ARM::AK_ARMV7EM:
4426       return "7EM";
4427     case llvm::ARM::AK_ARMV8A:
4428       return "8A";
4429     case llvm::ARM::AK_ARMV8_1A:
4430       return "8_1A";
4431     }
4432   }
4433 
getCPUProfile() const4434   StringRef getCPUProfile() const {
4435     switch(ArchProfile) {
4436     case llvm::ARM::PK_A:
4437       return "A";
4438     case llvm::ARM::PK_R:
4439       return "R";
4440     case llvm::ARM::PK_M:
4441       return "M";
4442     default:
4443       return "";
4444     }
4445   }
4446 
4447 public:
ARMTargetInfo(const llvm::Triple & Triple,bool IsBigEndian)4448   ARMTargetInfo(const llvm::Triple &Triple, bool IsBigEndian)
4449       : TargetInfo(Triple), FPMath(FP_Default),
4450         IsAAPCS(true), LDREX(0), HW_FP(0) {
4451     BigEndian = IsBigEndian;
4452 
4453     switch (getTriple().getOS()) {
4454     case llvm::Triple::NetBSD:
4455       PtrDiffType = SignedLong;
4456       break;
4457     default:
4458       PtrDiffType = SignedInt;
4459       break;
4460     }
4461 
4462     // Cache arch related info.
4463     setArchInfo();
4464 
4465     // {} in inline assembly are neon specifiers, not assembly variant
4466     // specifiers.
4467     NoAsmVariants = true;
4468 
4469     // FIXME: This duplicates code from the driver that sets the -target-abi
4470     // option - this code is used if -target-abi isn't passed and should
4471     // be unified in some way.
4472     if (Triple.isOSBinFormatMachO()) {
4473       // The backend is hardwired to assume AAPCS for M-class processors, ensure
4474       // the frontend matches that.
4475       if (Triple.getEnvironment() == llvm::Triple::EABI ||
4476           Triple.getOS() == llvm::Triple::UnknownOS ||
4477           StringRef(CPU).startswith("cortex-m")) {
4478         setABI("aapcs");
4479       } else if (Triple.isWatchOS()) {
4480         setABI("aapcs16");
4481       } else {
4482         setABI("apcs-gnu");
4483       }
4484     } else if (Triple.isOSWindows()) {
4485       // FIXME: this is invalid for WindowsCE
4486       setABI("aapcs");
4487     } else {
4488       // Select the default based on the platform.
4489       switch (Triple.getEnvironment()) {
4490       case llvm::Triple::Android:
4491       case llvm::Triple::GNUEABI:
4492       case llvm::Triple::GNUEABIHF:
4493         setABI("aapcs-linux");
4494         break;
4495       case llvm::Triple::EABIHF:
4496       case llvm::Triple::EABI:
4497         setABI("aapcs");
4498         break;
4499       case llvm::Triple::GNU:
4500         setABI("apcs-gnu");
4501       break;
4502       default:
4503         if (Triple.getOS() == llvm::Triple::NetBSD)
4504           setABI("apcs-gnu");
4505         else
4506           setABI("aapcs");
4507         break;
4508       }
4509     }
4510 
4511     // ARM targets default to using the ARM C++ ABI.
4512     TheCXXABI.set(TargetCXXABI::GenericARM);
4513 
4514     // ARM has atomics up to 8 bytes
4515     setAtomic();
4516 
4517     // Do force alignment of members that follow zero length bitfields.  If
4518     // the alignment of the zero-length bitfield is greater than the member
4519     // that follows it, `bar', `bar' will be aligned as the  type of the
4520     // zero length bitfield.
4521     UseZeroLengthBitfieldAlignment = true;
4522   }
4523 
getABI() const4524   StringRef getABI() const override { return ABI; }
4525 
setABI(const std::string & Name)4526   bool setABI(const std::string &Name) override {
4527     ABI = Name;
4528 
4529     // The defaults (above) are for AAPCS, check if we need to change them.
4530     //
4531     // FIXME: We need support for -meabi... we could just mangle it into the
4532     // name.
4533     if (Name == "apcs-gnu" || Name == "aapcs16") {
4534       setABIAPCS(Name == "aapcs16");
4535       return true;
4536     }
4537     if (Name == "aapcs" || Name == "aapcs-vfp" || Name == "aapcs-linux") {
4538       setABIAAPCS();
4539       return true;
4540     }
4541     return false;
4542   }
4543 
4544   // FIXME: This should be based on Arch attributes, not CPU names.
4545   bool
initFeatureMap(llvm::StringMap<bool> & Features,DiagnosticsEngine & Diags,StringRef CPU,const std::vector<std::string> & FeaturesVec) const4546   initFeatureMap(llvm::StringMap<bool> &Features, DiagnosticsEngine &Diags,
4547                  StringRef CPU,
4548                  const std::vector<std::string> &FeaturesVec) const override {
4549 
4550     std::vector<const char*> TargetFeatures;
4551     unsigned Arch = llvm::ARM::parseArch(getTriple().getArchName());
4552 
4553     // get default FPU features
4554     unsigned FPUKind = llvm::ARM::getDefaultFPU(CPU, Arch);
4555     llvm::ARM::getFPUFeatures(FPUKind, TargetFeatures);
4556 
4557     // get default Extension features
4558     unsigned Extensions = llvm::ARM::getDefaultExtensions(CPU, Arch);
4559     llvm::ARM::getExtensionFeatures(Extensions, TargetFeatures);
4560 
4561     for (const char *Feature : TargetFeatures)
4562       if (Feature[0] == '+')
4563         Features[Feature+1] = true;
4564 
4565     return TargetInfo::initFeatureMap(Features, Diags, CPU, FeaturesVec);
4566   }
4567 
handleTargetFeatures(std::vector<std::string> & Features,DiagnosticsEngine & Diags)4568   bool handleTargetFeatures(std::vector<std::string> &Features,
4569                             DiagnosticsEngine &Diags) override {
4570     FPU = 0;
4571     CRC = 0;
4572     Crypto = 0;
4573     DSP = 0;
4574     Unaligned = 1;
4575     SoftFloat = SoftFloatABI = false;
4576     HWDiv = 0;
4577 
4578     // This does not diagnose illegal cases like having both
4579     // "+vfpv2" and "+vfpv3" or having "+neon" and "+fp-only-sp".
4580     uint32_t HW_FP_remove = 0;
4581     for (const auto &Feature : Features) {
4582       if (Feature == "+soft-float") {
4583         SoftFloat = true;
4584       } else if (Feature == "+soft-float-abi") {
4585         SoftFloatABI = true;
4586       } else if (Feature == "+vfp2") {
4587         FPU |= VFP2FPU;
4588         HW_FP |= HW_FP_SP | HW_FP_DP;
4589       } else if (Feature == "+vfp3") {
4590         FPU |= VFP3FPU;
4591         HW_FP |= HW_FP_SP | HW_FP_DP;
4592       } else if (Feature == "+vfp4") {
4593         FPU |= VFP4FPU;
4594         HW_FP |= HW_FP_SP | HW_FP_DP | HW_FP_HP;
4595       } else if (Feature == "+fp-armv8") {
4596         FPU |= FPARMV8;
4597         HW_FP |= HW_FP_SP | HW_FP_DP | HW_FP_HP;
4598       } else if (Feature == "+neon") {
4599         FPU |= NeonFPU;
4600         HW_FP |= HW_FP_SP | HW_FP_DP;
4601       } else if (Feature == "+long64") {
4602         LongWidth = LongAlign = 64;  // RenderScript uses a 64-bit long type
4603       } else if (Feature == "+hwdiv") {
4604         HWDiv |= HWDivThumb;
4605       } else if (Feature == "+hwdiv-arm") {
4606         HWDiv |= HWDivARM;
4607       } else if (Feature == "+crc") {
4608         CRC = 1;
4609       } else if (Feature == "+crypto") {
4610         Crypto = 1;
4611       } else if (Feature == "+dsp") {
4612         DSP = 1;
4613       } else if (Feature == "+fp-only-sp") {
4614         HW_FP_remove |= HW_FP_DP;
4615       } else if (Feature == "+strict-align") {
4616         Unaligned = 0;
4617       } else if (Feature == "+fp16") {
4618         HW_FP |= HW_FP_HP;
4619       }
4620     }
4621     HW_FP &= ~HW_FP_remove;
4622 
4623     switch (ArchVersion) {
4624     case 6:
4625       if (ArchProfile == llvm::ARM::PK_M)
4626         LDREX = 0;
4627       else if (ArchKind == llvm::ARM::AK_ARMV6K)
4628         LDREX = LDREX_D | LDREX_W | LDREX_H | LDREX_B ;
4629       else
4630         LDREX = LDREX_W;
4631       break;
4632     case 7:
4633       if (ArchProfile == llvm::ARM::PK_M)
4634         LDREX = LDREX_W | LDREX_H | LDREX_B ;
4635       else
4636         LDREX = LDREX_D | LDREX_W | LDREX_H | LDREX_B ;
4637       break;
4638     case 8:
4639       LDREX = LDREX_D | LDREX_W | LDREX_H | LDREX_B ;
4640     }
4641 
4642     if (!(FPU & NeonFPU) && FPMath == FP_Neon) {
4643       Diags.Report(diag::err_target_unsupported_fpmath) << "neon";
4644       return false;
4645     }
4646 
4647     if (FPMath == FP_Neon)
4648       Features.push_back("+neonfp");
4649     else if (FPMath == FP_VFP)
4650       Features.push_back("-neonfp");
4651 
4652     // Remove front-end specific options which the backend handles differently.
4653     auto Feature =
4654         std::find(Features.begin(), Features.end(), "+soft-float-abi");
4655     if (Feature != Features.end())
4656       Features.erase(Feature);
4657 
4658     return true;
4659   }
4660 
hasFeature(StringRef Feature) const4661   bool hasFeature(StringRef Feature) const override {
4662     return llvm::StringSwitch<bool>(Feature)
4663         .Case("arm", true)
4664         .Case("aarch32", true)
4665         .Case("softfloat", SoftFloat)
4666         .Case("thumb", isThumb())
4667         .Case("neon", (FPU & NeonFPU) && !SoftFloat)
4668         .Case("hwdiv", HWDiv & HWDivThumb)
4669         .Case("hwdiv-arm", HWDiv & HWDivARM)
4670         .Default(false);
4671   }
4672 
setCPU(const std::string & Name)4673   bool setCPU(const std::string &Name) override {
4674     if (Name != "generic")
4675       setArchInfo(llvm::ARM::parseCPUArch(Name));
4676 
4677     if (ArchKind == llvm::ARM::AK_INVALID)
4678       return false;
4679     setAtomic();
4680     CPU = Name;
4681     return true;
4682   }
4683 
4684   bool setFPMath(StringRef Name) override;
4685 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const4686   void getTargetDefines(const LangOptions &Opts,
4687                         MacroBuilder &Builder) const override {
4688     // Target identification.
4689     Builder.defineMacro("__arm");
4690     Builder.defineMacro("__arm__");
4691 
4692     // Target properties.
4693     Builder.defineMacro("__REGISTER_PREFIX__", "");
4694 
4695     // Unfortunately, __ARM_ARCH_7K__ is now more of an ABI descriptor. The CPU
4696     // happens to be Cortex-A7 though, so it should still get __ARM_ARCH_7A__.
4697     if (getTriple().isWatchOS())
4698       Builder.defineMacro("__ARM_ARCH_7K__", "2");
4699 
4700     if (!CPUAttr.empty())
4701       Builder.defineMacro("__ARM_ARCH_" + CPUAttr + "__");
4702 
4703     // ACLE 6.4.1 ARM/Thumb instruction set architecture
4704     // __ARM_ARCH is defined as an integer value indicating the current ARM ISA
4705     Builder.defineMacro("__ARM_ARCH", llvm::utostr(ArchVersion));
4706 
4707     if (ArchVersion >= 8) {
4708       // ACLE 6.5.7 Crypto Extension
4709       if (Crypto)
4710         Builder.defineMacro("__ARM_FEATURE_CRYPTO", "1");
4711       // ACLE 6.5.8 CRC32 Extension
4712       if (CRC)
4713         Builder.defineMacro("__ARM_FEATURE_CRC32", "1");
4714       // ACLE 6.5.10 Numeric Maximum and Minimum
4715       Builder.defineMacro("__ARM_FEATURE_NUMERIC_MAXMIN", "1");
4716       // ACLE 6.5.9 Directed Rounding
4717       Builder.defineMacro("__ARM_FEATURE_DIRECTED_ROUNDING", "1");
4718     }
4719 
4720     // __ARM_ARCH_ISA_ARM is defined to 1 if the core supports the ARM ISA.  It
4721     // is not defined for the M-profile.
4722     // NOTE that the deffault profile is assumed to be 'A'
4723     if (CPUProfile.empty() || CPUProfile != "M")
4724       Builder.defineMacro("__ARM_ARCH_ISA_ARM", "1");
4725 
4726     // __ARM_ARCH_ISA_THUMB is defined to 1 if the core supporst the original
4727     // Thumb ISA (including v6-M).  It is set to 2 if the core supports the
4728     // Thumb-2 ISA as found in the v6T2 architecture and all v7 architecture.
4729     if (supportsThumb2())
4730       Builder.defineMacro("__ARM_ARCH_ISA_THUMB", "2");
4731     else if (supportsThumb())
4732       Builder.defineMacro("__ARM_ARCH_ISA_THUMB", "1");
4733 
4734     // __ARM_32BIT_STATE is defined to 1 if code is being generated for a 32-bit
4735     // instruction set such as ARM or Thumb.
4736     Builder.defineMacro("__ARM_32BIT_STATE", "1");
4737 
4738     // ACLE 6.4.2 Architectural Profile (A, R, M or pre-Cortex)
4739 
4740     // __ARM_ARCH_PROFILE is defined as 'A', 'R', 'M' or 'S', or unset.
4741     if (!CPUProfile.empty())
4742       Builder.defineMacro("__ARM_ARCH_PROFILE", "'" + CPUProfile + "'");
4743 
4744     // ACLE 6.4.3 Unaligned access supported in hardware
4745     if (Unaligned)
4746       Builder.defineMacro("__ARM_FEATURE_UNALIGNED", "1");
4747 
4748     // ACLE 6.4.4 LDREX/STREX
4749     if (LDREX)
4750       Builder.defineMacro("__ARM_FEATURE_LDREX", "0x" + llvm::utohexstr(LDREX));
4751 
4752     // ACLE 6.4.5 CLZ
4753     if (ArchVersion == 5 ||
4754        (ArchVersion == 6 && CPUProfile != "M") ||
4755         ArchVersion >  6)
4756       Builder.defineMacro("__ARM_FEATURE_CLZ", "1");
4757 
4758     // ACLE 6.5.1 Hardware Floating Point
4759     if (HW_FP)
4760       Builder.defineMacro("__ARM_FP", "0x" + llvm::utohexstr(HW_FP));
4761 
4762     // ACLE predefines.
4763     Builder.defineMacro("__ARM_ACLE", "200");
4764 
4765     // FP16 support (we currently only support IEEE format).
4766     Builder.defineMacro("__ARM_FP16_FORMAT_IEEE", "1");
4767     Builder.defineMacro("__ARM_FP16_ARGS", "1");
4768 
4769     // ACLE 6.5.3 Fused multiply-accumulate (FMA)
4770     if (ArchVersion >= 7 && (CPUProfile != "M" || CPUAttr == "7EM"))
4771       Builder.defineMacro("__ARM_FEATURE_FMA", "1");
4772 
4773     // Subtarget options.
4774 
4775     // FIXME: It's more complicated than this and we don't really support
4776     // interworking.
4777     // Windows on ARM does not "support" interworking
4778     if (5 <= ArchVersion && ArchVersion <= 8 && !getTriple().isOSWindows())
4779       Builder.defineMacro("__THUMB_INTERWORK__");
4780 
4781     if (ABI == "aapcs" || ABI == "aapcs-linux" || ABI == "aapcs-vfp") {
4782       // Embedded targets on Darwin follow AAPCS, but not EABI.
4783       // Windows on ARM follows AAPCS VFP, but does not conform to EABI.
4784       if (!getTriple().isOSDarwin() && !getTriple().isOSWindows())
4785         Builder.defineMacro("__ARM_EABI__");
4786       Builder.defineMacro("__ARM_PCS", "1");
4787 
4788       if ((!SoftFloat && !SoftFloatABI) || ABI == "aapcs-vfp")
4789         Builder.defineMacro("__ARM_PCS_VFP", "1");
4790     }
4791 
4792     if (SoftFloat)
4793       Builder.defineMacro("__SOFTFP__");
4794 
4795     if (CPU == "xscale")
4796       Builder.defineMacro("__XSCALE__");
4797 
4798     if (isThumb()) {
4799       Builder.defineMacro("__THUMBEL__");
4800       Builder.defineMacro("__thumb__");
4801       if (supportsThumb2())
4802         Builder.defineMacro("__thumb2__");
4803     }
4804 
4805     // ACLE 6.4.9 32-bit SIMD instructions
4806     if (ArchVersion >= 6 && (CPUProfile != "M" || CPUAttr == "7EM"))
4807       Builder.defineMacro("__ARM_FEATURE_SIMD32", "1");
4808 
4809     // ACLE 6.4.10 Hardware Integer Divide
4810     if (((HWDiv & HWDivThumb) && isThumb()) ||
4811         ((HWDiv & HWDivARM) && !isThumb())) {
4812       Builder.defineMacro("__ARM_FEATURE_IDIV", "1");
4813       Builder.defineMacro("__ARM_ARCH_EXT_IDIV__", "1");
4814     }
4815 
4816     // Note, this is always on in gcc, even though it doesn't make sense.
4817     Builder.defineMacro("__APCS_32__");
4818 
4819     if (FPUModeIsVFP((FPUMode) FPU)) {
4820       Builder.defineMacro("__VFP_FP__");
4821       if (FPU & VFP2FPU)
4822         Builder.defineMacro("__ARM_VFPV2__");
4823       if (FPU & VFP3FPU)
4824         Builder.defineMacro("__ARM_VFPV3__");
4825       if (FPU & VFP4FPU)
4826         Builder.defineMacro("__ARM_VFPV4__");
4827     }
4828 
4829     // This only gets set when Neon instructions are actually available, unlike
4830     // the VFP define, hence the soft float and arch check. This is subtly
4831     // different from gcc, we follow the intent which was that it should be set
4832     // when Neon instructions are actually available.
4833     if ((FPU & NeonFPU) && !SoftFloat && ArchVersion >= 7) {
4834       Builder.defineMacro("__ARM_NEON", "1");
4835       Builder.defineMacro("__ARM_NEON__");
4836       // current AArch32 NEON implementations do not support double-precision
4837       // floating-point even when it is present in VFP.
4838       Builder.defineMacro("__ARM_NEON_FP",
4839                           "0x" + llvm::utohexstr(HW_FP & ~HW_FP_DP));
4840     }
4841 
4842     Builder.defineMacro("__ARM_SIZEOF_WCHAR_T",
4843                         Opts.ShortWChar ? "2" : "4");
4844 
4845     Builder.defineMacro("__ARM_SIZEOF_MINIMAL_ENUM",
4846                         Opts.ShortEnums ? "1" : "4");
4847 
4848     if (ArchVersion >= 6 && CPUAttr != "6M") {
4849       Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_1");
4850       Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_2");
4851       Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4");
4852       Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8");
4853     }
4854 
4855     // ACLE 6.4.7 DSP instructions
4856     if (DSP) {
4857       Builder.defineMacro("__ARM_FEATURE_DSP", "1");
4858     }
4859 
4860     // ACLE 6.4.8 Saturation instructions
4861     bool SAT = false;
4862     if ((ArchVersion == 6 && CPUProfile != "M") || ArchVersion > 6 ) {
4863       Builder.defineMacro("__ARM_FEATURE_SAT", "1");
4864       SAT = true;
4865     }
4866 
4867     // ACLE 6.4.6 Q (saturation) flag
4868     if (DSP || SAT)
4869       Builder.defineMacro("__ARM_FEATURE_QBIT", "1");
4870 
4871     if (Opts.UnsafeFPMath)
4872       Builder.defineMacro("__ARM_FP_FAST", "1");
4873 
4874     if (ArchKind == llvm::ARM::AK_ARMV8_1A)
4875       Builder.defineMacro("__ARM_FEATURE_QRDMX", "1");
4876   }
4877 
getTargetBuiltins() const4878   ArrayRef<Builtin::Info> getTargetBuiltins() const override {
4879     return llvm::makeArrayRef(BuiltinInfo,
4880                              clang::ARM::LastTSBuiltin-Builtin::FirstTSBuiltin);
4881   }
isCLZForZeroUndef() const4882   bool isCLZForZeroUndef() const override { return false; }
getBuiltinVaListKind() const4883   BuiltinVaListKind getBuiltinVaListKind() const override {
4884     return IsAAPCS
4885                ? AAPCSABIBuiltinVaList
4886                : (getTriple().isWatchOS() ? TargetInfo::CharPtrBuiltinVaList
4887                                           : TargetInfo::VoidPtrBuiltinVaList);
4888   }
4889   ArrayRef<const char *> getGCCRegNames() const override;
4890   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override;
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & Info) const4891   bool validateAsmConstraint(const char *&Name,
4892                              TargetInfo::ConstraintInfo &Info) const override {
4893     switch (*Name) {
4894     default: break;
4895     case 'l': // r0-r7
4896     case 'h': // r8-r15
4897     case 'w': // VFP Floating point register single precision
4898     case 'P': // VFP Floating point register double precision
4899       Info.setAllowsRegister();
4900       return true;
4901     case 'I':
4902     case 'J':
4903     case 'K':
4904     case 'L':
4905     case 'M':
4906       // FIXME
4907       return true;
4908     case 'Q': // A memory address that is a single base register.
4909       Info.setAllowsMemory();
4910       return true;
4911     case 'U': // a memory reference...
4912       switch (Name[1]) {
4913       case 'q': // ...ARMV4 ldrsb
4914       case 'v': // ...VFP load/store (reg+constant offset)
4915       case 'y': // ...iWMMXt load/store
4916       case 't': // address valid for load/store opaque types wider
4917                 // than 128-bits
4918       case 'n': // valid address for Neon doubleword vector load/store
4919       case 'm': // valid address for Neon element and structure load/store
4920       case 's': // valid address for non-offset loads/stores of quad-word
4921                 // values in four ARM registers
4922         Info.setAllowsMemory();
4923         Name++;
4924         return true;
4925       }
4926     }
4927     return false;
4928   }
convertConstraint(const char * & Constraint) const4929   std::string convertConstraint(const char *&Constraint) const override {
4930     std::string R;
4931     switch (*Constraint) {
4932     case 'U':   // Two-character constraint; add "^" hint for later parsing.
4933       R = std::string("^") + std::string(Constraint, 2);
4934       Constraint++;
4935       break;
4936     case 'p': // 'p' should be translated to 'r' by default.
4937       R = std::string("r");
4938       break;
4939     default:
4940       return std::string(1, *Constraint);
4941     }
4942     return R;
4943   }
4944   bool
validateConstraintModifier(StringRef Constraint,char Modifier,unsigned Size,std::string & SuggestedModifier) const4945   validateConstraintModifier(StringRef Constraint, char Modifier, unsigned Size,
4946                              std::string &SuggestedModifier) const override {
4947     bool isOutput = (Constraint[0] == '=');
4948     bool isInOut = (Constraint[0] == '+');
4949 
4950     // Strip off constraint modifiers.
4951     while (Constraint[0] == '=' ||
4952            Constraint[0] == '+' ||
4953            Constraint[0] == '&')
4954       Constraint = Constraint.substr(1);
4955 
4956     switch (Constraint[0]) {
4957     default: break;
4958     case 'r': {
4959       switch (Modifier) {
4960       default:
4961         return (isInOut || isOutput || Size <= 64);
4962       case 'q':
4963         // A register of size 32 cannot fit a vector type.
4964         return false;
4965       }
4966     }
4967     }
4968 
4969     return true;
4970   }
getClobbers() const4971   const char *getClobbers() const override {
4972     // FIXME: Is this really right?
4973     return "";
4974   }
4975 
checkCallingConvention(CallingConv CC) const4976   CallingConvCheckResult checkCallingConvention(CallingConv CC) const override {
4977     return (CC == CC_AAPCS || CC == CC_AAPCS_VFP) ? CCCR_OK : CCCR_Warning;
4978   }
4979 
getEHDataRegisterNumber(unsigned RegNo) const4980   int getEHDataRegisterNumber(unsigned RegNo) const override {
4981     if (RegNo == 0) return 0;
4982     if (RegNo == 1) return 1;
4983     return -1;
4984   }
4985 
hasSjLjLowering() const4986   bool hasSjLjLowering() const override {
4987     return true;
4988   }
4989 };
4990 
setFPMath(StringRef Name)4991 bool ARMTargetInfo::setFPMath(StringRef Name) {
4992   if (Name == "neon") {
4993     FPMath = FP_Neon;
4994     return true;
4995   } else if (Name == "vfp" || Name == "vfp2" || Name == "vfp3" ||
4996              Name == "vfp4") {
4997     FPMath = FP_VFP;
4998     return true;
4999   }
5000   return false;
5001 }
5002 
5003 const char * const ARMTargetInfo::GCCRegNames[] = {
5004   // Integer registers
5005   "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7",
5006   "r8", "r9", "r10", "r11", "r12", "sp", "lr", "pc",
5007 
5008   // Float registers
5009   "s0", "s1", "s2", "s3", "s4", "s5", "s6", "s7",
5010   "s8", "s9", "s10", "s11", "s12", "s13", "s14", "s15",
5011   "s16", "s17", "s18", "s19", "s20", "s21", "s22", "s23",
5012   "s24", "s25", "s26", "s27", "s28", "s29", "s30", "s31",
5013 
5014   // Double registers
5015   "d0", "d1", "d2", "d3", "d4", "d5", "d6", "d7",
5016   "d8", "d9", "d10", "d11", "d12", "d13", "d14", "d15",
5017   "d16", "d17", "d18", "d19", "d20", "d21", "d22", "d23",
5018   "d24", "d25", "d26", "d27", "d28", "d29", "d30", "d31",
5019 
5020   // Quad registers
5021   "q0", "q1", "q2", "q3", "q4", "q5", "q6", "q7",
5022   "q8", "q9", "q10", "q11", "q12", "q13", "q14", "q15"
5023 };
5024 
getGCCRegNames() const5025 ArrayRef<const char *> ARMTargetInfo::getGCCRegNames() const {
5026   return llvm::makeArrayRef(GCCRegNames);
5027 }
5028 
5029 const TargetInfo::GCCRegAlias ARMTargetInfo::GCCRegAliases[] = {
5030   { { "a1" }, "r0" },
5031   { { "a2" }, "r1" },
5032   { { "a3" }, "r2" },
5033   { { "a4" }, "r3" },
5034   { { "v1" }, "r4" },
5035   { { "v2" }, "r5" },
5036   { { "v3" }, "r6" },
5037   { { "v4" }, "r7" },
5038   { { "v5" }, "r8" },
5039   { { "v6", "rfp" }, "r9" },
5040   { { "sl" }, "r10" },
5041   { { "fp" }, "r11" },
5042   { { "ip" }, "r12" },
5043   { { "r13" }, "sp" },
5044   { { "r14" }, "lr" },
5045   { { "r15" }, "pc" },
5046   // The S, D and Q registers overlap, but aren't really aliases; we
5047   // don't want to substitute one of these for a different-sized one.
5048 };
5049 
getGCCRegAliases() const5050 ArrayRef<TargetInfo::GCCRegAlias> ARMTargetInfo::getGCCRegAliases() const {
5051   return llvm::makeArrayRef(GCCRegAliases);
5052 }
5053 
5054 const Builtin::Info ARMTargetInfo::BuiltinInfo[] = {
5055 #define BUILTIN(ID, TYPE, ATTRS) \
5056   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr },
5057 #define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) \
5058   { #ID, TYPE, ATTRS, HEADER, ALL_LANGUAGES, nullptr },
5059 #include "clang/Basic/BuiltinsNEON.def"
5060 
5061 #define BUILTIN(ID, TYPE, ATTRS) \
5062   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr },
5063 #define LANGBUILTIN(ID, TYPE, ATTRS, LANG) \
5064   { #ID, TYPE, ATTRS, nullptr, LANG, nullptr },
5065 #define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) \
5066   { #ID, TYPE, ATTRS, HEADER, ALL_LANGUAGES, nullptr },
5067 #include "clang/Basic/BuiltinsARM.def"
5068 };
5069 
5070 class ARMleTargetInfo : public ARMTargetInfo {
5071 public:
ARMleTargetInfo(const llvm::Triple & Triple)5072   ARMleTargetInfo(const llvm::Triple &Triple)
5073     : ARMTargetInfo(Triple, false) { }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const5074   void getTargetDefines(const LangOptions &Opts,
5075                         MacroBuilder &Builder) const override {
5076     Builder.defineMacro("__ARMEL__");
5077     ARMTargetInfo::getTargetDefines(Opts, Builder);
5078   }
5079 };
5080 
5081 class ARMbeTargetInfo : public ARMTargetInfo {
5082 public:
ARMbeTargetInfo(const llvm::Triple & Triple)5083   ARMbeTargetInfo(const llvm::Triple &Triple)
5084     : ARMTargetInfo(Triple, true) { }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const5085   void getTargetDefines(const LangOptions &Opts,
5086                         MacroBuilder &Builder) const override {
5087     Builder.defineMacro("__ARMEB__");
5088     Builder.defineMacro("__ARM_BIG_ENDIAN");
5089     ARMTargetInfo::getTargetDefines(Opts, Builder);
5090   }
5091 };
5092 
5093 class WindowsARMTargetInfo : public WindowsTargetInfo<ARMleTargetInfo> {
5094   const llvm::Triple Triple;
5095 public:
WindowsARMTargetInfo(const llvm::Triple & Triple)5096   WindowsARMTargetInfo(const llvm::Triple &Triple)
5097     : WindowsTargetInfo<ARMleTargetInfo>(Triple), Triple(Triple) {
5098     TLSSupported = false;
5099     WCharType = UnsignedShort;
5100     SizeType = UnsignedInt;
5101     UserLabelPrefix = "";
5102   }
getVisualStudioDefines(const LangOptions & Opts,MacroBuilder & Builder) const5103   void getVisualStudioDefines(const LangOptions &Opts,
5104                               MacroBuilder &Builder) const {
5105     WindowsTargetInfo<ARMleTargetInfo>::getVisualStudioDefines(Opts, Builder);
5106 
5107     // FIXME: this is invalid for WindowsCE
5108     Builder.defineMacro("_M_ARM_NT", "1");
5109     Builder.defineMacro("_M_ARMT", "_M_ARM");
5110     Builder.defineMacro("_M_THUMB", "_M_ARM");
5111 
5112     assert((Triple.getArch() == llvm::Triple::arm ||
5113             Triple.getArch() == llvm::Triple::thumb) &&
5114            "invalid architecture for Windows ARM target info");
5115     unsigned Offset = Triple.getArch() == llvm::Triple::arm ? 4 : 6;
5116     Builder.defineMacro("_M_ARM", Triple.getArchName().substr(Offset));
5117 
5118     // TODO map the complete set of values
5119     // 31: VFPv3 40: VFPv4
5120     Builder.defineMacro("_M_ARM_FP", "31");
5121   }
getBuiltinVaListKind() const5122   BuiltinVaListKind getBuiltinVaListKind() const override {
5123     return TargetInfo::CharPtrBuiltinVaList;
5124   }
checkCallingConvention(CallingConv CC) const5125   CallingConvCheckResult checkCallingConvention(CallingConv CC) const override {
5126     switch (CC) {
5127     case CC_X86StdCall:
5128     case CC_X86ThisCall:
5129     case CC_X86FastCall:
5130     case CC_X86VectorCall:
5131       return CCCR_Ignore;
5132     case CC_C:
5133       return CCCR_OK;
5134     default:
5135       return CCCR_Warning;
5136     }
5137   }
5138 };
5139 
5140 // Windows ARM + Itanium C++ ABI Target
5141 class ItaniumWindowsARMleTargetInfo : public WindowsARMTargetInfo {
5142 public:
ItaniumWindowsARMleTargetInfo(const llvm::Triple & Triple)5143   ItaniumWindowsARMleTargetInfo(const llvm::Triple &Triple)
5144     : WindowsARMTargetInfo(Triple) {
5145     TheCXXABI.set(TargetCXXABI::GenericARM);
5146   }
5147 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const5148   void getTargetDefines(const LangOptions &Opts,
5149                         MacroBuilder &Builder) const override {
5150     WindowsARMTargetInfo::getTargetDefines(Opts, Builder);
5151 
5152     if (Opts.MSVCCompat)
5153       WindowsARMTargetInfo::getVisualStudioDefines(Opts, Builder);
5154   }
5155 };
5156 
5157 // Windows ARM, MS (C++) ABI
5158 class MicrosoftARMleTargetInfo : public WindowsARMTargetInfo {
5159 public:
MicrosoftARMleTargetInfo(const llvm::Triple & Triple)5160   MicrosoftARMleTargetInfo(const llvm::Triple &Triple)
5161     : WindowsARMTargetInfo(Triple) {
5162     TheCXXABI.set(TargetCXXABI::Microsoft);
5163   }
5164 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const5165   void getTargetDefines(const LangOptions &Opts,
5166                         MacroBuilder &Builder) const override {
5167     WindowsARMTargetInfo::getTargetDefines(Opts, Builder);
5168     WindowsARMTargetInfo::getVisualStudioDefines(Opts, Builder);
5169   }
5170 };
5171 
5172 // ARM MinGW target
5173 class MinGWARMTargetInfo : public WindowsARMTargetInfo {
5174 public:
MinGWARMTargetInfo(const llvm::Triple & Triple)5175   MinGWARMTargetInfo(const llvm::Triple &Triple)
5176       : WindowsARMTargetInfo(Triple) {
5177     TheCXXABI.set(TargetCXXABI::GenericARM);
5178   }
5179 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const5180   void getTargetDefines(const LangOptions &Opts,
5181                         MacroBuilder &Builder) const override {
5182     WindowsARMTargetInfo::getTargetDefines(Opts, Builder);
5183     DefineStd(Builder, "WIN32", Opts);
5184     DefineStd(Builder, "WINNT", Opts);
5185     Builder.defineMacro("_ARM_");
5186     addMinGWDefines(Opts, Builder);
5187   }
5188 };
5189 
5190 // ARM Cygwin target
5191 class CygwinARMTargetInfo : public ARMleTargetInfo {
5192 public:
CygwinARMTargetInfo(const llvm::Triple & Triple)5193   CygwinARMTargetInfo(const llvm::Triple &Triple) : ARMleTargetInfo(Triple) {
5194     TLSSupported = false;
5195     WCharType = UnsignedShort;
5196     DoubleAlign = LongLongAlign = 64;
5197     DataLayoutString = "e-m:e-p:32:32-i64:64-v128:64:128-a:0:32-n32-S64";
5198   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const5199   void getTargetDefines(const LangOptions &Opts,
5200                         MacroBuilder &Builder) const override {
5201     ARMleTargetInfo::getTargetDefines(Opts, Builder);
5202     Builder.defineMacro("_ARM_");
5203     Builder.defineMacro("__CYGWIN__");
5204     Builder.defineMacro("__CYGWIN32__");
5205     DefineStd(Builder, "unix", Opts);
5206     if (Opts.CPlusPlus)
5207       Builder.defineMacro("_GNU_SOURCE");
5208   }
5209 };
5210 
5211 class DarwinARMTargetInfo :
5212   public DarwinTargetInfo<ARMleTargetInfo> {
5213 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const5214   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
5215                     MacroBuilder &Builder) const override {
5216     getDarwinDefines(Builder, Opts, Triple, PlatformName, PlatformMinVersion);
5217   }
5218 
5219 public:
DarwinARMTargetInfo(const llvm::Triple & Triple)5220   DarwinARMTargetInfo(const llvm::Triple &Triple)
5221       : DarwinTargetInfo<ARMleTargetInfo>(Triple) {
5222     HasAlignMac68kSupport = true;
5223     // iOS always has 64-bit atomic instructions.
5224     // FIXME: This should be based off of the target features in
5225     // ARMleTargetInfo.
5226     MaxAtomicInlineWidth = 64;
5227 
5228     if (Triple.isWatchOS()) {
5229       // Darwin on iOS uses a variant of the ARM C++ ABI.
5230       TheCXXABI.set(TargetCXXABI::WatchOS);
5231 
5232       // The 32-bit ABI is silent on what ptrdiff_t should be, but given that
5233       // size_t is long, it's a bit weird for it to be int.
5234       PtrDiffType = SignedLong;
5235 
5236       // BOOL should be a real boolean on the new ABI
5237       UseSignedCharForObjCBool = false;
5238     } else
5239       TheCXXABI.set(TargetCXXABI::iOS);
5240   }
5241 };
5242 
5243 class AArch64TargetInfo : public TargetInfo {
5244   virtual void setDataLayoutString() = 0;
5245   static const TargetInfo::GCCRegAlias GCCRegAliases[];
5246   static const char *const GCCRegNames[];
5247 
5248   enum FPUModeEnum {
5249     FPUMode,
5250     NeonMode
5251   };
5252 
5253   unsigned FPU;
5254   unsigned CRC;
5255   unsigned Crypto;
5256   unsigned Unaligned;
5257   unsigned V8_1A;
5258 
5259   static const Builtin::Info BuiltinInfo[];
5260 
5261   std::string ABI;
5262 
5263 public:
AArch64TargetInfo(const llvm::Triple & Triple)5264   AArch64TargetInfo(const llvm::Triple &Triple)
5265       : TargetInfo(Triple), ABI("aapcs") {
5266 
5267     if (getTriple().getOS() == llvm::Triple::NetBSD) {
5268       WCharType = SignedInt;
5269 
5270       // NetBSD apparently prefers consistency across ARM targets to consistency
5271       // across 64-bit targets.
5272       Int64Type = SignedLongLong;
5273       IntMaxType = SignedLongLong;
5274     } else {
5275       WCharType = UnsignedInt;
5276       Int64Type = SignedLong;
5277       IntMaxType = SignedLong;
5278     }
5279 
5280     LongWidth = LongAlign = PointerWidth = PointerAlign = 64;
5281     MaxVectorAlign = 128;
5282     MaxAtomicInlineWidth = 128;
5283     MaxAtomicPromoteWidth = 128;
5284 
5285     LongDoubleWidth = LongDoubleAlign = SuitableAlign = 128;
5286     LongDoubleFormat = &llvm::APFloat::IEEEquad;
5287 
5288     // {} in inline assembly are neon specifiers, not assembly variant
5289     // specifiers.
5290     NoAsmVariants = true;
5291 
5292     // AAPCS gives rules for bitfields. 7.1.7 says: "The container type
5293     // contributes to the alignment of the containing aggregate in the same way
5294     // a plain (non bit-field) member of that type would, without exception for
5295     // zero-sized or anonymous bit-fields."
5296     assert(UseBitFieldTypeAlignment && "bitfields affect type alignment");
5297     UseZeroLengthBitfieldAlignment = true;
5298 
5299     // AArch64 targets default to using the ARM C++ ABI.
5300     TheCXXABI.set(TargetCXXABI::GenericAArch64);
5301   }
5302 
getABI() const5303   StringRef getABI() const override { return ABI; }
setABI(const std::string & Name)5304   bool setABI(const std::string &Name) override {
5305     if (Name != "aapcs" && Name != "darwinpcs")
5306       return false;
5307 
5308     ABI = Name;
5309     return true;
5310   }
5311 
setCPU(const std::string & Name)5312   bool setCPU(const std::string &Name) override {
5313     bool CPUKnown = llvm::StringSwitch<bool>(Name)
5314                         .Case("generic", true)
5315                         .Cases("cortex-a53", "cortex-a57", "cortex-a72", "cortex-a35", true)
5316                         .Case("cyclone", true)
5317                         .Default(false);
5318     return CPUKnown;
5319   }
5320 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const5321   void getTargetDefines(const LangOptions &Opts,
5322                         MacroBuilder &Builder) const override {
5323     // Target identification.
5324     Builder.defineMacro("__aarch64__");
5325 
5326     // Target properties.
5327     Builder.defineMacro("_LP64");
5328     Builder.defineMacro("__LP64__");
5329 
5330     // ACLE predefines. Many can only have one possible value on v8 AArch64.
5331     Builder.defineMacro("__ARM_ACLE", "200");
5332     Builder.defineMacro("__ARM_ARCH", "8");
5333     Builder.defineMacro("__ARM_ARCH_PROFILE", "'A'");
5334 
5335     Builder.defineMacro("__ARM_64BIT_STATE", "1");
5336     Builder.defineMacro("__ARM_PCS_AAPCS64", "1");
5337     Builder.defineMacro("__ARM_ARCH_ISA_A64", "1");
5338 
5339     Builder.defineMacro("__ARM_FEATURE_CLZ", "1");
5340     Builder.defineMacro("__ARM_FEATURE_FMA", "1");
5341     Builder.defineMacro("__ARM_FEATURE_LDREX", "0xF");
5342     Builder.defineMacro("__ARM_FEATURE_IDIV", "1"); // As specified in ACLE
5343     Builder.defineMacro("__ARM_FEATURE_DIV");  // For backwards compatibility
5344     Builder.defineMacro("__ARM_FEATURE_NUMERIC_MAXMIN", "1");
5345     Builder.defineMacro("__ARM_FEATURE_DIRECTED_ROUNDING", "1");
5346 
5347     Builder.defineMacro("__ARM_ALIGN_MAX_STACK_PWR", "4");
5348 
5349     // 0xe implies support for half, single and double precision operations.
5350     Builder.defineMacro("__ARM_FP", "0xE");
5351 
5352     // PCS specifies this for SysV variants, which is all we support. Other ABIs
5353     // may choose __ARM_FP16_FORMAT_ALTERNATIVE.
5354     Builder.defineMacro("__ARM_FP16_FORMAT_IEEE", "1");
5355     Builder.defineMacro("__ARM_FP16_ARGS", "1");
5356 
5357     if (Opts.UnsafeFPMath)
5358       Builder.defineMacro("__ARM_FP_FAST", "1");
5359 
5360     Builder.defineMacro("__ARM_SIZEOF_WCHAR_T", Opts.ShortWChar ? "2" : "4");
5361 
5362     Builder.defineMacro("__ARM_SIZEOF_MINIMAL_ENUM",
5363                         Opts.ShortEnums ? "1" : "4");
5364 
5365     if (FPU == NeonMode) {
5366       Builder.defineMacro("__ARM_NEON", "1");
5367       // 64-bit NEON supports half, single and double precision operations.
5368       Builder.defineMacro("__ARM_NEON_FP", "0xE");
5369     }
5370 
5371     if (CRC)
5372       Builder.defineMacro("__ARM_FEATURE_CRC32", "1");
5373 
5374     if (Crypto)
5375       Builder.defineMacro("__ARM_FEATURE_CRYPTO", "1");
5376 
5377     if (Unaligned)
5378       Builder.defineMacro("__ARM_FEATURE_UNALIGNED", "1");
5379 
5380     if (V8_1A)
5381       Builder.defineMacro("__ARM_FEATURE_QRDMX", "1");
5382 
5383     // All of the __sync_(bool|val)_compare_and_swap_(1|2|4|8) builtins work.
5384     Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_1");
5385     Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_2");
5386     Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4");
5387     Builder.defineMacro("__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8");
5388   }
5389 
getTargetBuiltins() const5390   ArrayRef<Builtin::Info> getTargetBuiltins() const override {
5391     return llvm::makeArrayRef(BuiltinInfo,
5392                        clang::AArch64::LastTSBuiltin - Builtin::FirstTSBuiltin);
5393   }
5394 
hasFeature(StringRef Feature) const5395   bool hasFeature(StringRef Feature) const override {
5396     return Feature == "aarch64" ||
5397       Feature == "arm64" ||
5398       Feature == "arm" ||
5399       (Feature == "neon" && FPU == NeonMode);
5400   }
5401 
handleTargetFeatures(std::vector<std::string> & Features,DiagnosticsEngine & Diags)5402   bool handleTargetFeatures(std::vector<std::string> &Features,
5403                             DiagnosticsEngine &Diags) override {
5404     FPU = FPUMode;
5405     CRC = 0;
5406     Crypto = 0;
5407     Unaligned = 1;
5408     V8_1A = 0;
5409 
5410     for (const auto &Feature : Features) {
5411       if (Feature == "+neon")
5412         FPU = NeonMode;
5413       if (Feature == "+crc")
5414         CRC = 1;
5415       if (Feature == "+crypto")
5416         Crypto = 1;
5417       if (Feature == "+strict-align")
5418         Unaligned = 0;
5419       if (Feature == "+v8.1a")
5420         V8_1A = 1;
5421     }
5422 
5423     setDataLayoutString();
5424 
5425     return true;
5426   }
5427 
isCLZForZeroUndef() const5428   bool isCLZForZeroUndef() const override { return false; }
5429 
getBuiltinVaListKind() const5430   BuiltinVaListKind getBuiltinVaListKind() const override {
5431     return TargetInfo::AArch64ABIBuiltinVaList;
5432   }
5433 
5434   ArrayRef<const char *> getGCCRegNames() const override;
5435   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override;
5436 
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & Info) const5437   bool validateAsmConstraint(const char *&Name,
5438                              TargetInfo::ConstraintInfo &Info) const override {
5439     switch (*Name) {
5440     default:
5441       return false;
5442     case 'w': // Floating point and SIMD registers (V0-V31)
5443       Info.setAllowsRegister();
5444       return true;
5445     case 'I': // Constant that can be used with an ADD instruction
5446     case 'J': // Constant that can be used with a SUB instruction
5447     case 'K': // Constant that can be used with a 32-bit logical instruction
5448     case 'L': // Constant that can be used with a 64-bit logical instruction
5449     case 'M': // Constant that can be used as a 32-bit MOV immediate
5450     case 'N': // Constant that can be used as a 64-bit MOV immediate
5451     case 'Y': // Floating point constant zero
5452     case 'Z': // Integer constant zero
5453       return true;
5454     case 'Q': // A memory reference with base register and no offset
5455       Info.setAllowsMemory();
5456       return true;
5457     case 'S': // A symbolic address
5458       Info.setAllowsRegister();
5459       return true;
5460     case 'U':
5461       // Ump: A memory address suitable for ldp/stp in SI, DI, SF and DF modes.
5462       // Utf: A memory address suitable for ldp/stp in TF mode.
5463       // Usa: An absolute symbolic address.
5464       // Ush: The high part (bits 32:12) of a pc-relative symbolic address.
5465       llvm_unreachable("FIXME: Unimplemented support for U* constraints.");
5466     case 'z': // Zero register, wzr or xzr
5467       Info.setAllowsRegister();
5468       return true;
5469     case 'x': // Floating point and SIMD registers (V0-V15)
5470       Info.setAllowsRegister();
5471       return true;
5472     }
5473     return false;
5474   }
5475 
5476   bool
validateConstraintModifier(StringRef Constraint,char Modifier,unsigned Size,std::string & SuggestedModifier) const5477   validateConstraintModifier(StringRef Constraint, char Modifier, unsigned Size,
5478                              std::string &SuggestedModifier) const override {
5479     // Strip off constraint modifiers.
5480     while (Constraint[0] == '=' || Constraint[0] == '+' || Constraint[0] == '&')
5481       Constraint = Constraint.substr(1);
5482 
5483     switch (Constraint[0]) {
5484     default:
5485       return true;
5486     case 'z':
5487     case 'r': {
5488       switch (Modifier) {
5489       case 'x':
5490       case 'w':
5491         // For now assume that the person knows what they're
5492         // doing with the modifier.
5493         return true;
5494       default:
5495         // By default an 'r' constraint will be in the 'x'
5496         // registers.
5497         if (Size == 64)
5498           return true;
5499 
5500         SuggestedModifier = "w";
5501         return false;
5502       }
5503     }
5504     }
5505   }
5506 
getClobbers() const5507   const char *getClobbers() const override { return ""; }
5508 
getEHDataRegisterNumber(unsigned RegNo) const5509   int getEHDataRegisterNumber(unsigned RegNo) const override {
5510     if (RegNo == 0)
5511       return 0;
5512     if (RegNo == 1)
5513       return 1;
5514     return -1;
5515   }
5516 };
5517 
5518 const char *const AArch64TargetInfo::GCCRegNames[] = {
5519   // 32-bit Integer registers
5520   "w0",  "w1",  "w2",  "w3",  "w4",  "w5",  "w6",  "w7",  "w8",  "w9",  "w10",
5521   "w11", "w12", "w13", "w14", "w15", "w16", "w17", "w18", "w19", "w20", "w21",
5522   "w22", "w23", "w24", "w25", "w26", "w27", "w28", "w29", "w30", "wsp",
5523 
5524   // 64-bit Integer registers
5525   "x0",  "x1",  "x2",  "x3",  "x4",  "x5",  "x6",  "x7",  "x8",  "x9",  "x10",
5526   "x11", "x12", "x13", "x14", "x15", "x16", "x17", "x18", "x19", "x20", "x21",
5527   "x22", "x23", "x24", "x25", "x26", "x27", "x28", "fp",  "lr",  "sp",
5528 
5529   // 32-bit floating point regsisters
5530   "s0",  "s1",  "s2",  "s3",  "s4",  "s5",  "s6",  "s7",  "s8",  "s9",  "s10",
5531   "s11", "s12", "s13", "s14", "s15", "s16", "s17", "s18", "s19", "s20", "s21",
5532   "s22", "s23", "s24", "s25", "s26", "s27", "s28", "s29", "s30", "s31",
5533 
5534   // 64-bit floating point regsisters
5535   "d0",  "d1",  "d2",  "d3",  "d4",  "d5",  "d6",  "d7",  "d8",  "d9",  "d10",
5536   "d11", "d12", "d13", "d14", "d15", "d16", "d17", "d18", "d19", "d20", "d21",
5537   "d22", "d23", "d24", "d25", "d26", "d27", "d28", "d29", "d30", "d31",
5538 
5539   // Vector registers
5540   "v0",  "v1",  "v2",  "v3",  "v4",  "v5",  "v6",  "v7",  "v8",  "v9",  "v10",
5541   "v11", "v12", "v13", "v14", "v15", "v16", "v17", "v18", "v19", "v20", "v21",
5542   "v22", "v23", "v24", "v25", "v26", "v27", "v28", "v29", "v30", "v31"
5543 };
5544 
getGCCRegNames() const5545 ArrayRef<const char *> AArch64TargetInfo::getGCCRegNames() const {
5546   return llvm::makeArrayRef(GCCRegNames);
5547 }
5548 
5549 const TargetInfo::GCCRegAlias AArch64TargetInfo::GCCRegAliases[] = {
5550   { { "w31" }, "wsp" },
5551   { { "x29" }, "fp" },
5552   { { "x30" }, "lr" },
5553   { { "x31" }, "sp" },
5554   // The S/D/Q and W/X registers overlap, but aren't really aliases; we
5555   // don't want to substitute one of these for a different-sized one.
5556 };
5557 
getGCCRegAliases() const5558 ArrayRef<TargetInfo::GCCRegAlias> AArch64TargetInfo::getGCCRegAliases() const {
5559   return llvm::makeArrayRef(GCCRegAliases);
5560 }
5561 
5562 const Builtin::Info AArch64TargetInfo::BuiltinInfo[] = {
5563 #define BUILTIN(ID, TYPE, ATTRS)                                               \
5564   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr },
5565 #include "clang/Basic/BuiltinsNEON.def"
5566 
5567 #define BUILTIN(ID, TYPE, ATTRS)                                               \
5568   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr },
5569 #include "clang/Basic/BuiltinsAArch64.def"
5570 };
5571 
5572 class AArch64leTargetInfo : public AArch64TargetInfo {
setDataLayoutString()5573   void setDataLayoutString() override {
5574     if (getTriple().isOSBinFormatMachO())
5575       DataLayoutString = "e-m:o-i64:64-i128:128-n32:64-S128";
5576     else
5577       DataLayoutString = "e-m:e-i64:64-i128:128-n32:64-S128";
5578   }
5579 
5580 public:
AArch64leTargetInfo(const llvm::Triple & Triple)5581   AArch64leTargetInfo(const llvm::Triple &Triple)
5582     : AArch64TargetInfo(Triple) {
5583     BigEndian = false;
5584     }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const5585   void getTargetDefines(const LangOptions &Opts,
5586                         MacroBuilder &Builder) const override {
5587     Builder.defineMacro("__AARCH64EL__");
5588     AArch64TargetInfo::getTargetDefines(Opts, Builder);
5589   }
5590 };
5591 
5592 class AArch64beTargetInfo : public AArch64TargetInfo {
setDataLayoutString()5593   void setDataLayoutString() override {
5594     assert(!getTriple().isOSBinFormatMachO());
5595     DataLayoutString = "E-m:e-i64:64-i128:128-n32:64-S128";
5596   }
5597 
5598 public:
AArch64beTargetInfo(const llvm::Triple & Triple)5599   AArch64beTargetInfo(const llvm::Triple &Triple)
5600     : AArch64TargetInfo(Triple) { }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const5601   void getTargetDefines(const LangOptions &Opts,
5602                         MacroBuilder &Builder) const override {
5603     Builder.defineMacro("__AARCH64EB__");
5604     Builder.defineMacro("__AARCH_BIG_ENDIAN");
5605     Builder.defineMacro("__ARM_BIG_ENDIAN");
5606     AArch64TargetInfo::getTargetDefines(Opts, Builder);
5607   }
5608 };
5609 
5610 class DarwinAArch64TargetInfo : public DarwinTargetInfo<AArch64leTargetInfo> {
5611 protected:
getOSDefines(const LangOptions & Opts,const llvm::Triple & Triple,MacroBuilder & Builder) const5612   void getOSDefines(const LangOptions &Opts, const llvm::Triple &Triple,
5613                     MacroBuilder &Builder) const override {
5614     Builder.defineMacro("__AARCH64_SIMD__");
5615     Builder.defineMacro("__ARM64_ARCH_8__");
5616     Builder.defineMacro("__ARM_NEON__");
5617     Builder.defineMacro("__LITTLE_ENDIAN__");
5618     Builder.defineMacro("__REGISTER_PREFIX__", "");
5619     Builder.defineMacro("__arm64", "1");
5620     Builder.defineMacro("__arm64__", "1");
5621 
5622     getDarwinDefines(Builder, Opts, Triple, PlatformName, PlatformMinVersion);
5623   }
5624 
5625 public:
DarwinAArch64TargetInfo(const llvm::Triple & Triple)5626   DarwinAArch64TargetInfo(const llvm::Triple &Triple)
5627       : DarwinTargetInfo<AArch64leTargetInfo>(Triple) {
5628     Int64Type = SignedLongLong;
5629     WCharType = SignedInt;
5630     UseSignedCharForObjCBool = false;
5631 
5632     LongDoubleWidth = LongDoubleAlign = SuitableAlign = 64;
5633     LongDoubleFormat = &llvm::APFloat::IEEEdouble;
5634 
5635     TheCXXABI.set(TargetCXXABI::iOS64);
5636   }
5637 
getBuiltinVaListKind() const5638   BuiltinVaListKind getBuiltinVaListKind() const override {
5639     return TargetInfo::CharPtrBuiltinVaList;
5640   }
5641 };
5642 
5643 // Hexagon abstract base class
5644 class HexagonTargetInfo : public TargetInfo {
5645   static const Builtin::Info BuiltinInfo[];
5646   static const char * const GCCRegNames[];
5647   static const TargetInfo::GCCRegAlias GCCRegAliases[];
5648   std::string CPU;
5649   bool HasHVX, HasHVXDouble;
5650 
5651 public:
HexagonTargetInfo(const llvm::Triple & Triple)5652   HexagonTargetInfo(const llvm::Triple &Triple) : TargetInfo(Triple) {
5653     BigEndian = false;
5654     DataLayoutString = "e-m:e-p:32:32:32-"
5655                        "i64:64:64-i32:32:32-i16:16:16-i1:8:8-"
5656                        "f64:64:64-f32:32:32-v64:64:64-v32:32:32-a:0-n16:32";
5657     SizeType    = UnsignedInt;
5658     PtrDiffType = SignedInt;
5659     IntPtrType  = SignedInt;
5660 
5661     // {} in inline assembly are packet specifiers, not assembly variant
5662     // specifiers.
5663     NoAsmVariants = true;
5664 
5665     LargeArrayMinWidth = 64;
5666     LargeArrayAlign = 64;
5667     UseBitFieldTypeAlignment = true;
5668     ZeroLengthBitfieldBoundary = 32;
5669     HasHVX = HasHVXDouble = false;
5670   }
5671 
getTargetBuiltins() const5672   ArrayRef<Builtin::Info> getTargetBuiltins() const override {
5673     return llvm::makeArrayRef(BuiltinInfo,
5674                          clang::Hexagon::LastTSBuiltin-Builtin::FirstTSBuiltin);
5675   }
5676 
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & Info) const5677   bool validateAsmConstraint(const char *&Name,
5678                              TargetInfo::ConstraintInfo &Info) const override {
5679     return true;
5680   }
5681 
5682   void getTargetDefines(const LangOptions &Opts,
5683                         MacroBuilder &Builder) const override;
5684 
isCLZForZeroUndef() const5685   bool isCLZForZeroUndef() const override { return false; }
5686 
hasFeature(StringRef Feature) const5687   bool hasFeature(StringRef Feature) const override {
5688     return llvm::StringSwitch<bool>(Feature)
5689       .Case("hexagon", true)
5690       .Case("hvx", HasHVX)
5691       .Case("hvx-double", HasHVXDouble)
5692       .Default(false);
5693   }
5694 
5695   bool initFeatureMap(llvm::StringMap<bool> &Features, DiagnosticsEngine &Diags,
5696         StringRef CPU, const std::vector<std::string> &FeaturesVec)
5697         const override;
5698 
5699   bool handleTargetFeatures(std::vector<std::string> &Features,
5700                             DiagnosticsEngine &Diags) override;
5701 
getBuiltinVaListKind() const5702   BuiltinVaListKind getBuiltinVaListKind() const override {
5703     return TargetInfo::CharPtrBuiltinVaList;
5704   }
5705   ArrayRef<const char *> getGCCRegNames() const override;
5706   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override;
getClobbers() const5707   const char *getClobbers() const override {
5708     return "";
5709   }
5710 
getHexagonCPUSuffix(StringRef Name)5711   static const char *getHexagonCPUSuffix(StringRef Name) {
5712     return llvm::StringSwitch<const char*>(Name)
5713       .Case("hexagonv4", "4")
5714       .Case("hexagonv5", "5")
5715       .Case("hexagonv55", "55")
5716       .Case("hexagonv60", "60")
5717       .Default(nullptr);
5718   }
5719 
setCPU(const std::string & Name)5720   bool setCPU(const std::string &Name) override {
5721     if (!getHexagonCPUSuffix(Name))
5722       return false;
5723     CPU = Name;
5724     return true;
5725   }
5726 
getEHDataRegisterNumber(unsigned RegNo) const5727   int getEHDataRegisterNumber(unsigned RegNo) const override {
5728     return RegNo < 2 ? RegNo : -1;
5729   }
5730 };
5731 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const5732 void HexagonTargetInfo::getTargetDefines(const LangOptions &Opts,
5733                                          MacroBuilder &Builder) const {
5734   Builder.defineMacro("__qdsp6__", "1");
5735   Builder.defineMacro("__hexagon__", "1");
5736 
5737   if (CPU == "hexagonv4") {
5738     Builder.defineMacro("__HEXAGON_V4__");
5739     Builder.defineMacro("__HEXAGON_ARCH__", "4");
5740     if (Opts.HexagonQdsp6Compat) {
5741       Builder.defineMacro("__QDSP6_V4__");
5742       Builder.defineMacro("__QDSP6_ARCH__", "4");
5743     }
5744   } else if (CPU == "hexagonv5") {
5745     Builder.defineMacro("__HEXAGON_V5__");
5746     Builder.defineMacro("__HEXAGON_ARCH__", "5");
5747     if(Opts.HexagonQdsp6Compat) {
5748       Builder.defineMacro("__QDSP6_V5__");
5749       Builder.defineMacro("__QDSP6_ARCH__", "5");
5750     }
5751   } else if (CPU == "hexagonv60") {
5752     Builder.defineMacro("__HEXAGON_V60__");
5753     Builder.defineMacro("__HEXAGON_ARCH__", "60");
5754     Builder.defineMacro("__QDSP6_V60__");
5755     Builder.defineMacro("__QDSP6_ARCH__", "60");
5756   }
5757 }
5758 
handleTargetFeatures(std::vector<std::string> & Features,DiagnosticsEngine & Diags)5759 bool HexagonTargetInfo::handleTargetFeatures(std::vector<std::string> &Features,
5760                                              DiagnosticsEngine &Diags) {
5761   for (auto &F : Features) {
5762     if (F == "+hvx")
5763       HasHVX = true;
5764     else if (F == "-hvx")
5765       HasHVX = HasHVXDouble = false;
5766     else if (F == "+hvx-double")
5767       HasHVX = HasHVXDouble = true;
5768     else if (F == "-hvx-double")
5769       HasHVXDouble = false;
5770   }
5771   return true;
5772 }
5773 
initFeatureMap(llvm::StringMap<bool> & Features,DiagnosticsEngine & Diags,StringRef CPU,const std::vector<std::string> & FeaturesVec) const5774 bool HexagonTargetInfo::initFeatureMap(llvm::StringMap<bool> &Features,
5775       DiagnosticsEngine &Diags, StringRef CPU,
5776       const std::vector<std::string> &FeaturesVec) const {
5777   // Default for v60: -hvx, -hvx-double.
5778   Features["hvx"] = false;
5779   Features["hvx-double"] = false;
5780 
5781   return TargetInfo::initFeatureMap(Features, Diags, CPU, FeaturesVec);
5782 }
5783 
5784 
5785 const char *const HexagonTargetInfo::GCCRegNames[] = {
5786   "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7",
5787   "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
5788   "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23",
5789   "r24", "r25", "r26", "r27", "r28", "r29", "r30", "r31",
5790   "p0", "p1", "p2", "p3",
5791   "sa0", "lc0", "sa1", "lc1", "m0", "m1", "usr", "ugp"
5792 };
5793 
getGCCRegNames() const5794 ArrayRef<const char*> HexagonTargetInfo::getGCCRegNames() const {
5795   return llvm::makeArrayRef(GCCRegNames);
5796 }
5797 
5798 const TargetInfo::GCCRegAlias HexagonTargetInfo::GCCRegAliases[] = {
5799   { { "sp" }, "r29" },
5800   { { "fp" }, "r30" },
5801   { { "lr" }, "r31" },
5802 };
5803 
getGCCRegAliases() const5804 ArrayRef<TargetInfo::GCCRegAlias> HexagonTargetInfo::getGCCRegAliases() const {
5805   return llvm::makeArrayRef(GCCRegAliases);
5806 }
5807 
5808 
5809 const Builtin::Info HexagonTargetInfo::BuiltinInfo[] = {
5810 #define BUILTIN(ID, TYPE, ATTRS) \
5811   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr },
5812 #define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) \
5813   { #ID, TYPE, ATTRS, HEADER, ALL_LANGUAGES, nullptr },
5814 #include "clang/Basic/BuiltinsHexagon.def"
5815 };
5816 
5817 // Shared base class for SPARC v8 (32-bit) and SPARC v9 (64-bit).
5818 class SparcTargetInfo : public TargetInfo {
5819   static const TargetInfo::GCCRegAlias GCCRegAliases[];
5820   static const char * const GCCRegNames[];
5821   bool SoftFloat;
5822 public:
SparcTargetInfo(const llvm::Triple & Triple)5823   SparcTargetInfo(const llvm::Triple &Triple)
5824       : TargetInfo(Triple), SoftFloat(false) {}
5825 
handleTargetFeatures(std::vector<std::string> & Features,DiagnosticsEngine & Diags)5826   bool handleTargetFeatures(std::vector<std::string> &Features,
5827                             DiagnosticsEngine &Diags) override {
5828     // The backend doesn't actually handle soft float yet, but in case someone
5829     // is using the support for the front end continue to support it.
5830     auto Feature = std::find(Features.begin(), Features.end(), "+soft-float");
5831     if (Feature != Features.end()) {
5832       SoftFloat = true;
5833       Features.erase(Feature);
5834     }
5835     return true;
5836   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const5837   void getTargetDefines(const LangOptions &Opts,
5838                         MacroBuilder &Builder) const override {
5839     DefineStd(Builder, "sparc", Opts);
5840     Builder.defineMacro("__REGISTER_PREFIX__", "");
5841 
5842     if (SoftFloat)
5843       Builder.defineMacro("SOFT_FLOAT", "1");
5844   }
5845 
hasFeature(StringRef Feature) const5846   bool hasFeature(StringRef Feature) const override {
5847     return llvm::StringSwitch<bool>(Feature)
5848              .Case("softfloat", SoftFloat)
5849              .Case("sparc", true)
5850              .Default(false);
5851   }
5852 
getTargetBuiltins() const5853   ArrayRef<Builtin::Info> getTargetBuiltins() const override {
5854     // FIXME: Implement!
5855     return None;
5856   }
getBuiltinVaListKind() const5857   BuiltinVaListKind getBuiltinVaListKind() const override {
5858     return TargetInfo::VoidPtrBuiltinVaList;
5859   }
5860   ArrayRef<const char *> getGCCRegNames() const override;
5861   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override;
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & info) const5862   bool validateAsmConstraint(const char *&Name,
5863                              TargetInfo::ConstraintInfo &info) const override {
5864     // FIXME: Implement!
5865     switch (*Name) {
5866     case 'I': // Signed 13-bit constant
5867     case 'J': // Zero
5868     case 'K': // 32-bit constant with the low 12 bits clear
5869     case 'L': // A constant in the range supported by movcc (11-bit signed imm)
5870     case 'M': // A constant in the range supported by movrcc (19-bit signed imm)
5871     case 'N': // Same as 'K' but zext (required for SIMode)
5872     case 'O': // The constant 4096
5873       return true;
5874     }
5875     return false;
5876   }
getClobbers() const5877   const char *getClobbers() const override {
5878     // FIXME: Implement!
5879     return "";
5880   }
5881 
5882   // No Sparc V7 for now, the backend doesn't support it anyway.
5883   enum CPUKind {
5884     CK_GENERIC,
5885     CK_V8,
5886     CK_SUPERSPARC,
5887     CK_SPARCLITE,
5888     CK_F934,
5889     CK_HYPERSPARC,
5890     CK_SPARCLITE86X,
5891     CK_SPARCLET,
5892     CK_TSC701,
5893     CK_V9,
5894     CK_ULTRASPARC,
5895     CK_ULTRASPARC3,
5896     CK_NIAGARA,
5897     CK_NIAGARA2,
5898     CK_NIAGARA3,
5899     CK_NIAGARA4
5900   } CPU = CK_GENERIC;
5901 
5902   enum CPUGeneration {
5903     CG_V8,
5904     CG_V9,
5905   };
5906 
getCPUGeneration(CPUKind Kind) const5907   CPUGeneration getCPUGeneration(CPUKind Kind) const {
5908     switch (Kind) {
5909     case CK_GENERIC:
5910     case CK_V8:
5911     case CK_SUPERSPARC:
5912     case CK_SPARCLITE:
5913     case CK_F934:
5914     case CK_HYPERSPARC:
5915     case CK_SPARCLITE86X:
5916     case CK_SPARCLET:
5917     case CK_TSC701:
5918       return CG_V8;
5919     case CK_V9:
5920     case CK_ULTRASPARC:
5921     case CK_ULTRASPARC3:
5922     case CK_NIAGARA:
5923     case CK_NIAGARA2:
5924     case CK_NIAGARA3:
5925     case CK_NIAGARA4:
5926       return CG_V9;
5927     }
5928     llvm_unreachable("Unexpected CPU kind");
5929   }
5930 
getCPUKind(StringRef Name) const5931   CPUKind getCPUKind(StringRef Name) const {
5932     return llvm::StringSwitch<CPUKind>(Name)
5933         .Case("v8", CK_V8)
5934         .Case("supersparc", CK_SUPERSPARC)
5935         .Case("sparclite", CK_SPARCLITE)
5936         .Case("f934", CK_F934)
5937         .Case("hypersparc", CK_HYPERSPARC)
5938         .Case("sparclite86x", CK_SPARCLITE86X)
5939         .Case("sparclet", CK_SPARCLET)
5940         .Case("tsc701", CK_TSC701)
5941         .Case("v9", CK_V9)
5942         .Case("ultrasparc", CK_ULTRASPARC)
5943         .Case("ultrasparc3", CK_ULTRASPARC3)
5944         .Case("niagara", CK_NIAGARA)
5945         .Case("niagara2", CK_NIAGARA2)
5946         .Case("niagara3", CK_NIAGARA3)
5947         .Case("niagara4", CK_NIAGARA4)
5948         .Default(CK_GENERIC);
5949   }
5950 
setCPU(const std::string & Name)5951   bool setCPU(const std::string &Name) override {
5952     CPU = getCPUKind(Name);
5953     return CPU != CK_GENERIC;
5954   }
5955 };
5956 
5957 const char * const SparcTargetInfo::GCCRegNames[] = {
5958   "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7",
5959   "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
5960   "r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23",
5961   "r24", "r25", "r26", "r27", "r28", "r29", "r30", "r31"
5962 };
5963 
getGCCRegNames() const5964 ArrayRef<const char *> SparcTargetInfo::getGCCRegNames() const {
5965   return llvm::makeArrayRef(GCCRegNames);
5966 }
5967 
5968 const TargetInfo::GCCRegAlias SparcTargetInfo::GCCRegAliases[] = {
5969   { { "g0" }, "r0" },
5970   { { "g1" }, "r1" },
5971   { { "g2" }, "r2" },
5972   { { "g3" }, "r3" },
5973   { { "g4" }, "r4" },
5974   { { "g5" }, "r5" },
5975   { { "g6" }, "r6" },
5976   { { "g7" }, "r7" },
5977   { { "o0" }, "r8" },
5978   { { "o1" }, "r9" },
5979   { { "o2" }, "r10" },
5980   { { "o3" }, "r11" },
5981   { { "o4" }, "r12" },
5982   { { "o5" }, "r13" },
5983   { { "o6", "sp" }, "r14" },
5984   { { "o7" }, "r15" },
5985   { { "l0" }, "r16" },
5986   { { "l1" }, "r17" },
5987   { { "l2" }, "r18" },
5988   { { "l3" }, "r19" },
5989   { { "l4" }, "r20" },
5990   { { "l5" }, "r21" },
5991   { { "l6" }, "r22" },
5992   { { "l7" }, "r23" },
5993   { { "i0" }, "r24" },
5994   { { "i1" }, "r25" },
5995   { { "i2" }, "r26" },
5996   { { "i3" }, "r27" },
5997   { { "i4" }, "r28" },
5998   { { "i5" }, "r29" },
5999   { { "i6", "fp" }, "r30" },
6000   { { "i7" }, "r31" },
6001 };
6002 
getGCCRegAliases() const6003 ArrayRef<TargetInfo::GCCRegAlias> SparcTargetInfo::getGCCRegAliases() const {
6004   return llvm::makeArrayRef(GCCRegAliases);
6005 }
6006 
6007 // SPARC v8 is the 32-bit mode selected by Triple::sparc.
6008 class SparcV8TargetInfo : public SparcTargetInfo {
6009 public:
SparcV8TargetInfo(const llvm::Triple & Triple)6010   SparcV8TargetInfo(const llvm::Triple &Triple) : SparcTargetInfo(Triple) {
6011     DataLayoutString = "E-m:e-p:32:32-i64:64-f128:64-n32-S64";
6012     // NetBSD / OpenBSD use long (same as llvm default); everyone else uses int.
6013     switch (getTriple().getOS()) {
6014     default:
6015       SizeType = UnsignedInt;
6016       IntPtrType = SignedInt;
6017       PtrDiffType = SignedInt;
6018       break;
6019     case llvm::Triple::NetBSD:
6020     case llvm::Triple::OpenBSD:
6021       SizeType = UnsignedLong;
6022       IntPtrType = SignedLong;
6023       PtrDiffType = SignedLong;
6024       break;
6025     }
6026   }
6027 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const6028   void getTargetDefines(const LangOptions &Opts,
6029                         MacroBuilder &Builder) const override {
6030     SparcTargetInfo::getTargetDefines(Opts, Builder);
6031     switch (getCPUGeneration(CPU)) {
6032     case CG_V8:
6033       Builder.defineMacro("__sparcv8");
6034       if (getTriple().getOS() != llvm::Triple::Solaris)
6035         Builder.defineMacro("__sparcv8__");
6036       break;
6037     case CG_V9:
6038       Builder.defineMacro("__sparcv9");
6039       if (getTriple().getOS() != llvm::Triple::Solaris) {
6040         Builder.defineMacro("__sparcv9__");
6041         Builder.defineMacro("__sparc_v9__");
6042       }
6043       break;
6044     }
6045   }
6046 };
6047 
6048 // SPARCV8el is the 32-bit little-endian mode selected by Triple::sparcel.
6049 class SparcV8elTargetInfo : public SparcV8TargetInfo {
6050  public:
SparcV8elTargetInfo(const llvm::Triple & Triple)6051   SparcV8elTargetInfo(const llvm::Triple &Triple) : SparcV8TargetInfo(Triple) {
6052     DataLayoutString = "e-m:e-p:32:32-i64:64-f128:64-n32-S64";
6053     BigEndian = false;
6054   }
6055 };
6056 
6057 // SPARC v9 is the 64-bit mode selected by Triple::sparcv9.
6058 class SparcV9TargetInfo : public SparcTargetInfo {
6059 public:
SparcV9TargetInfo(const llvm::Triple & Triple)6060   SparcV9TargetInfo(const llvm::Triple &Triple) : SparcTargetInfo(Triple) {
6061     // FIXME: Support Sparc quad-precision long double?
6062     DataLayoutString = "E-m:e-i64:64-n32:64-S128";
6063     // This is an LP64 platform.
6064     LongWidth = LongAlign = PointerWidth = PointerAlign = 64;
6065 
6066     // OpenBSD uses long long for int64_t and intmax_t.
6067     if (getTriple().getOS() == llvm::Triple::OpenBSD)
6068       IntMaxType = SignedLongLong;
6069     else
6070       IntMaxType = SignedLong;
6071     Int64Type = IntMaxType;
6072 
6073     // The SPARCv8 System V ABI has long double 128-bits in size, but 64-bit
6074     // aligned. The SPARCv9 SCD 2.4.1 says 16-byte aligned.
6075     LongDoubleWidth = 128;
6076     LongDoubleAlign = 128;
6077     LongDoubleFormat = &llvm::APFloat::IEEEquad;
6078     MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 64;
6079   }
6080 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const6081   void getTargetDefines(const LangOptions &Opts,
6082                         MacroBuilder &Builder) const override {
6083     SparcTargetInfo::getTargetDefines(Opts, Builder);
6084     Builder.defineMacro("__sparcv9");
6085     Builder.defineMacro("__arch64__");
6086     // Solaris doesn't need these variants, but the BSDs do.
6087     if (getTriple().getOS() != llvm::Triple::Solaris) {
6088       Builder.defineMacro("__sparc64__");
6089       Builder.defineMacro("__sparc_v9__");
6090       Builder.defineMacro("__sparcv9__");
6091     }
6092   }
6093 
setCPU(const std::string & Name)6094   bool setCPU(const std::string &Name) override {
6095     if (!SparcTargetInfo::setCPU(Name))
6096       return false;
6097     return getCPUGeneration(CPU) == CG_V9;
6098   }
6099 };
6100 
6101 class SystemZTargetInfo : public TargetInfo {
6102   static const Builtin::Info BuiltinInfo[];
6103   static const char *const GCCRegNames[];
6104   std::string CPU;
6105   bool HasTransactionalExecution;
6106   bool HasVector;
6107 
6108 public:
SystemZTargetInfo(const llvm::Triple & Triple)6109   SystemZTargetInfo(const llvm::Triple &Triple)
6110       : TargetInfo(Triple), CPU("z10"), HasTransactionalExecution(false),
6111         HasVector(false) {
6112     IntMaxType = SignedLong;
6113     Int64Type = SignedLong;
6114     TLSSupported = true;
6115     IntWidth = IntAlign = 32;
6116     LongWidth = LongLongWidth = LongAlign = LongLongAlign = 64;
6117     PointerWidth = PointerAlign = 64;
6118     LongDoubleWidth = 128;
6119     LongDoubleAlign = 64;
6120     LongDoubleFormat = &llvm::APFloat::IEEEquad;
6121     DefaultAlignForAttributeAligned = 64;
6122     MinGlobalAlign = 16;
6123     DataLayoutString = "E-m:e-i1:8:16-i8:8:16-i64:64-f128:64-a:8:16-n32:64";
6124     MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 64;
6125   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const6126   void getTargetDefines(const LangOptions &Opts,
6127                         MacroBuilder &Builder) const override {
6128     Builder.defineMacro("__s390__");
6129     Builder.defineMacro("__s390x__");
6130     Builder.defineMacro("__zarch__");
6131     Builder.defineMacro("__LONG_DOUBLE_128__");
6132     if (HasTransactionalExecution)
6133       Builder.defineMacro("__HTM__");
6134     if (Opts.ZVector)
6135       Builder.defineMacro("__VEC__", "10301");
6136   }
getTargetBuiltins() const6137   ArrayRef<Builtin::Info> getTargetBuiltins() const override {
6138     return llvm::makeArrayRef(BuiltinInfo,
6139                          clang::SystemZ::LastTSBuiltin-Builtin::FirstTSBuiltin);
6140   }
6141 
6142   ArrayRef<const char *> getGCCRegNames() const override;
getGCCRegAliases() const6143   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override {
6144     // No aliases.
6145     return None;
6146   }
6147   bool validateAsmConstraint(const char *&Name,
6148                              TargetInfo::ConstraintInfo &info) const override;
getClobbers() const6149   const char *getClobbers() const override {
6150     // FIXME: Is this really right?
6151     return "";
6152   }
getBuiltinVaListKind() const6153   BuiltinVaListKind getBuiltinVaListKind() const override {
6154     return TargetInfo::SystemZBuiltinVaList;
6155   }
setCPU(const std::string & Name)6156   bool setCPU(const std::string &Name) override {
6157     CPU = Name;
6158     bool CPUKnown = llvm::StringSwitch<bool>(Name)
6159       .Case("z10", true)
6160       .Case("z196", true)
6161       .Case("zEC12", true)
6162       .Case("z13", true)
6163       .Default(false);
6164 
6165     return CPUKnown;
6166   }
6167   bool
initFeatureMap(llvm::StringMap<bool> & Features,DiagnosticsEngine & Diags,StringRef CPU,const std::vector<std::string> & FeaturesVec) const6168   initFeatureMap(llvm::StringMap<bool> &Features, DiagnosticsEngine &Diags,
6169                  StringRef CPU,
6170                  const std::vector<std::string> &FeaturesVec) const override {
6171     if (CPU == "zEC12")
6172       Features["transactional-execution"] = true;
6173     if (CPU == "z13") {
6174       Features["transactional-execution"] = true;
6175       Features["vector"] = true;
6176     }
6177     return TargetInfo::initFeatureMap(Features, Diags, CPU, FeaturesVec);
6178   }
6179 
handleTargetFeatures(std::vector<std::string> & Features,DiagnosticsEngine & Diags)6180   bool handleTargetFeatures(std::vector<std::string> &Features,
6181                             DiagnosticsEngine &Diags) override {
6182     HasTransactionalExecution = false;
6183     for (const auto &Feature : Features) {
6184       if (Feature == "+transactional-execution")
6185         HasTransactionalExecution = true;
6186       else if (Feature == "+vector")
6187         HasVector = true;
6188     }
6189     // If we use the vector ABI, vector types are 64-bit aligned.
6190     if (HasVector) {
6191       MaxVectorAlign = 64;
6192       DataLayoutString = "E-m:e-i1:8:16-i8:8:16-i64:64-f128:64"
6193                          "-v128:64-a:8:16-n32:64";
6194     }
6195     return true;
6196   }
6197 
hasFeature(StringRef Feature) const6198   bool hasFeature(StringRef Feature) const override {
6199     return llvm::StringSwitch<bool>(Feature)
6200         .Case("systemz", true)
6201         .Case("htm", HasTransactionalExecution)
6202         .Case("vx", HasVector)
6203         .Default(false);
6204   }
6205 
getABI() const6206   StringRef getABI() const override {
6207     if (HasVector)
6208       return "vector";
6209     return "";
6210   }
6211 
useFloat128ManglingForLongDouble() const6212   bool useFloat128ManglingForLongDouble() const override {
6213     return true;
6214   }
6215 };
6216 
6217 const Builtin::Info SystemZTargetInfo::BuiltinInfo[] = {
6218 #define BUILTIN(ID, TYPE, ATTRS)                                               \
6219   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr },
6220 #include "clang/Basic/BuiltinsSystemZ.def"
6221 };
6222 
6223 const char *const SystemZTargetInfo::GCCRegNames[] = {
6224   "r0",  "r1",  "r2",  "r3",  "r4",  "r5",  "r6",  "r7",
6225   "r8",  "r9",  "r10", "r11", "r12", "r13", "r14", "r15",
6226   "f0",  "f2",  "f4",  "f6",  "f1",  "f3",  "f5",  "f7",
6227   "f8",  "f10", "f12", "f14", "f9",  "f11", "f13", "f15"
6228 };
6229 
getGCCRegNames() const6230 ArrayRef<const char *> SystemZTargetInfo::getGCCRegNames() const {
6231   return llvm::makeArrayRef(GCCRegNames);
6232 }
6233 
6234 bool SystemZTargetInfo::
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & Info) const6235 validateAsmConstraint(const char *&Name,
6236                       TargetInfo::ConstraintInfo &Info) const {
6237   switch (*Name) {
6238   default:
6239     return false;
6240 
6241   case 'a': // Address register
6242   case 'd': // Data register (equivalent to 'r')
6243   case 'f': // Floating-point register
6244     Info.setAllowsRegister();
6245     return true;
6246 
6247   case 'I': // Unsigned 8-bit constant
6248   case 'J': // Unsigned 12-bit constant
6249   case 'K': // Signed 16-bit constant
6250   case 'L': // Signed 20-bit displacement (on all targets we support)
6251   case 'M': // 0x7fffffff
6252     return true;
6253 
6254   case 'Q': // Memory with base and unsigned 12-bit displacement
6255   case 'R': // Likewise, plus an index
6256   case 'S': // Memory with base and signed 20-bit displacement
6257   case 'T': // Likewise, plus an index
6258     Info.setAllowsMemory();
6259     return true;
6260   }
6261 }
6262 
6263 class MSP430TargetInfo : public TargetInfo {
6264   static const char *const GCCRegNames[];
6265 
6266 public:
MSP430TargetInfo(const llvm::Triple & Triple)6267   MSP430TargetInfo(const llvm::Triple &Triple) : TargetInfo(Triple) {
6268     BigEndian = false;
6269     TLSSupported = false;
6270     IntWidth = 16;
6271     IntAlign = 16;
6272     LongWidth = 32;
6273     LongLongWidth = 64;
6274     LongAlign = LongLongAlign = 16;
6275     PointerWidth = 16;
6276     PointerAlign = 16;
6277     SuitableAlign = 16;
6278     SizeType = UnsignedInt;
6279     IntMaxType = SignedLongLong;
6280     IntPtrType = SignedInt;
6281     PtrDiffType = SignedInt;
6282     SigAtomicType = SignedLong;
6283     DataLayoutString = "e-m:e-p:16:16-i32:16:32-a:16-n8:16";
6284   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const6285   void getTargetDefines(const LangOptions &Opts,
6286                         MacroBuilder &Builder) const override {
6287     Builder.defineMacro("MSP430");
6288     Builder.defineMacro("__MSP430__");
6289     // FIXME: defines for different 'flavours' of MCU
6290   }
getTargetBuiltins() const6291   ArrayRef<Builtin::Info> getTargetBuiltins() const override {
6292     // FIXME: Implement.
6293     return None;
6294   }
hasFeature(StringRef Feature) const6295   bool hasFeature(StringRef Feature) const override {
6296     return Feature == "msp430";
6297   }
6298   ArrayRef<const char *> getGCCRegNames() const override;
getGCCRegAliases() const6299   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override {
6300     // No aliases.
6301     return None;
6302   }
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & info) const6303   bool validateAsmConstraint(const char *&Name,
6304                              TargetInfo::ConstraintInfo &info) const override {
6305     // FIXME: implement
6306     switch (*Name) {
6307     case 'K': // the constant 1
6308     case 'L': // constant -1^20 .. 1^19
6309     case 'M': // constant 1-4:
6310       return true;
6311     }
6312     // No target constraints for now.
6313     return false;
6314   }
getClobbers() const6315   const char *getClobbers() const override {
6316     // FIXME: Is this really right?
6317     return "";
6318   }
getBuiltinVaListKind() const6319   BuiltinVaListKind getBuiltinVaListKind() const override {
6320     // FIXME: implement
6321     return TargetInfo::CharPtrBuiltinVaList;
6322   }
6323 };
6324 
6325 const char *const MSP430TargetInfo::GCCRegNames[] = {
6326     "r0", "r1", "r2",  "r3",  "r4",  "r5",  "r6",  "r7",
6327     "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15"};
6328 
getGCCRegNames() const6329 ArrayRef<const char *> MSP430TargetInfo::getGCCRegNames() const {
6330   return llvm::makeArrayRef(GCCRegNames);
6331 }
6332 
6333 // LLVM and Clang cannot be used directly to output native binaries for
6334 // target, but is used to compile C code to llvm bitcode with correct
6335 // type and alignment information.
6336 //
6337 // TCE uses the llvm bitcode as input and uses it for generating customized
6338 // target processor and program binary. TCE co-design environment is
6339 // publicly available in http://tce.cs.tut.fi
6340 
6341 static const unsigned TCEOpenCLAddrSpaceMap[] = {
6342     3, // opencl_global
6343     4, // opencl_local
6344     5, // opencl_constant
6345     // FIXME: generic has to be added to the target
6346     0, // opencl_generic
6347     0, // cuda_device
6348     0, // cuda_constant
6349     0  // cuda_shared
6350 };
6351 
6352 class TCETargetInfo : public TargetInfo {
6353 public:
TCETargetInfo(const llvm::Triple & Triple)6354   TCETargetInfo(const llvm::Triple &Triple) : TargetInfo(Triple) {
6355     TLSSupported = false;
6356     IntWidth = 32;
6357     LongWidth = LongLongWidth = 32;
6358     PointerWidth = 32;
6359     IntAlign = 32;
6360     LongAlign = LongLongAlign = 32;
6361     PointerAlign = 32;
6362     SuitableAlign = 32;
6363     SizeType = UnsignedInt;
6364     IntMaxType = SignedLong;
6365     IntPtrType = SignedInt;
6366     PtrDiffType = SignedInt;
6367     FloatWidth = 32;
6368     FloatAlign = 32;
6369     DoubleWidth = 32;
6370     DoubleAlign = 32;
6371     LongDoubleWidth = 32;
6372     LongDoubleAlign = 32;
6373     FloatFormat = &llvm::APFloat::IEEEsingle;
6374     DoubleFormat = &llvm::APFloat::IEEEsingle;
6375     LongDoubleFormat = &llvm::APFloat::IEEEsingle;
6376     DataLayoutString = "E-p:32:32-i8:8:32-i16:16:32-i64:32"
6377                        "-f64:32-v64:32-v128:32-a:0:32-n32";
6378     AddrSpaceMap = &TCEOpenCLAddrSpaceMap;
6379     UseAddrSpaceMapMangling = true;
6380   }
6381 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const6382   void getTargetDefines(const LangOptions &Opts,
6383                         MacroBuilder &Builder) const override {
6384     DefineStd(Builder, "tce", Opts);
6385     Builder.defineMacro("__TCE__");
6386     Builder.defineMacro("__TCE_V1__");
6387   }
hasFeature(StringRef Feature) const6388   bool hasFeature(StringRef Feature) const override { return Feature == "tce"; }
6389 
getTargetBuiltins() const6390   ArrayRef<Builtin::Info> getTargetBuiltins() const override { return None; }
getClobbers() const6391   const char *getClobbers() const override { return ""; }
getBuiltinVaListKind() const6392   BuiltinVaListKind getBuiltinVaListKind() const override {
6393     return TargetInfo::VoidPtrBuiltinVaList;
6394   }
getGCCRegNames() const6395   ArrayRef<const char *> getGCCRegNames() const override { return None; }
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & info) const6396   bool validateAsmConstraint(const char *&Name,
6397                              TargetInfo::ConstraintInfo &info) const override {
6398     return true;
6399   }
getGCCRegAliases() const6400   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override {
6401     return None;
6402   }
6403 };
6404 
6405 class BPFTargetInfo : public TargetInfo {
6406 public:
BPFTargetInfo(const llvm::Triple & Triple)6407   BPFTargetInfo(const llvm::Triple &Triple) : TargetInfo(Triple) {
6408     LongWidth = LongAlign = PointerWidth = PointerAlign = 64;
6409     SizeType    = UnsignedLong;
6410     PtrDiffType = SignedLong;
6411     IntPtrType  = SignedLong;
6412     IntMaxType  = SignedLong;
6413     Int64Type   = SignedLong;
6414     RegParmMax = 5;
6415     if (Triple.getArch() == llvm::Triple::bpfeb) {
6416       BigEndian = true;
6417       DataLayoutString = "E-m:e-p:64:64-i64:64-n32:64-S128";
6418     } else {
6419       BigEndian = false;
6420       DataLayoutString = "e-m:e-p:64:64-i64:64-n32:64-S128";
6421     }
6422     MaxAtomicPromoteWidth = 64;
6423     MaxAtomicInlineWidth = 64;
6424     TLSSupported = false;
6425   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const6426   void getTargetDefines(const LangOptions &Opts,
6427                         MacroBuilder &Builder) const override {
6428     DefineStd(Builder, "bpf", Opts);
6429     Builder.defineMacro("__BPF__");
6430   }
hasFeature(StringRef Feature) const6431   bool hasFeature(StringRef Feature) const override {
6432     return Feature == "bpf";
6433   }
6434 
getTargetBuiltins() const6435   ArrayRef<Builtin::Info> getTargetBuiltins() const override { return None; }
getClobbers() const6436   const char *getClobbers() const override {
6437     return "";
6438   }
getBuiltinVaListKind() const6439   BuiltinVaListKind getBuiltinVaListKind() const override {
6440     return TargetInfo::VoidPtrBuiltinVaList;
6441   }
getGCCRegNames() const6442   ArrayRef<const char *> getGCCRegNames() const override {
6443     return None;
6444   }
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & info) const6445   bool validateAsmConstraint(const char *&Name,
6446                              TargetInfo::ConstraintInfo &info) const override {
6447     return true;
6448   }
getGCCRegAliases() const6449   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override {
6450     return None;
6451   }
6452 };
6453 
6454 class MipsTargetInfoBase : public TargetInfo {
6455   virtual void setDataLayoutString() = 0;
6456 
6457   static const Builtin::Info BuiltinInfo[];
6458   std::string CPU;
6459   bool IsMips16;
6460   bool IsMicromips;
6461   bool IsNan2008;
6462   bool IsSingleFloat;
6463   enum MipsFloatABI {
6464     HardFloat, SoftFloat
6465   } FloatABI;
6466   enum DspRevEnum {
6467     NoDSP, DSP1, DSP2
6468   } DspRev;
6469   bool HasMSA;
6470 
6471 protected:
6472   bool HasFP64;
6473   std::string ABI;
6474 
6475 public:
MipsTargetInfoBase(const llvm::Triple & Triple,const std::string & ABIStr,const std::string & CPUStr)6476   MipsTargetInfoBase(const llvm::Triple &Triple, const std::string &ABIStr,
6477                      const std::string &CPUStr)
6478       : TargetInfo(Triple), CPU(CPUStr), IsMips16(false), IsMicromips(false),
6479         IsNan2008(false), IsSingleFloat(false), FloatABI(HardFloat),
6480         DspRev(NoDSP), HasMSA(false), HasFP64(false), ABI(ABIStr) {
6481     TheCXXABI.set(TargetCXXABI::GenericMIPS);
6482   }
6483 
isNaN2008Default() const6484   bool isNaN2008Default() const {
6485     return CPU == "mips32r6" || CPU == "mips64r6";
6486   }
6487 
isFP64Default() const6488   bool isFP64Default() const {
6489     return CPU == "mips32r6" || ABI == "n32" || ABI == "n64" || ABI == "64";
6490   }
6491 
isNan2008() const6492   bool isNan2008() const override {
6493     return IsNan2008;
6494   }
6495 
getABI() const6496   StringRef getABI() const override { return ABI; }
setCPU(const std::string & Name)6497   bool setCPU(const std::string &Name) override {
6498     bool IsMips32 = getTriple().getArch() == llvm::Triple::mips ||
6499                     getTriple().getArch() == llvm::Triple::mipsel;
6500     CPU = Name;
6501     return llvm::StringSwitch<bool>(Name)
6502         .Case("mips1", IsMips32)
6503         .Case("mips2", IsMips32)
6504         .Case("mips3", true)
6505         .Case("mips4", true)
6506         .Case("mips5", true)
6507         .Case("mips32", IsMips32)
6508         .Case("mips32r2", IsMips32)
6509         .Case("mips32r3", IsMips32)
6510         .Case("mips32r5", IsMips32)
6511         .Case("mips32r6", IsMips32)
6512         .Case("mips64", true)
6513         .Case("mips64r2", true)
6514         .Case("mips64r3", true)
6515         .Case("mips64r5", true)
6516         .Case("mips64r6", true)
6517         .Case("octeon", true)
6518         .Case("p5600", true)
6519         .Default(false);
6520   }
getCPU() const6521   const std::string& getCPU() const { return CPU; }
6522   bool
initFeatureMap(llvm::StringMap<bool> & Features,DiagnosticsEngine & Diags,StringRef CPU,const std::vector<std::string> & FeaturesVec) const6523   initFeatureMap(llvm::StringMap<bool> &Features, DiagnosticsEngine &Diags,
6524                  StringRef CPU,
6525                  const std::vector<std::string> &FeaturesVec) const override {
6526     if (CPU == "octeon")
6527       Features["mips64r2"] = Features["cnmips"] = true;
6528     else
6529       Features[CPU] = true;
6530     return TargetInfo::initFeatureMap(Features, Diags, CPU, FeaturesVec);
6531   }
6532 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const6533   void getTargetDefines(const LangOptions &Opts,
6534                         MacroBuilder &Builder) const override {
6535     Builder.defineMacro("__mips__");
6536     Builder.defineMacro("_mips");
6537     if (Opts.GNUMode)
6538       Builder.defineMacro("mips");
6539 
6540     Builder.defineMacro("__REGISTER_PREFIX__", "");
6541 
6542     switch (FloatABI) {
6543     case HardFloat:
6544       Builder.defineMacro("__mips_hard_float", Twine(1));
6545       break;
6546     case SoftFloat:
6547       Builder.defineMacro("__mips_soft_float", Twine(1));
6548       break;
6549     }
6550 
6551     if (IsSingleFloat)
6552       Builder.defineMacro("__mips_single_float", Twine(1));
6553 
6554     Builder.defineMacro("__mips_fpr", HasFP64 ? Twine(64) : Twine(32));
6555     Builder.defineMacro("_MIPS_FPSET",
6556                         Twine(32 / (HasFP64 || IsSingleFloat ? 1 : 2)));
6557 
6558     if (IsMips16)
6559       Builder.defineMacro("__mips16", Twine(1));
6560 
6561     if (IsMicromips)
6562       Builder.defineMacro("__mips_micromips", Twine(1));
6563 
6564     if (IsNan2008)
6565       Builder.defineMacro("__mips_nan2008", Twine(1));
6566 
6567     switch (DspRev) {
6568     default:
6569       break;
6570     case DSP1:
6571       Builder.defineMacro("__mips_dsp_rev", Twine(1));
6572       Builder.defineMacro("__mips_dsp", Twine(1));
6573       break;
6574     case DSP2:
6575       Builder.defineMacro("__mips_dsp_rev", Twine(2));
6576       Builder.defineMacro("__mips_dspr2", Twine(1));
6577       Builder.defineMacro("__mips_dsp", Twine(1));
6578       break;
6579     }
6580 
6581     if (HasMSA)
6582       Builder.defineMacro("__mips_msa", Twine(1));
6583 
6584     Builder.defineMacro("_MIPS_SZPTR", Twine(getPointerWidth(0)));
6585     Builder.defineMacro("_MIPS_SZINT", Twine(getIntWidth()));
6586     Builder.defineMacro("_MIPS_SZLONG", Twine(getLongWidth()));
6587 
6588     Builder.defineMacro("_MIPS_ARCH", "\"" + CPU + "\"");
6589     Builder.defineMacro("_MIPS_ARCH_" + StringRef(CPU).upper());
6590   }
6591 
getTargetBuiltins() const6592   ArrayRef<Builtin::Info> getTargetBuiltins() const override {
6593     return llvm::makeArrayRef(BuiltinInfo,
6594                           clang::Mips::LastTSBuiltin - Builtin::FirstTSBuiltin);
6595   }
hasFeature(StringRef Feature) const6596   bool hasFeature(StringRef Feature) const override {
6597     return llvm::StringSwitch<bool>(Feature)
6598       .Case("mips", true)
6599       .Case("fp64", HasFP64)
6600       .Default(false);
6601   }
getBuiltinVaListKind() const6602   BuiltinVaListKind getBuiltinVaListKind() const override {
6603     return TargetInfo::VoidPtrBuiltinVaList;
6604   }
getGCCRegNames() const6605   ArrayRef<const char *> getGCCRegNames() const override {
6606     static const char *const GCCRegNames[] = {
6607       // CPU register names
6608       // Must match second column of GCCRegAliases
6609       "$0",   "$1",   "$2",   "$3",   "$4",   "$5",   "$6",   "$7",
6610       "$8",   "$9",   "$10",  "$11",  "$12",  "$13",  "$14",  "$15",
6611       "$16",  "$17",  "$18",  "$19",  "$20",  "$21",  "$22",  "$23",
6612       "$24",  "$25",  "$26",  "$27",  "$28",  "$29",  "$30",  "$31",
6613       // Floating point register names
6614       "$f0",  "$f1",  "$f2",  "$f3",  "$f4",  "$f5",  "$f6",  "$f7",
6615       "$f8",  "$f9",  "$f10", "$f11", "$f12", "$f13", "$f14", "$f15",
6616       "$f16", "$f17", "$f18", "$f19", "$f20", "$f21", "$f22", "$f23",
6617       "$f24", "$f25", "$f26", "$f27", "$f28", "$f29", "$f30", "$f31",
6618       // Hi/lo and condition register names
6619       "hi",   "lo",   "",     "$fcc0","$fcc1","$fcc2","$fcc3","$fcc4",
6620       "$fcc5","$fcc6","$fcc7",
6621       // MSA register names
6622       "$w0",  "$w1",  "$w2",  "$w3",  "$w4",  "$w5",  "$w6",  "$w7",
6623       "$w8",  "$w9",  "$w10", "$w11", "$w12", "$w13", "$w14", "$w15",
6624       "$w16", "$w17", "$w18", "$w19", "$w20", "$w21", "$w22", "$w23",
6625       "$w24", "$w25", "$w26", "$w27", "$w28", "$w29", "$w30", "$w31",
6626       // MSA control register names
6627       "$msair",      "$msacsr", "$msaaccess", "$msasave", "$msamodify",
6628       "$msarequest", "$msamap", "$msaunmap"
6629     };
6630     return llvm::makeArrayRef(GCCRegNames);
6631   }
6632   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override = 0;
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & Info) const6633   bool validateAsmConstraint(const char *&Name,
6634                              TargetInfo::ConstraintInfo &Info) const override {
6635     switch (*Name) {
6636     default:
6637       return false;
6638     case 'r': // CPU registers.
6639     case 'd': // Equivalent to "r" unless generating MIPS16 code.
6640     case 'y': // Equivalent to "r", backward compatibility only.
6641     case 'f': // floating-point registers.
6642     case 'c': // $25 for indirect jumps
6643     case 'l': // lo register
6644     case 'x': // hilo register pair
6645       Info.setAllowsRegister();
6646       return true;
6647     case 'I': // Signed 16-bit constant
6648     case 'J': // Integer 0
6649     case 'K': // Unsigned 16-bit constant
6650     case 'L': // Signed 32-bit constant, lower 16-bit zeros (for lui)
6651     case 'M': // Constants not loadable via lui, addiu, or ori
6652     case 'N': // Constant -1 to -65535
6653     case 'O': // A signed 15-bit constant
6654     case 'P': // A constant between 1 go 65535
6655       return true;
6656     case 'R': // An address that can be used in a non-macro load or store
6657       Info.setAllowsMemory();
6658       return true;
6659     case 'Z':
6660       if (Name[1] == 'C') { // An address usable by ll, and sc.
6661         Info.setAllowsMemory();
6662         Name++; // Skip over 'Z'.
6663         return true;
6664       }
6665       return false;
6666     }
6667   }
6668 
convertConstraint(const char * & Constraint) const6669   std::string convertConstraint(const char *&Constraint) const override {
6670     std::string R;
6671     switch (*Constraint) {
6672     case 'Z': // Two-character constraint; add "^" hint for later parsing.
6673       if (Constraint[1] == 'C') {
6674         R = std::string("^") + std::string(Constraint, 2);
6675         Constraint++;
6676         return R;
6677       }
6678       break;
6679     }
6680     return TargetInfo::convertConstraint(Constraint);
6681   }
6682 
getClobbers() const6683   const char *getClobbers() const override {
6684     // In GCC, $1 is not widely used in generated code (it's used only in a few
6685     // specific situations), so there is no real need for users to add it to
6686     // the clobbers list if they want to use it in their inline assembly code.
6687     //
6688     // In LLVM, $1 is treated as a normal GPR and is always allocatable during
6689     // code generation, so using it in inline assembly without adding it to the
6690     // clobbers list can cause conflicts between the inline assembly code and
6691     // the surrounding generated code.
6692     //
6693     // Another problem is that LLVM is allowed to choose $1 for inline assembly
6694     // operands, which will conflict with the ".set at" assembler option (which
6695     // we use only for inline assembly, in order to maintain compatibility with
6696     // GCC) and will also conflict with the user's usage of $1.
6697     //
6698     // The easiest way to avoid these conflicts and keep $1 as an allocatable
6699     // register for generated code is to automatically clobber $1 for all inline
6700     // assembly code.
6701     //
6702     // FIXME: We should automatically clobber $1 only for inline assembly code
6703     // which actually uses it. This would allow LLVM to use $1 for inline
6704     // assembly operands if the user's assembly code doesn't use it.
6705     return "~{$1}";
6706   }
6707 
handleTargetFeatures(std::vector<std::string> & Features,DiagnosticsEngine & Diags)6708   bool handleTargetFeatures(std::vector<std::string> &Features,
6709                             DiagnosticsEngine &Diags) override {
6710     IsMips16 = false;
6711     IsMicromips = false;
6712     IsNan2008 = isNaN2008Default();
6713     IsSingleFloat = false;
6714     FloatABI = HardFloat;
6715     DspRev = NoDSP;
6716     HasFP64 = isFP64Default();
6717 
6718     for (const auto &Feature : Features) {
6719       if (Feature == "+single-float")
6720         IsSingleFloat = true;
6721       else if (Feature == "+soft-float")
6722         FloatABI = SoftFloat;
6723       else if (Feature == "+mips16")
6724         IsMips16 = true;
6725       else if (Feature == "+micromips")
6726         IsMicromips = true;
6727       else if (Feature == "+dsp")
6728         DspRev = std::max(DspRev, DSP1);
6729       else if (Feature == "+dspr2")
6730         DspRev = std::max(DspRev, DSP2);
6731       else if (Feature == "+msa")
6732         HasMSA = true;
6733       else if (Feature == "+fp64")
6734         HasFP64 = true;
6735       else if (Feature == "-fp64")
6736         HasFP64 = false;
6737       else if (Feature == "+nan2008")
6738         IsNan2008 = true;
6739       else if (Feature == "-nan2008")
6740         IsNan2008 = false;
6741     }
6742 
6743     setDataLayoutString();
6744 
6745     return true;
6746   }
6747 
getEHDataRegisterNumber(unsigned RegNo) const6748   int getEHDataRegisterNumber(unsigned RegNo) const override {
6749     if (RegNo == 0) return 4;
6750     if (RegNo == 1) return 5;
6751     return -1;
6752   }
6753 
isCLZForZeroUndef() const6754   bool isCLZForZeroUndef() const override { return false; }
6755 };
6756 
6757 const Builtin::Info MipsTargetInfoBase::BuiltinInfo[] = {
6758 #define BUILTIN(ID, TYPE, ATTRS) \
6759   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr },
6760 #define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) \
6761   { #ID, TYPE, ATTRS, HEADER, ALL_LANGUAGES, nullptr },
6762 #include "clang/Basic/BuiltinsMips.def"
6763 };
6764 
6765 class Mips32TargetInfoBase : public MipsTargetInfoBase {
6766 public:
Mips32TargetInfoBase(const llvm::Triple & Triple)6767   Mips32TargetInfoBase(const llvm::Triple &Triple)
6768       : MipsTargetInfoBase(Triple, "o32", "mips32r2") {
6769     SizeType = UnsignedInt;
6770     PtrDiffType = SignedInt;
6771     Int64Type = SignedLongLong;
6772     IntMaxType = Int64Type;
6773     MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 32;
6774   }
setABI(const std::string & Name)6775   bool setABI(const std::string &Name) override {
6776     if (Name == "o32" || Name == "eabi") {
6777       ABI = Name;
6778       return true;
6779     }
6780     return false;
6781   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const6782   void getTargetDefines(const LangOptions &Opts,
6783                         MacroBuilder &Builder) const override {
6784     MipsTargetInfoBase::getTargetDefines(Opts, Builder);
6785 
6786     Builder.defineMacro("__mips", "32");
6787     Builder.defineMacro("_MIPS_ISA", "_MIPS_ISA_MIPS32");
6788 
6789     const std::string& CPUStr = getCPU();
6790     if (CPUStr == "mips32")
6791       Builder.defineMacro("__mips_isa_rev", "1");
6792     else if (CPUStr == "mips32r2")
6793       Builder.defineMacro("__mips_isa_rev", "2");
6794     else if (CPUStr == "mips32r3")
6795       Builder.defineMacro("__mips_isa_rev", "3");
6796     else if (CPUStr == "mips32r5")
6797       Builder.defineMacro("__mips_isa_rev", "5");
6798     else if (CPUStr == "mips32r6")
6799       Builder.defineMacro("__mips_isa_rev", "6");
6800 
6801     if (ABI == "o32") {
6802       Builder.defineMacro("__mips_o32");
6803       Builder.defineMacro("_ABIO32", "1");
6804       Builder.defineMacro("_MIPS_SIM", "_ABIO32");
6805     }
6806     else if (ABI == "eabi")
6807       Builder.defineMacro("__mips_eabi");
6808     else
6809       llvm_unreachable("Invalid ABI for Mips32.");
6810   }
getGCCRegAliases() const6811   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override {
6812     static const TargetInfo::GCCRegAlias GCCRegAliases[] = {
6813       { { "at" },  "$1" },
6814       { { "v0" },  "$2" },
6815       { { "v1" },  "$3" },
6816       { { "a0" },  "$4" },
6817       { { "a1" },  "$5" },
6818       { { "a2" },  "$6" },
6819       { { "a3" },  "$7" },
6820       { { "t0" },  "$8" },
6821       { { "t1" },  "$9" },
6822       { { "t2" }, "$10" },
6823       { { "t3" }, "$11" },
6824       { { "t4" }, "$12" },
6825       { { "t5" }, "$13" },
6826       { { "t6" }, "$14" },
6827       { { "t7" }, "$15" },
6828       { { "s0" }, "$16" },
6829       { { "s1" }, "$17" },
6830       { { "s2" }, "$18" },
6831       { { "s3" }, "$19" },
6832       { { "s4" }, "$20" },
6833       { { "s5" }, "$21" },
6834       { { "s6" }, "$22" },
6835       { { "s7" }, "$23" },
6836       { { "t8" }, "$24" },
6837       { { "t9" }, "$25" },
6838       { { "k0" }, "$26" },
6839       { { "k1" }, "$27" },
6840       { { "gp" }, "$28" },
6841       { { "sp","$sp" }, "$29" },
6842       { { "fp","$fp" }, "$30" },
6843       { { "ra" }, "$31" }
6844     };
6845     return llvm::makeArrayRef(GCCRegAliases);
6846   }
6847 };
6848 
6849 class Mips32EBTargetInfo : public Mips32TargetInfoBase {
setDataLayoutString()6850   void setDataLayoutString() override {
6851     DataLayoutString = "E-m:m-p:32:32-i8:8:32-i16:16:32-i64:64-n32-S64";
6852   }
6853 
6854 public:
Mips32EBTargetInfo(const llvm::Triple & Triple)6855   Mips32EBTargetInfo(const llvm::Triple &Triple)
6856       : Mips32TargetInfoBase(Triple) {
6857   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const6858   void getTargetDefines(const LangOptions &Opts,
6859                         MacroBuilder &Builder) const override {
6860     DefineStd(Builder, "MIPSEB", Opts);
6861     Builder.defineMacro("_MIPSEB");
6862     Mips32TargetInfoBase::getTargetDefines(Opts, Builder);
6863   }
6864 };
6865 
6866 class Mips32ELTargetInfo : public Mips32TargetInfoBase {
setDataLayoutString()6867   void setDataLayoutString() override {
6868     DataLayoutString = "e-m:m-p:32:32-i8:8:32-i16:16:32-i64:64-n32-S64";
6869   }
6870 
6871 public:
Mips32ELTargetInfo(const llvm::Triple & Triple)6872   Mips32ELTargetInfo(const llvm::Triple &Triple)
6873       : Mips32TargetInfoBase(Triple) {
6874     BigEndian = false;
6875   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const6876   void getTargetDefines(const LangOptions &Opts,
6877                         MacroBuilder &Builder) const override {
6878     DefineStd(Builder, "MIPSEL", Opts);
6879     Builder.defineMacro("_MIPSEL");
6880     Mips32TargetInfoBase::getTargetDefines(Opts, Builder);
6881   }
6882 };
6883 
6884 class Mips64TargetInfoBase : public MipsTargetInfoBase {
6885 public:
Mips64TargetInfoBase(const llvm::Triple & Triple)6886   Mips64TargetInfoBase(const llvm::Triple &Triple)
6887       : MipsTargetInfoBase(Triple, "n64", "mips64r2") {
6888     LongDoubleWidth = LongDoubleAlign = 128;
6889     LongDoubleFormat = &llvm::APFloat::IEEEquad;
6890     if (getTriple().getOS() == llvm::Triple::FreeBSD) {
6891       LongDoubleWidth = LongDoubleAlign = 64;
6892       LongDoubleFormat = &llvm::APFloat::IEEEdouble;
6893     }
6894     setN64ABITypes();
6895     SuitableAlign = 128;
6896     MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 64;
6897   }
6898 
setN64ABITypes()6899   void setN64ABITypes() {
6900     LongWidth = LongAlign = 64;
6901     PointerWidth = PointerAlign = 64;
6902     SizeType = UnsignedLong;
6903     PtrDiffType = SignedLong;
6904     Int64Type = SignedLong;
6905     IntMaxType = Int64Type;
6906   }
6907 
setN32ABITypes()6908   void setN32ABITypes() {
6909     LongWidth = LongAlign = 32;
6910     PointerWidth = PointerAlign = 32;
6911     SizeType = UnsignedInt;
6912     PtrDiffType = SignedInt;
6913     Int64Type = SignedLongLong;
6914     IntMaxType = Int64Type;
6915   }
6916 
setABI(const std::string & Name)6917   bool setABI(const std::string &Name) override {
6918     if (Name == "n32") {
6919       setN32ABITypes();
6920       ABI = Name;
6921       return true;
6922     }
6923     if (Name == "n64") {
6924       setN64ABITypes();
6925       ABI = Name;
6926       return true;
6927     }
6928     return false;
6929   }
6930 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const6931   void getTargetDefines(const LangOptions &Opts,
6932                         MacroBuilder &Builder) const override {
6933     MipsTargetInfoBase::getTargetDefines(Opts, Builder);
6934 
6935     Builder.defineMacro("__mips", "64");
6936     Builder.defineMacro("__mips64");
6937     Builder.defineMacro("__mips64__");
6938     Builder.defineMacro("_MIPS_ISA", "_MIPS_ISA_MIPS64");
6939 
6940     const std::string& CPUStr = getCPU();
6941     if (CPUStr == "mips64")
6942       Builder.defineMacro("__mips_isa_rev", "1");
6943     else if (CPUStr == "mips64r2")
6944       Builder.defineMacro("__mips_isa_rev", "2");
6945     else if (CPUStr == "mips64r3")
6946       Builder.defineMacro("__mips_isa_rev", "3");
6947     else if (CPUStr == "mips64r5")
6948       Builder.defineMacro("__mips_isa_rev", "5");
6949     else if (CPUStr == "mips64r6")
6950       Builder.defineMacro("__mips_isa_rev", "6");
6951 
6952     if (ABI == "n32") {
6953       Builder.defineMacro("__mips_n32");
6954       Builder.defineMacro("_ABIN32", "2");
6955       Builder.defineMacro("_MIPS_SIM", "_ABIN32");
6956     }
6957     else if (ABI == "n64") {
6958       Builder.defineMacro("__mips_n64");
6959       Builder.defineMacro("_ABI64", "3");
6960       Builder.defineMacro("_MIPS_SIM", "_ABI64");
6961     }
6962     else
6963       llvm_unreachable("Invalid ABI for Mips64.");
6964   }
getGCCRegAliases() const6965   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override {
6966     static const TargetInfo::GCCRegAlias GCCRegAliases[] = {
6967       { { "at" },  "$1" },
6968       { { "v0" },  "$2" },
6969       { { "v1" },  "$3" },
6970       { { "a0" },  "$4" },
6971       { { "a1" },  "$5" },
6972       { { "a2" },  "$6" },
6973       { { "a3" },  "$7" },
6974       { { "a4" },  "$8" },
6975       { { "a5" },  "$9" },
6976       { { "a6" }, "$10" },
6977       { { "a7" }, "$11" },
6978       { { "t0" }, "$12" },
6979       { { "t1" }, "$13" },
6980       { { "t2" }, "$14" },
6981       { { "t3" }, "$15" },
6982       { { "s0" }, "$16" },
6983       { { "s1" }, "$17" },
6984       { { "s2" }, "$18" },
6985       { { "s3" }, "$19" },
6986       { { "s4" }, "$20" },
6987       { { "s5" }, "$21" },
6988       { { "s6" }, "$22" },
6989       { { "s7" }, "$23" },
6990       { { "t8" }, "$24" },
6991       { { "t9" }, "$25" },
6992       { { "k0" }, "$26" },
6993       { { "k1" }, "$27" },
6994       { { "gp" }, "$28" },
6995       { { "sp","$sp" }, "$29" },
6996       { { "fp","$fp" }, "$30" },
6997       { { "ra" }, "$31" }
6998     };
6999     return llvm::makeArrayRef(GCCRegAliases);
7000   }
7001 
hasInt128Type() const7002   bool hasInt128Type() const override { return true; }
7003 };
7004 
7005 class Mips64EBTargetInfo : public Mips64TargetInfoBase {
setDataLayoutString()7006   void setDataLayoutString() override {
7007     if (ABI == "n32")
7008       DataLayoutString = "E-m:m-p:32:32-i8:8:32-i16:16:32-i64:64-n32:64-S128";
7009     else
7010       DataLayoutString = "E-m:m-i8:8:32-i16:16:32-i64:64-n32:64-S128";
7011 
7012   }
7013 
7014 public:
Mips64EBTargetInfo(const llvm::Triple & Triple)7015   Mips64EBTargetInfo(const llvm::Triple &Triple)
7016       : Mips64TargetInfoBase(Triple) {}
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const7017   void getTargetDefines(const LangOptions &Opts,
7018                         MacroBuilder &Builder) const override {
7019     DefineStd(Builder, "MIPSEB", Opts);
7020     Builder.defineMacro("_MIPSEB");
7021     Mips64TargetInfoBase::getTargetDefines(Opts, Builder);
7022   }
7023 };
7024 
7025 class Mips64ELTargetInfo : public Mips64TargetInfoBase {
setDataLayoutString()7026   void setDataLayoutString() override {
7027     if (ABI == "n32")
7028       DataLayoutString = "e-m:m-p:32:32-i8:8:32-i16:16:32-i64:64-n32:64-S128";
7029     else
7030       DataLayoutString = "e-m:m-i8:8:32-i16:16:32-i64:64-n32:64-S128";
7031   }
7032 public:
Mips64ELTargetInfo(const llvm::Triple & Triple)7033   Mips64ELTargetInfo(const llvm::Triple &Triple)
7034       : Mips64TargetInfoBase(Triple) {
7035     // Default ABI is n64.
7036     BigEndian = false;
7037   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const7038   void getTargetDefines(const LangOptions &Opts,
7039                         MacroBuilder &Builder) const override {
7040     DefineStd(Builder, "MIPSEL", Opts);
7041     Builder.defineMacro("_MIPSEL");
7042     Mips64TargetInfoBase::getTargetDefines(Opts, Builder);
7043   }
7044 };
7045 
7046 class PNaClTargetInfo : public TargetInfo {
7047 public:
PNaClTargetInfo(const llvm::Triple & Triple)7048   PNaClTargetInfo(const llvm::Triple &Triple) : TargetInfo(Triple) {
7049     BigEndian = false;
7050     this->UserLabelPrefix = "";
7051     this->LongAlign = 32;
7052     this->LongWidth = 32;
7053     this->PointerAlign = 32;
7054     this->PointerWidth = 32;
7055     this->IntMaxType = TargetInfo::SignedLongLong;
7056     this->Int64Type = TargetInfo::SignedLongLong;
7057     this->DoubleAlign = 64;
7058     this->LongDoubleWidth = 64;
7059     this->LongDoubleAlign = 64;
7060     this->SizeType = TargetInfo::UnsignedInt;
7061     this->PtrDiffType = TargetInfo::SignedInt;
7062     this->IntPtrType = TargetInfo::SignedInt;
7063     this->RegParmMax = 0; // Disallow regparm
7064   }
7065 
getArchDefines(const LangOptions & Opts,MacroBuilder & Builder) const7066   void getArchDefines(const LangOptions &Opts, MacroBuilder &Builder) const {
7067     Builder.defineMacro("__le32__");
7068     Builder.defineMacro("__pnacl__");
7069   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const7070   void getTargetDefines(const LangOptions &Opts,
7071                         MacroBuilder &Builder) const override {
7072     getArchDefines(Opts, Builder);
7073   }
hasFeature(StringRef Feature) const7074   bool hasFeature(StringRef Feature) const override {
7075     return Feature == "pnacl";
7076   }
getTargetBuiltins() const7077   ArrayRef<Builtin::Info> getTargetBuiltins() const override { return None; }
getBuiltinVaListKind() const7078   BuiltinVaListKind getBuiltinVaListKind() const override {
7079     return TargetInfo::PNaClABIBuiltinVaList;
7080   }
7081   ArrayRef<const char *> getGCCRegNames() const override;
7082   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override;
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & Info) const7083   bool validateAsmConstraint(const char *&Name,
7084                              TargetInfo::ConstraintInfo &Info) const override {
7085     return false;
7086   }
7087 
getClobbers() const7088   const char *getClobbers() const override {
7089     return "";
7090   }
7091 };
7092 
getGCCRegNames() const7093 ArrayRef<const char *> PNaClTargetInfo::getGCCRegNames() const {
7094   return None;
7095 }
7096 
getGCCRegAliases() const7097 ArrayRef<TargetInfo::GCCRegAlias> PNaClTargetInfo::getGCCRegAliases() const {
7098   return None;
7099 }
7100 
7101 // We attempt to use PNaCl (le32) frontend and Mips32EL backend.
7102 class NaClMips32ELTargetInfo : public Mips32ELTargetInfo {
7103 public:
NaClMips32ELTargetInfo(const llvm::Triple & Triple)7104   NaClMips32ELTargetInfo(const llvm::Triple &Triple) :
7105     Mips32ELTargetInfo(Triple) {
7106   }
7107 
getBuiltinVaListKind() const7108   BuiltinVaListKind getBuiltinVaListKind() const override {
7109     return TargetInfo::PNaClABIBuiltinVaList;
7110   }
7111 };
7112 
7113 class Le64TargetInfo : public TargetInfo {
7114   static const Builtin::Info BuiltinInfo[];
7115 
7116 public:
Le64TargetInfo(const llvm::Triple & Triple)7117   Le64TargetInfo(const llvm::Triple &Triple) : TargetInfo(Triple) {
7118     BigEndian = false;
7119     NoAsmVariants = true;
7120     LongWidth = LongAlign = PointerWidth = PointerAlign = 64;
7121     MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 64;
7122     DataLayoutString = "e-m:e-v128:32-v16:16-v32:32-v96:32-n8:16:32:64-S128";
7123   }
7124 
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const7125   void getTargetDefines(const LangOptions &Opts,
7126                         MacroBuilder &Builder) const override {
7127     DefineStd(Builder, "unix", Opts);
7128     defineCPUMacros(Builder, "le64", /*Tuning=*/false);
7129     Builder.defineMacro("__ELF__");
7130   }
getTargetBuiltins() const7131   ArrayRef<Builtin::Info> getTargetBuiltins() const override {
7132     return llvm::makeArrayRef(BuiltinInfo,
7133                           clang::Le64::LastTSBuiltin - Builtin::FirstTSBuiltin);
7134   }
getBuiltinVaListKind() const7135   BuiltinVaListKind getBuiltinVaListKind() const override {
7136     return TargetInfo::PNaClABIBuiltinVaList;
7137   }
getClobbers() const7138   const char *getClobbers() const override { return ""; }
getGCCRegNames() const7139   ArrayRef<const char *> getGCCRegNames() const override {
7140     return None;
7141   }
getGCCRegAliases() const7142   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override {
7143     return None;
7144   }
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & Info) const7145   bool validateAsmConstraint(const char *&Name,
7146                              TargetInfo::ConstraintInfo &Info) const override {
7147     return false;
7148   }
7149 
hasProtectedVisibility() const7150   bool hasProtectedVisibility() const override { return false; }
7151 };
7152 
7153 class WebAssemblyTargetInfo : public TargetInfo {
7154   static const Builtin::Info BuiltinInfo[];
7155 
7156   enum SIMDEnum {
7157     NoSIMD,
7158     SIMD128,
7159   } SIMDLevel;
7160 
7161 public:
WebAssemblyTargetInfo(const llvm::Triple & T)7162   explicit WebAssemblyTargetInfo(const llvm::Triple &T)
7163       : TargetInfo(T), SIMDLevel(NoSIMD) {
7164     BigEndian = false;
7165     NoAsmVariants = true;
7166     SuitableAlign = 128;
7167     LargeArrayMinWidth = 128;
7168     LargeArrayAlign = 128;
7169     SimdDefaultAlign = 128;
7170     SigAtomicType = SignedLong;
7171     LongDoubleWidth = LongDoubleAlign = 128;
7172     LongDoubleFormat = &llvm::APFloat::IEEEquad;
7173   }
7174 
7175 protected:
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const7176   void getTargetDefines(const LangOptions &Opts,
7177                         MacroBuilder &Builder) const override {
7178     defineCPUMacros(Builder, "wasm", /*Tuning=*/false);
7179     if (SIMDLevel >= SIMD128)
7180       Builder.defineMacro("__wasm_simd128__");
7181   }
7182 
7183 private:
7184   bool
initFeatureMap(llvm::StringMap<bool> & Features,DiagnosticsEngine & Diags,StringRef CPU,const std::vector<std::string> & FeaturesVec) const7185   initFeatureMap(llvm::StringMap<bool> &Features, DiagnosticsEngine &Diags,
7186                  StringRef CPU,
7187                  const std::vector<std::string> &FeaturesVec) const override {
7188     if (CPU == "bleeding-edge")
7189       Features["simd128"] = true;
7190     return TargetInfo::initFeatureMap(Features, Diags, CPU, FeaturesVec);
7191   }
hasFeature(StringRef Feature) const7192   bool hasFeature(StringRef Feature) const final {
7193     return llvm::StringSwitch<bool>(Feature)
7194         .Case("simd128", SIMDLevel >= SIMD128)
7195         .Default(false);
7196   }
handleTargetFeatures(std::vector<std::string> & Features,DiagnosticsEngine & Diags)7197   bool handleTargetFeatures(std::vector<std::string> &Features,
7198                             DiagnosticsEngine &Diags) final {
7199     for (const auto &Feature : Features) {
7200       if (Feature == "+simd128") {
7201         SIMDLevel = std::max(SIMDLevel, SIMD128);
7202         continue;
7203       }
7204       if (Feature == "-simd128") {
7205         SIMDLevel = std::min(SIMDLevel, SIMDEnum(SIMD128 - 1));
7206         continue;
7207       }
7208 
7209       Diags.Report(diag::err_opt_not_valid_with_opt) << Feature
7210                                                      << "-target-feature";
7211       return false;
7212     }
7213     return true;
7214   }
setCPU(const std::string & Name)7215   bool setCPU(const std::string &Name) final {
7216     return llvm::StringSwitch<bool>(Name)
7217               .Case("mvp",           true)
7218               .Case("bleeding-edge", true)
7219               .Case("generic",       true)
7220               .Default(false);
7221   }
getTargetBuiltins() const7222   ArrayRef<Builtin::Info> getTargetBuiltins() const final {
7223     return llvm::makeArrayRef(BuiltinInfo,
7224                    clang::WebAssembly::LastTSBuiltin - Builtin::FirstTSBuiltin);
7225   }
getBuiltinVaListKind() const7226   BuiltinVaListKind getBuiltinVaListKind() const final {
7227     return VoidPtrBuiltinVaList;
7228   }
getGCCRegNames() const7229   ArrayRef<const char *> getGCCRegNames() const final {
7230     return None;
7231   }
getGCCRegAliases() const7232   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const final {
7233     return None;
7234   }
7235   bool
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & Info) const7236   validateAsmConstraint(const char *&Name,
7237                         TargetInfo::ConstraintInfo &Info) const final {
7238     return false;
7239   }
getClobbers() const7240   const char *getClobbers() const final { return ""; }
isCLZForZeroUndef() const7241   bool isCLZForZeroUndef() const final { return false; }
hasInt128Type() const7242   bool hasInt128Type() const final { return true; }
getIntTypeByWidth(unsigned BitWidth,bool IsSigned) const7243   IntType getIntTypeByWidth(unsigned BitWidth,
7244                             bool IsSigned) const final {
7245     // WebAssembly prefers long long for explicitly 64-bit integers.
7246     return BitWidth == 64 ? (IsSigned ? SignedLongLong : UnsignedLongLong)
7247                           : TargetInfo::getIntTypeByWidth(BitWidth, IsSigned);
7248   }
getLeastIntTypeByWidth(unsigned BitWidth,bool IsSigned) const7249   IntType getLeastIntTypeByWidth(unsigned BitWidth,
7250                                  bool IsSigned) const final {
7251     // WebAssembly uses long long for int_least64_t and int_fast64_t.
7252     return BitWidth == 64
7253                ? (IsSigned ? SignedLongLong : UnsignedLongLong)
7254                : TargetInfo::getLeastIntTypeByWidth(BitWidth, IsSigned);
7255   }
7256 };
7257 
7258 const Builtin::Info WebAssemblyTargetInfo::BuiltinInfo[] = {
7259 #define BUILTIN(ID, TYPE, ATTRS) \
7260   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr },
7261 #define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) \
7262   { #ID, TYPE, ATTRS, HEADER, ALL_LANGUAGES, nullptr },
7263 #include "clang/Basic/BuiltinsWebAssembly.def"
7264 };
7265 
7266 class WebAssembly32TargetInfo : public WebAssemblyTargetInfo {
7267 public:
WebAssembly32TargetInfo(const llvm::Triple & T)7268   explicit WebAssembly32TargetInfo(const llvm::Triple &T)
7269       : WebAssemblyTargetInfo(T) {
7270     MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 32;
7271     DataLayoutString = "e-p:32:32-i64:64-n32:64-S128";
7272   }
7273 
7274 protected:
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const7275   void getTargetDefines(const LangOptions &Opts,
7276                         MacroBuilder &Builder) const override {
7277     WebAssemblyTargetInfo::getTargetDefines(Opts, Builder);
7278     defineCPUMacros(Builder, "wasm32", /*Tuning=*/false);
7279   }
7280 };
7281 
7282 class WebAssembly64TargetInfo : public WebAssemblyTargetInfo {
7283 public:
WebAssembly64TargetInfo(const llvm::Triple & T)7284   explicit WebAssembly64TargetInfo(const llvm::Triple &T)
7285       : WebAssemblyTargetInfo(T) {
7286     LongAlign = LongWidth = 64;
7287     PointerAlign = PointerWidth = 64;
7288     MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 64;
7289     DataLayoutString = "e-p:64:64-i64:64-n32:64-S128";
7290   }
7291 
7292 protected:
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const7293   void getTargetDefines(const LangOptions &Opts,
7294                         MacroBuilder &Builder) const override {
7295     WebAssemblyTargetInfo::getTargetDefines(Opts, Builder);
7296     defineCPUMacros(Builder, "wasm64", /*Tuning=*/false);
7297   }
7298 };
7299 
7300 const Builtin::Info Le64TargetInfo::BuiltinInfo[] = {
7301 #define BUILTIN(ID, TYPE, ATTRS)                                               \
7302   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr },
7303 #include "clang/Basic/BuiltinsLe64.def"
7304 };
7305 
7306 static const unsigned SPIRAddrSpaceMap[] = {
7307     1, // opencl_global
7308     3, // opencl_local
7309     2, // opencl_constant
7310     4, // opencl_generic
7311     0, // cuda_device
7312     0, // cuda_constant
7313     0  // cuda_shared
7314 };
7315 class SPIRTargetInfo : public TargetInfo {
7316 public:
SPIRTargetInfo(const llvm::Triple & Triple)7317   SPIRTargetInfo(const llvm::Triple &Triple) : TargetInfo(Triple) {
7318     assert(getTriple().getOS() == llvm::Triple::UnknownOS &&
7319            "SPIR target must use unknown OS");
7320     assert(getTriple().getEnvironment() == llvm::Triple::UnknownEnvironment &&
7321            "SPIR target must use unknown environment type");
7322     BigEndian = false;
7323     TLSSupported = false;
7324     LongWidth = LongAlign = 64;
7325     AddrSpaceMap = &SPIRAddrSpaceMap;
7326     UseAddrSpaceMapMangling = true;
7327     // Define available target features
7328     // These must be defined in sorted order!
7329     NoAsmVariants = true;
7330   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const7331   void getTargetDefines(const LangOptions &Opts,
7332                         MacroBuilder &Builder) const override {
7333     DefineStd(Builder, "SPIR", Opts);
7334   }
hasFeature(StringRef Feature) const7335   bool hasFeature(StringRef Feature) const override {
7336     return Feature == "spir";
7337   }
7338 
getTargetBuiltins() const7339   ArrayRef<Builtin::Info> getTargetBuiltins() const override { return None; }
getClobbers() const7340   const char *getClobbers() const override { return ""; }
getGCCRegNames() const7341   ArrayRef<const char *> getGCCRegNames() const override { return None; }
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & info) const7342   bool validateAsmConstraint(const char *&Name,
7343                              TargetInfo::ConstraintInfo &info) const override {
7344     return true;
7345   }
getGCCRegAliases() const7346   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override {
7347     return None;
7348   }
getBuiltinVaListKind() const7349   BuiltinVaListKind getBuiltinVaListKind() const override {
7350     return TargetInfo::VoidPtrBuiltinVaList;
7351   }
7352 
checkCallingConvention(CallingConv CC) const7353   CallingConvCheckResult checkCallingConvention(CallingConv CC) const override {
7354     return (CC == CC_SpirFunction || CC == CC_SpirKernel) ? CCCR_OK
7355                                                           : CCCR_Warning;
7356   }
7357 
getDefaultCallingConv(CallingConvMethodType MT) const7358   CallingConv getDefaultCallingConv(CallingConvMethodType MT) const override {
7359     return CC_SpirFunction;
7360   }
7361 };
7362 
7363 class SPIR32TargetInfo : public SPIRTargetInfo {
7364 public:
SPIR32TargetInfo(const llvm::Triple & Triple)7365   SPIR32TargetInfo(const llvm::Triple &Triple) : SPIRTargetInfo(Triple) {
7366     PointerWidth = PointerAlign = 32;
7367     SizeType = TargetInfo::UnsignedInt;
7368     PtrDiffType = IntPtrType = TargetInfo::SignedInt;
7369     DataLayoutString = "e-p:32:32-i64:64-v16:16-v24:32-v32:32-v48:64-"
7370                        "v96:128-v192:256-v256:256-v512:512-v1024:1024";
7371   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const7372   void getTargetDefines(const LangOptions &Opts,
7373                         MacroBuilder &Builder) const override {
7374     DefineStd(Builder, "SPIR32", Opts);
7375   }
7376 };
7377 
7378 class SPIR64TargetInfo : public SPIRTargetInfo {
7379 public:
SPIR64TargetInfo(const llvm::Triple & Triple)7380   SPIR64TargetInfo(const llvm::Triple &Triple) : SPIRTargetInfo(Triple) {
7381     PointerWidth = PointerAlign = 64;
7382     SizeType = TargetInfo::UnsignedLong;
7383     PtrDiffType = IntPtrType = TargetInfo::SignedLong;
7384     DataLayoutString = "e-i64:64-v16:16-v24:32-v32:32-v48:64-"
7385                        "v96:128-v192:256-v256:256-v512:512-v1024:1024";
7386   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const7387   void getTargetDefines(const LangOptions &Opts,
7388                         MacroBuilder &Builder) const override {
7389     DefineStd(Builder, "SPIR64", Opts);
7390   }
7391 };
7392 
7393 class XCoreTargetInfo : public TargetInfo {
7394   static const Builtin::Info BuiltinInfo[];
7395 public:
XCoreTargetInfo(const llvm::Triple & Triple)7396   XCoreTargetInfo(const llvm::Triple &Triple) : TargetInfo(Triple) {
7397     BigEndian = false;
7398     NoAsmVariants = true;
7399     LongLongAlign = 32;
7400     SuitableAlign = 32;
7401     DoubleAlign = LongDoubleAlign = 32;
7402     SizeType = UnsignedInt;
7403     PtrDiffType = SignedInt;
7404     IntPtrType = SignedInt;
7405     WCharType = UnsignedChar;
7406     WIntType = UnsignedInt;
7407     UseZeroLengthBitfieldAlignment = true;
7408     DataLayoutString = "e-m:e-p:32:32-i1:8:32-i8:8:32-i16:16:32-i64:32"
7409                        "-f64:32-a:0:32-n32";
7410   }
getTargetDefines(const LangOptions & Opts,MacroBuilder & Builder) const7411   void getTargetDefines(const LangOptions &Opts,
7412                         MacroBuilder &Builder) const override {
7413     Builder.defineMacro("__XS1B__");
7414   }
getTargetBuiltins() const7415   ArrayRef<Builtin::Info> getTargetBuiltins() const override {
7416     return llvm::makeArrayRef(BuiltinInfo,
7417                            clang::XCore::LastTSBuiltin-Builtin::FirstTSBuiltin);
7418   }
getBuiltinVaListKind() const7419   BuiltinVaListKind getBuiltinVaListKind() const override {
7420     return TargetInfo::VoidPtrBuiltinVaList;
7421   }
getClobbers() const7422   const char *getClobbers() const override {
7423     return "";
7424   }
getGCCRegNames() const7425   ArrayRef<const char *> getGCCRegNames() const override {
7426     static const char * const GCCRegNames[] = {
7427       "r0",   "r1",   "r2",   "r3",   "r4",   "r5",   "r6",   "r7",
7428       "r8",   "r9",   "r10",  "r11",  "cp",   "dp",   "sp",   "lr"
7429     };
7430     return llvm::makeArrayRef(GCCRegNames);
7431   }
getGCCRegAliases() const7432   ArrayRef<TargetInfo::GCCRegAlias> getGCCRegAliases() const override {
7433     return None;
7434   }
validateAsmConstraint(const char * & Name,TargetInfo::ConstraintInfo & Info) const7435   bool validateAsmConstraint(const char *&Name,
7436                              TargetInfo::ConstraintInfo &Info) const override {
7437     return false;
7438   }
getEHDataRegisterNumber(unsigned RegNo) const7439   int getEHDataRegisterNumber(unsigned RegNo) const override {
7440     // R0=ExceptionPointerRegister R1=ExceptionSelectorRegister
7441     return (RegNo < 2)? RegNo : -1;
7442   }
7443 };
7444 
7445 const Builtin::Info XCoreTargetInfo::BuiltinInfo[] = {
7446 #define BUILTIN(ID, TYPE, ATTRS) \
7447   { #ID, TYPE, ATTRS, nullptr, ALL_LANGUAGES, nullptr },
7448 #define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) \
7449   { #ID, TYPE, ATTRS, HEADER, ALL_LANGUAGES, nullptr },
7450 #include "clang/Basic/BuiltinsXCore.def"
7451 };
7452 
7453 // x86_32 Android target
7454 class AndroidX86_32TargetInfo : public LinuxTargetInfo<X86_32TargetInfo> {
7455 public:
AndroidX86_32TargetInfo(const llvm::Triple & Triple)7456   AndroidX86_32TargetInfo(const llvm::Triple &Triple)
7457       : LinuxTargetInfo<X86_32TargetInfo>(Triple) {
7458     SuitableAlign = 32;
7459     LongDoubleWidth = 64;
7460     LongDoubleFormat = &llvm::APFloat::IEEEdouble;
7461   }
7462 };
7463 
7464 // x86_64 Android target
7465 class AndroidX86_64TargetInfo : public LinuxTargetInfo<X86_64TargetInfo> {
7466 public:
AndroidX86_64TargetInfo(const llvm::Triple & Triple)7467   AndroidX86_64TargetInfo(const llvm::Triple &Triple)
7468       : LinuxTargetInfo<X86_64TargetInfo>(Triple) {
7469     LongDoubleFormat = &llvm::APFloat::IEEEquad;
7470   }
7471 
useFloat128ManglingForLongDouble() const7472   bool useFloat128ManglingForLongDouble() const override {
7473     return true;
7474   }
7475 };
7476 } // end anonymous namespace
7477 
7478 //===----------------------------------------------------------------------===//
7479 // Driver code
7480 //===----------------------------------------------------------------------===//
7481 
AllocateTarget(const llvm::Triple & Triple)7482 static TargetInfo *AllocateTarget(const llvm::Triple &Triple) {
7483   llvm::Triple::OSType os = Triple.getOS();
7484 
7485   switch (Triple.getArch()) {
7486   default:
7487     return nullptr;
7488 
7489   case llvm::Triple::xcore:
7490     return new XCoreTargetInfo(Triple);
7491 
7492   case llvm::Triple::hexagon:
7493     return new HexagonTargetInfo(Triple);
7494 
7495   case llvm::Triple::aarch64:
7496     if (Triple.isOSDarwin())
7497       return new DarwinAArch64TargetInfo(Triple);
7498 
7499     switch (os) {
7500     case llvm::Triple::CloudABI:
7501       return new CloudABITargetInfo<AArch64leTargetInfo>(Triple);
7502     case llvm::Triple::FreeBSD:
7503       return new FreeBSDTargetInfo<AArch64leTargetInfo>(Triple);
7504     case llvm::Triple::Linux:
7505       return new LinuxTargetInfo<AArch64leTargetInfo>(Triple);
7506     case llvm::Triple::NetBSD:
7507       return new NetBSDTargetInfo<AArch64leTargetInfo>(Triple);
7508     default:
7509       return new AArch64leTargetInfo(Triple);
7510     }
7511 
7512   case llvm::Triple::aarch64_be:
7513     switch (os) {
7514     case llvm::Triple::FreeBSD:
7515       return new FreeBSDTargetInfo<AArch64beTargetInfo>(Triple);
7516     case llvm::Triple::Linux:
7517       return new LinuxTargetInfo<AArch64beTargetInfo>(Triple);
7518     case llvm::Triple::NetBSD:
7519       return new NetBSDTargetInfo<AArch64beTargetInfo>(Triple);
7520     default:
7521       return new AArch64beTargetInfo(Triple);
7522     }
7523 
7524   case llvm::Triple::arm:
7525   case llvm::Triple::thumb:
7526     if (Triple.isOSBinFormatMachO())
7527       return new DarwinARMTargetInfo(Triple);
7528 
7529     switch (os) {
7530     case llvm::Triple::Linux:
7531       return new LinuxTargetInfo<ARMleTargetInfo>(Triple);
7532     case llvm::Triple::FreeBSD:
7533       return new FreeBSDTargetInfo<ARMleTargetInfo>(Triple);
7534     case llvm::Triple::NetBSD:
7535       return new NetBSDTargetInfo<ARMleTargetInfo>(Triple);
7536     case llvm::Triple::OpenBSD:
7537       return new OpenBSDTargetInfo<ARMleTargetInfo>(Triple);
7538     case llvm::Triple::Bitrig:
7539       return new BitrigTargetInfo<ARMleTargetInfo>(Triple);
7540     case llvm::Triple::RTEMS:
7541       return new RTEMSTargetInfo<ARMleTargetInfo>(Triple);
7542     case llvm::Triple::NaCl:
7543       return new NaClTargetInfo<ARMleTargetInfo>(Triple);
7544     case llvm::Triple::Win32:
7545       switch (Triple.getEnvironment()) {
7546       case llvm::Triple::Cygnus:
7547         return new CygwinARMTargetInfo(Triple);
7548       case llvm::Triple::GNU:
7549         return new MinGWARMTargetInfo(Triple);
7550       case llvm::Triple::Itanium:
7551         return new ItaniumWindowsARMleTargetInfo(Triple);
7552       case llvm::Triple::MSVC:
7553       default: // Assume MSVC for unknown environments
7554         return new MicrosoftARMleTargetInfo(Triple);
7555       }
7556     default:
7557       return new ARMleTargetInfo(Triple);
7558     }
7559 
7560   case llvm::Triple::armeb:
7561   case llvm::Triple::thumbeb:
7562     if (Triple.isOSDarwin())
7563       return new DarwinARMTargetInfo(Triple);
7564 
7565     switch (os) {
7566     case llvm::Triple::Linux:
7567       return new LinuxTargetInfo<ARMbeTargetInfo>(Triple);
7568     case llvm::Triple::FreeBSD:
7569       return new FreeBSDTargetInfo<ARMbeTargetInfo>(Triple);
7570     case llvm::Triple::NetBSD:
7571       return new NetBSDTargetInfo<ARMbeTargetInfo>(Triple);
7572     case llvm::Triple::OpenBSD:
7573       return new OpenBSDTargetInfo<ARMbeTargetInfo>(Triple);
7574     case llvm::Triple::Bitrig:
7575       return new BitrigTargetInfo<ARMbeTargetInfo>(Triple);
7576     case llvm::Triple::RTEMS:
7577       return new RTEMSTargetInfo<ARMbeTargetInfo>(Triple);
7578     case llvm::Triple::NaCl:
7579       return new NaClTargetInfo<ARMbeTargetInfo>(Triple);
7580     default:
7581       return new ARMbeTargetInfo(Triple);
7582     }
7583 
7584   case llvm::Triple::bpfeb:
7585   case llvm::Triple::bpfel:
7586     return new BPFTargetInfo(Triple);
7587 
7588   case llvm::Triple::msp430:
7589     return new MSP430TargetInfo(Triple);
7590 
7591   case llvm::Triple::mips:
7592     switch (os) {
7593     case llvm::Triple::Linux:
7594       return new LinuxTargetInfo<Mips32EBTargetInfo>(Triple);
7595     case llvm::Triple::RTEMS:
7596       return new RTEMSTargetInfo<Mips32EBTargetInfo>(Triple);
7597     case llvm::Triple::FreeBSD:
7598       return new FreeBSDTargetInfo<Mips32EBTargetInfo>(Triple);
7599     case llvm::Triple::NetBSD:
7600       return new NetBSDTargetInfo<Mips32EBTargetInfo>(Triple);
7601     default:
7602       return new Mips32EBTargetInfo(Triple);
7603     }
7604 
7605   case llvm::Triple::mipsel:
7606     switch (os) {
7607     case llvm::Triple::Linux:
7608       return new LinuxTargetInfo<Mips32ELTargetInfo>(Triple);
7609     case llvm::Triple::RTEMS:
7610       return new RTEMSTargetInfo<Mips32ELTargetInfo>(Triple);
7611     case llvm::Triple::FreeBSD:
7612       return new FreeBSDTargetInfo<Mips32ELTargetInfo>(Triple);
7613     case llvm::Triple::NetBSD:
7614       return new NetBSDTargetInfo<Mips32ELTargetInfo>(Triple);
7615     case llvm::Triple::NaCl:
7616       return new NaClTargetInfo<NaClMips32ELTargetInfo>(Triple);
7617     default:
7618       return new Mips32ELTargetInfo(Triple);
7619     }
7620 
7621   case llvm::Triple::mips64:
7622     switch (os) {
7623     case llvm::Triple::Linux:
7624       return new LinuxTargetInfo<Mips64EBTargetInfo>(Triple);
7625     case llvm::Triple::RTEMS:
7626       return new RTEMSTargetInfo<Mips64EBTargetInfo>(Triple);
7627     case llvm::Triple::FreeBSD:
7628       return new FreeBSDTargetInfo<Mips64EBTargetInfo>(Triple);
7629     case llvm::Triple::NetBSD:
7630       return new NetBSDTargetInfo<Mips64EBTargetInfo>(Triple);
7631     case llvm::Triple::OpenBSD:
7632       return new OpenBSDTargetInfo<Mips64EBTargetInfo>(Triple);
7633     default:
7634       return new Mips64EBTargetInfo(Triple);
7635     }
7636 
7637   case llvm::Triple::mips64el:
7638     switch (os) {
7639     case llvm::Triple::Linux:
7640       return new LinuxTargetInfo<Mips64ELTargetInfo>(Triple);
7641     case llvm::Triple::RTEMS:
7642       return new RTEMSTargetInfo<Mips64ELTargetInfo>(Triple);
7643     case llvm::Triple::FreeBSD:
7644       return new FreeBSDTargetInfo<Mips64ELTargetInfo>(Triple);
7645     case llvm::Triple::NetBSD:
7646       return new NetBSDTargetInfo<Mips64ELTargetInfo>(Triple);
7647     case llvm::Triple::OpenBSD:
7648       return new OpenBSDTargetInfo<Mips64ELTargetInfo>(Triple);
7649     default:
7650       return new Mips64ELTargetInfo(Triple);
7651     }
7652 
7653   case llvm::Triple::le32:
7654     switch (os) {
7655     case llvm::Triple::NaCl:
7656       return new NaClTargetInfo<PNaClTargetInfo>(Triple);
7657     default:
7658       return nullptr;
7659     }
7660 
7661   case llvm::Triple::le64:
7662     return new Le64TargetInfo(Triple);
7663 
7664   case llvm::Triple::ppc:
7665     if (Triple.isOSDarwin())
7666       return new DarwinPPC32TargetInfo(Triple);
7667     switch (os) {
7668     case llvm::Triple::Linux:
7669       return new LinuxTargetInfo<PPC32TargetInfo>(Triple);
7670     case llvm::Triple::FreeBSD:
7671       return new FreeBSDTargetInfo<PPC32TargetInfo>(Triple);
7672     case llvm::Triple::NetBSD:
7673       return new NetBSDTargetInfo<PPC32TargetInfo>(Triple);
7674     case llvm::Triple::OpenBSD:
7675       return new OpenBSDTargetInfo<PPC32TargetInfo>(Triple);
7676     case llvm::Triple::RTEMS:
7677       return new RTEMSTargetInfo<PPC32TargetInfo>(Triple);
7678     default:
7679       return new PPC32TargetInfo(Triple);
7680     }
7681 
7682   case llvm::Triple::ppc64:
7683     if (Triple.isOSDarwin())
7684       return new DarwinPPC64TargetInfo(Triple);
7685     switch (os) {
7686     case llvm::Triple::Linux:
7687       return new LinuxTargetInfo<PPC64TargetInfo>(Triple);
7688     case llvm::Triple::Lv2:
7689       return new PS3PPUTargetInfo<PPC64TargetInfo>(Triple);
7690     case llvm::Triple::FreeBSD:
7691       return new FreeBSDTargetInfo<PPC64TargetInfo>(Triple);
7692     case llvm::Triple::NetBSD:
7693       return new NetBSDTargetInfo<PPC64TargetInfo>(Triple);
7694     default:
7695       return new PPC64TargetInfo(Triple);
7696     }
7697 
7698   case llvm::Triple::ppc64le:
7699     switch (os) {
7700     case llvm::Triple::Linux:
7701       return new LinuxTargetInfo<PPC64TargetInfo>(Triple);
7702     case llvm::Triple::NetBSD:
7703       return new NetBSDTargetInfo<PPC64TargetInfo>(Triple);
7704     default:
7705       return new PPC64TargetInfo(Triple);
7706     }
7707 
7708   case llvm::Triple::nvptx:
7709     return new NVPTX32TargetInfo(Triple);
7710   case llvm::Triple::nvptx64:
7711     return new NVPTX64TargetInfo(Triple);
7712 
7713   case llvm::Triple::amdgcn:
7714   case llvm::Triple::r600:
7715     return new AMDGPUTargetInfo(Triple);
7716 
7717   case llvm::Triple::sparc:
7718     switch (os) {
7719     case llvm::Triple::Linux:
7720       return new LinuxTargetInfo<SparcV8TargetInfo>(Triple);
7721     case llvm::Triple::Solaris:
7722       return new SolarisTargetInfo<SparcV8TargetInfo>(Triple);
7723     case llvm::Triple::NetBSD:
7724       return new NetBSDTargetInfo<SparcV8TargetInfo>(Triple);
7725     case llvm::Triple::OpenBSD:
7726       return new OpenBSDTargetInfo<SparcV8TargetInfo>(Triple);
7727     case llvm::Triple::RTEMS:
7728       return new RTEMSTargetInfo<SparcV8TargetInfo>(Triple);
7729     default:
7730       return new SparcV8TargetInfo(Triple);
7731     }
7732 
7733   // The 'sparcel' architecture copies all the above cases except for Solaris.
7734   case llvm::Triple::sparcel:
7735     switch (os) {
7736     case llvm::Triple::Linux:
7737       return new LinuxTargetInfo<SparcV8elTargetInfo>(Triple);
7738     case llvm::Triple::NetBSD:
7739       return new NetBSDTargetInfo<SparcV8elTargetInfo>(Triple);
7740     case llvm::Triple::OpenBSD:
7741       return new OpenBSDTargetInfo<SparcV8elTargetInfo>(Triple);
7742     case llvm::Triple::RTEMS:
7743       return new RTEMSTargetInfo<SparcV8elTargetInfo>(Triple);
7744     default:
7745       return new SparcV8elTargetInfo(Triple);
7746     }
7747 
7748   case llvm::Triple::sparcv9:
7749     switch (os) {
7750     case llvm::Triple::Linux:
7751       return new LinuxTargetInfo<SparcV9TargetInfo>(Triple);
7752     case llvm::Triple::Solaris:
7753       return new SolarisTargetInfo<SparcV9TargetInfo>(Triple);
7754     case llvm::Triple::NetBSD:
7755       return new NetBSDTargetInfo<SparcV9TargetInfo>(Triple);
7756     case llvm::Triple::OpenBSD:
7757       return new OpenBSDTargetInfo<SparcV9TargetInfo>(Triple);
7758     case llvm::Triple::FreeBSD:
7759       return new FreeBSDTargetInfo<SparcV9TargetInfo>(Triple);
7760     default:
7761       return new SparcV9TargetInfo(Triple);
7762     }
7763 
7764   case llvm::Triple::systemz:
7765     switch (os) {
7766     case llvm::Triple::Linux:
7767       return new LinuxTargetInfo<SystemZTargetInfo>(Triple);
7768     default:
7769       return new SystemZTargetInfo(Triple);
7770     }
7771 
7772   case llvm::Triple::tce:
7773     return new TCETargetInfo(Triple);
7774 
7775   case llvm::Triple::x86:
7776     if (Triple.isOSDarwin())
7777       return new DarwinI386TargetInfo(Triple);
7778 
7779     switch (os) {
7780     case llvm::Triple::CloudABI:
7781       return new CloudABITargetInfo<X86_32TargetInfo>(Triple);
7782     case llvm::Triple::Linux: {
7783       switch (Triple.getEnvironment()) {
7784       default:
7785         return new LinuxTargetInfo<X86_32TargetInfo>(Triple);
7786       case llvm::Triple::Android:
7787         return new AndroidX86_32TargetInfo(Triple);
7788       }
7789     }
7790     case llvm::Triple::DragonFly:
7791       return new DragonFlyBSDTargetInfo<X86_32TargetInfo>(Triple);
7792     case llvm::Triple::NetBSD:
7793       return new NetBSDI386TargetInfo(Triple);
7794     case llvm::Triple::OpenBSD:
7795       return new OpenBSDI386TargetInfo(Triple);
7796     case llvm::Triple::Bitrig:
7797       return new BitrigI386TargetInfo(Triple);
7798     case llvm::Triple::FreeBSD:
7799       return new FreeBSDTargetInfo<X86_32TargetInfo>(Triple);
7800     case llvm::Triple::KFreeBSD:
7801       return new KFreeBSDTargetInfo<X86_32TargetInfo>(Triple);
7802     case llvm::Triple::Minix:
7803       return new MinixTargetInfo<X86_32TargetInfo>(Triple);
7804     case llvm::Triple::Solaris:
7805       return new SolarisTargetInfo<X86_32TargetInfo>(Triple);
7806     case llvm::Triple::Win32: {
7807       switch (Triple.getEnvironment()) {
7808       case llvm::Triple::Cygnus:
7809         return new CygwinX86_32TargetInfo(Triple);
7810       case llvm::Triple::GNU:
7811         return new MinGWX86_32TargetInfo(Triple);
7812       case llvm::Triple::Itanium:
7813       case llvm::Triple::MSVC:
7814       default: // Assume MSVC for unknown environments
7815         return new MicrosoftX86_32TargetInfo(Triple);
7816       }
7817     }
7818     case llvm::Triple::Haiku:
7819       return new HaikuX86_32TargetInfo(Triple);
7820     case llvm::Triple::RTEMS:
7821       return new RTEMSX86_32TargetInfo(Triple);
7822     case llvm::Triple::NaCl:
7823       return new NaClTargetInfo<X86_32TargetInfo>(Triple);
7824     case llvm::Triple::ELFIAMCU:
7825       return new MCUX86_32TargetInfo(Triple);
7826     default:
7827       return new X86_32TargetInfo(Triple);
7828     }
7829 
7830   case llvm::Triple::x86_64:
7831     if (Triple.isOSDarwin() || Triple.isOSBinFormatMachO())
7832       return new DarwinX86_64TargetInfo(Triple);
7833 
7834     switch (os) {
7835     case llvm::Triple::CloudABI:
7836       return new CloudABITargetInfo<X86_64TargetInfo>(Triple);
7837     case llvm::Triple::Linux: {
7838       switch (Triple.getEnvironment()) {
7839       default:
7840         return new LinuxTargetInfo<X86_64TargetInfo>(Triple);
7841       case llvm::Triple::Android:
7842         return new AndroidX86_64TargetInfo(Triple);
7843       }
7844     }
7845     case llvm::Triple::DragonFly:
7846       return new DragonFlyBSDTargetInfo<X86_64TargetInfo>(Triple);
7847     case llvm::Triple::NetBSD:
7848       return new NetBSDTargetInfo<X86_64TargetInfo>(Triple);
7849     case llvm::Triple::OpenBSD:
7850       return new OpenBSDX86_64TargetInfo(Triple);
7851     case llvm::Triple::Bitrig:
7852       return new BitrigX86_64TargetInfo(Triple);
7853     case llvm::Triple::FreeBSD:
7854       return new FreeBSDTargetInfo<X86_64TargetInfo>(Triple);
7855     case llvm::Triple::KFreeBSD:
7856       return new KFreeBSDTargetInfo<X86_64TargetInfo>(Triple);
7857     case llvm::Triple::Solaris:
7858       return new SolarisTargetInfo<X86_64TargetInfo>(Triple);
7859     case llvm::Triple::Win32: {
7860       switch (Triple.getEnvironment()) {
7861       case llvm::Triple::Cygnus:
7862         return new CygwinX86_64TargetInfo(Triple);
7863       case llvm::Triple::GNU:
7864         return new MinGWX86_64TargetInfo(Triple);
7865       case llvm::Triple::MSVC:
7866       default: // Assume MSVC for unknown environments
7867         return new MicrosoftX86_64TargetInfo(Triple);
7868       }
7869     }
7870     case llvm::Triple::NaCl:
7871       return new NaClTargetInfo<X86_64TargetInfo>(Triple);
7872     case llvm::Triple::PS4:
7873       return new PS4OSTargetInfo<X86_64TargetInfo>(Triple);
7874     default:
7875       return new X86_64TargetInfo(Triple);
7876     }
7877 
7878   case llvm::Triple::spir: {
7879     if (Triple.getOS() != llvm::Triple::UnknownOS ||
7880         Triple.getEnvironment() != llvm::Triple::UnknownEnvironment)
7881       return nullptr;
7882     return new SPIR32TargetInfo(Triple);
7883   }
7884   case llvm::Triple::spir64: {
7885     if (Triple.getOS() != llvm::Triple::UnknownOS ||
7886         Triple.getEnvironment() != llvm::Triple::UnknownEnvironment)
7887       return nullptr;
7888     return new SPIR64TargetInfo(Triple);
7889   }
7890   case llvm::Triple::wasm32:
7891     if (!(Triple == llvm::Triple("wasm32-unknown-unknown")))
7892       return nullptr;
7893     return new WebAssemblyOSTargetInfo<WebAssembly32TargetInfo>(Triple);
7894   case llvm::Triple::wasm64:
7895     if (!(Triple == llvm::Triple("wasm64-unknown-unknown")))
7896       return nullptr;
7897     return new WebAssemblyOSTargetInfo<WebAssembly64TargetInfo>(Triple);
7898   }
7899 }
7900 
7901 /// CreateTargetInfo - Return the target info object for the specified target
7902 /// options.
7903 TargetInfo *
CreateTargetInfo(DiagnosticsEngine & Diags,const std::shared_ptr<TargetOptions> & Opts)7904 TargetInfo::CreateTargetInfo(DiagnosticsEngine &Diags,
7905                              const std::shared_ptr<TargetOptions> &Opts) {
7906   llvm::Triple Triple(Opts->Triple);
7907 
7908   // Construct the target
7909   std::unique_ptr<TargetInfo> Target(AllocateTarget(Triple));
7910   if (!Target) {
7911     Diags.Report(diag::err_target_unknown_triple) << Triple.str();
7912     return nullptr;
7913   }
7914   Target->TargetOpts = Opts;
7915 
7916   // Set the target CPU if specified.
7917   if (!Opts->CPU.empty() && !Target->setCPU(Opts->CPU)) {
7918     Diags.Report(diag::err_target_unknown_cpu) << Opts->CPU;
7919     return nullptr;
7920   }
7921 
7922   // Set the target ABI if specified.
7923   if (!Opts->ABI.empty() && !Target->setABI(Opts->ABI)) {
7924     Diags.Report(diag::err_target_unknown_abi) << Opts->ABI;
7925     return nullptr;
7926   }
7927 
7928   // Set the fp math unit.
7929   if (!Opts->FPMath.empty() && !Target->setFPMath(Opts->FPMath)) {
7930     Diags.Report(diag::err_target_unknown_fpmath) << Opts->FPMath;
7931     return nullptr;
7932   }
7933 
7934   // Compute the default target features, we need the target to handle this
7935   // because features may have dependencies on one another.
7936   llvm::StringMap<bool> Features;
7937   if (!Target->initFeatureMap(Features, Diags, Opts->CPU,
7938                               Opts->FeaturesAsWritten))
7939       return nullptr;
7940 
7941   // Add the features to the compile options.
7942   Opts->Features.clear();
7943   for (const auto &F : Features)
7944     Opts->Features.push_back((F.getValue() ? "+" : "-") + F.getKey().str());
7945 
7946   if (!Target->handleTargetFeatures(Opts->Features, Diags))
7947     return nullptr;
7948 
7949   return Target.release();
7950 }
7951