1 //===--- TargetInfo.h - Expose information about the target -----*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 ///
9 /// \file
10 /// Defines the clang::TargetInfo interface.
11 ///
12 //===----------------------------------------------------------------------===//
13 
14 #ifndef LLVM_CLANG_BASIC_TARGETINFO_H
15 #define LLVM_CLANG_BASIC_TARGETINFO_H
16 
17 #include "clang/Basic/AddressSpaces.h"
18 #include "clang/Basic/CodeGenOptions.h"
19 #include "clang/Basic/LLVM.h"
20 #include "clang/Basic/LangOptions.h"
21 #include "clang/Basic/Specifiers.h"
22 #include "clang/Basic/TargetCXXABI.h"
23 #include "clang/Basic/TargetOptions.h"
24 #include "llvm/ADT/APFloat.h"
25 #include "llvm/ADT/APInt.h"
26 #include "llvm/ADT/ArrayRef.h"
27 #include "llvm/ADT/IntrusiveRefCntPtr.h"
28 #include "llvm/ADT/Optional.h"
29 #include "llvm/ADT/SmallSet.h"
30 #include "llvm/ADT/StringMap.h"
31 #include "llvm/ADT/StringRef.h"
32 #include "llvm/ADT/Triple.h"
33 #include "llvm/Frontend/OpenMP/OMPGridValues.h"
34 #include "llvm/Support/DataTypes.h"
35 #include "llvm/Support/Error.h"
36 #include "llvm/Support/VersionTuple.h"
37 #include <cassert>
38 #include <string>
39 #include <vector>
40 
41 namespace llvm {
42 struct fltSemantics;
43 }
44 
45 namespace clang {
46 class DiagnosticsEngine;
47 class LangOptions;
48 class CodeGenOptions;
49 class MacroBuilder;
50 class QualType;
51 class SourceLocation;
52 class SourceManager;
53 
54 namespace Builtin { struct Info; }
55 
56 /// Fields controlling how types are laid out in memory; these may need to
57 /// be copied for targets like AMDGPU that base their ABIs on an auxiliary
58 /// CPU target.
59 struct TransferrableTargetInfo {
60   unsigned char PointerWidth, PointerAlign;
61   unsigned char BoolWidth, BoolAlign;
62   unsigned char IntWidth, IntAlign;
63   unsigned char HalfWidth, HalfAlign;
64   unsigned char BFloat16Width, BFloat16Align;
65   unsigned char FloatWidth, FloatAlign;
66   unsigned char DoubleWidth, DoubleAlign;
67   unsigned char LongDoubleWidth, LongDoubleAlign, Float128Align;
68   unsigned char LargeArrayMinWidth, LargeArrayAlign;
69   unsigned char LongWidth, LongAlign;
70   unsigned char LongLongWidth, LongLongAlign;
71 
72   // Fixed point bit widths
73   unsigned char ShortAccumWidth, ShortAccumAlign;
74   unsigned char AccumWidth, AccumAlign;
75   unsigned char LongAccumWidth, LongAccumAlign;
76   unsigned char ShortFractWidth, ShortFractAlign;
77   unsigned char FractWidth, FractAlign;
78   unsigned char LongFractWidth, LongFractAlign;
79 
80   // If true, unsigned fixed point types have the same number of fractional bits
81   // as their signed counterparts, forcing the unsigned types to have one extra
82   // bit of padding. Otherwise, unsigned fixed point types have
83   // one more fractional bit than its corresponding signed type. This is false
84   // by default.
85   bool PaddingOnUnsignedFixedPoint;
86 
87   // Fixed point integral and fractional bit sizes
88   // Saturated types share the same integral/fractional bits as their
89   // corresponding unsaturated types.
90   // For simplicity, the fractional bits in a _Fract type will be one less the
91   // width of that _Fract type. This leaves all signed _Fract types having no
92   // padding and unsigned _Fract types will only have 1 bit of padding after the
93   // sign if PaddingOnUnsignedFixedPoint is set.
94   unsigned char ShortAccumScale;
95   unsigned char AccumScale;
96   unsigned char LongAccumScale;
97 
98   unsigned char SuitableAlign;
99   unsigned char DefaultAlignForAttributeAligned;
100   unsigned char MinGlobalAlign;
101 
102   unsigned short NewAlign;
103   unsigned MaxVectorAlign;
104   unsigned MaxTLSAlign;
105 
106   const llvm::fltSemantics *HalfFormat, *BFloat16Format, *FloatFormat,
107     *DoubleFormat, *LongDoubleFormat, *Float128Format;
108 
109   ///===---- Target Data Type Query Methods -------------------------------===//
110   enum IntType {
111     NoInt = 0,
112     SignedChar,
113     UnsignedChar,
114     SignedShort,
115     UnsignedShort,
116     SignedInt,
117     UnsignedInt,
118     SignedLong,
119     UnsignedLong,
120     SignedLongLong,
121     UnsignedLongLong
122   };
123 
124   enum RealType {
125     NoFloat = 255,
126     Float = 0,
127     Double,
128     LongDouble,
129     Float128
130   };
131 protected:
132   IntType SizeType, IntMaxType, PtrDiffType, IntPtrType, WCharType, WIntType,
133       Char16Type, Char32Type, Int64Type, Int16Type, SigAtomicType,
134       ProcessIDType;
135 
136   /// Whether Objective-C's built-in boolean type should be signed char.
137   ///
138   /// Otherwise, when this flag is not set, the normal built-in boolean type is
139   /// used.
140   unsigned UseSignedCharForObjCBool : 1;
141 
142   /// Control whether the alignment of bit-field types is respected when laying
143   /// out structures. If true, then the alignment of the bit-field type will be
144   /// used to (a) impact the alignment of the containing structure, and (b)
145   /// ensure that the individual bit-field will not straddle an alignment
146   /// boundary.
147   unsigned UseBitFieldTypeAlignment : 1;
148 
149   /// Whether zero length bitfields (e.g., int : 0;) force alignment of
150   /// the next bitfield.
151   ///
152   /// If the alignment of the zero length bitfield is greater than the member
153   /// that follows it, `bar', `bar' will be aligned as the type of the
154   /// zero-length bitfield.
155   unsigned UseZeroLengthBitfieldAlignment : 1;
156 
157   /// Whether zero length bitfield alignment is respected if they are the
158   /// leading members.
159   unsigned UseLeadingZeroLengthBitfield : 1;
160 
161   ///  Whether explicit bit field alignment attributes are honored.
162   unsigned UseExplicitBitFieldAlignment : 1;
163 
164   /// If non-zero, specifies a fixed alignment value for bitfields that follow
165   /// zero length bitfield, regardless of the zero length bitfield type.
166   unsigned ZeroLengthBitfieldBoundary;
167 
168   /// If non-zero, specifies a maximum alignment to truncate alignment
169   /// specified in the aligned attribute of a static variable to this value.
170   unsigned MaxAlignedAttribute;
171 };
172 
173 /// OpenCL type kinds.
174 enum OpenCLTypeKind : uint8_t {
175   OCLTK_Default,
176   OCLTK_ClkEvent,
177   OCLTK_Event,
178   OCLTK_Image,
179   OCLTK_Pipe,
180   OCLTK_Queue,
181   OCLTK_ReserveID,
182   OCLTK_Sampler,
183 };
184 
185 /// Exposes information about the current target.
186 ///
187 class TargetInfo : public virtual TransferrableTargetInfo,
188                    public RefCountedBase<TargetInfo> {
189   std::shared_ptr<TargetOptions> TargetOpts;
190   llvm::Triple Triple;
191 protected:
192   // Target values set by the ctor of the actual target implementation.  Default
193   // values are specified by the TargetInfo constructor.
194   bool BigEndian;
195   bool TLSSupported;
196   bool VLASupported;
197   bool NoAsmVariants;  // True if {|} are normal characters.
198   bool HasLegalHalfType; // True if the backend supports operations on the half
199                          // LLVM IR type.
200   bool HasFloat128;
201   bool HasFloat16;
202   bool HasBFloat16;
203   bool HasStrictFP;
204 
205   unsigned char MaxAtomicPromoteWidth, MaxAtomicInlineWidth;
206   unsigned short SimdDefaultAlign;
207   std::string DataLayoutString;
208   const char *UserLabelPrefix;
209   const char *MCountName;
210   unsigned char RegParmMax, SSERegParmMax;
211   TargetCXXABI TheCXXABI;
212   const LangASMap *AddrSpaceMap;
213   const unsigned *GridValues =
214       nullptr; // Array of target-specific GPU grid values that must be
215                // consistent between host RTL (plugin), device RTL, and clang.
216 
217   mutable StringRef PlatformName;
218   mutable VersionTuple PlatformMinVersion;
219 
220   unsigned HasAlignMac68kSupport : 1;
221   unsigned RealTypeUsesObjCFPRet : 3;
222   unsigned ComplexLongDoubleUsesFP2Ret : 1;
223 
224   unsigned HasBuiltinMSVaList : 1;
225 
226   unsigned IsRenderScriptTarget : 1;
227 
228   unsigned HasAArch64SVETypes : 1;
229 
230   unsigned HasRISCVVTypes : 1;
231 
232   unsigned AllowAMDGPUUnsafeFPAtomics : 1;
233 
234   unsigned ARMCDECoprocMask : 8;
235 
236   unsigned MaxOpenCLWorkGroupSize;
237 
238   // TargetInfo Constructor.  Default initializes all fields.
239   TargetInfo(const llvm::Triple &T);
240 
241   // UserLabelPrefix must match DL's getGlobalPrefix() when interpreted
242   // as a DataLayout object.
243   void resetDataLayout(StringRef DL, const char *UserLabelPrefix = "");
244 
245 public:
246   /// Construct a target for the given options.
247   ///
248   /// \param Opts - The options to use to initialize the target. The target may
249   /// modify the options to canonicalize the target feature information to match
250   /// what the backend expects.
251   static TargetInfo *
252   CreateTargetInfo(DiagnosticsEngine &Diags,
253                    const std::shared_ptr<TargetOptions> &Opts);
254 
255   virtual ~TargetInfo();
256 
257   /// Retrieve the target options.
getTargetOpts()258   TargetOptions &getTargetOpts() const {
259     assert(TargetOpts && "Missing target options");
260     return *TargetOpts;
261   }
262 
263   /// The different kinds of __builtin_va_list types defined by
264   /// the target implementation.
265   enum BuiltinVaListKind {
266     /// typedef char* __builtin_va_list;
267     CharPtrBuiltinVaList = 0,
268 
269     /// typedef void* __builtin_va_list;
270     VoidPtrBuiltinVaList,
271 
272     /// __builtin_va_list as defined by the AArch64 ABI
273     /// http://infocenter.arm.com/help/topic/com.arm.doc.ihi0055a/IHI0055A_aapcs64.pdf
274     AArch64ABIBuiltinVaList,
275 
276     /// __builtin_va_list as defined by the PNaCl ABI:
277     /// http://www.chromium.org/nativeclient/pnacl/bitcode-abi#TOC-Machine-Types
278     PNaClABIBuiltinVaList,
279 
280     /// __builtin_va_list as defined by the Power ABI:
281     /// https://www.power.org
282     ///        /resources/downloads/Power-Arch-32-bit-ABI-supp-1.0-Embedded.pdf
283     PowerABIBuiltinVaList,
284 
285     /// __builtin_va_list as defined by the x86-64 ABI:
286     /// http://refspecs.linuxbase.org/elf/x86_64-abi-0.21.pdf
287     X86_64ABIBuiltinVaList,
288 
289     /// __builtin_va_list as defined by ARM AAPCS ABI
290     /// http://infocenter.arm.com
291     //        /help/topic/com.arm.doc.ihi0042d/IHI0042D_aapcs.pdf
292     AAPCSABIBuiltinVaList,
293 
294     // typedef struct __va_list_tag
295     //   {
296     //     long __gpr;
297     //     long __fpr;
298     //     void *__overflow_arg_area;
299     //     void *__reg_save_area;
300     //   } va_list[1];
301     SystemZBuiltinVaList,
302 
303     // typedef struct __va_list_tag {
304     //    void *__current_saved_reg_area_pointer;
305     //    void *__saved_reg_area_end_pointer;
306     //    void *__overflow_area_pointer;
307     //} va_list;
308     HexagonBuiltinVaList
309   };
310 
311 protected:
312   /// Specify if mangling based on address space map should be used or
313   /// not for language specific address spaces
314   bool UseAddrSpaceMapMangling;
315 
316 public:
getSizeType()317   IntType getSizeType() const { return SizeType; }
getSignedSizeType()318   IntType getSignedSizeType() const {
319     switch (SizeType) {
320     case UnsignedShort:
321       return SignedShort;
322     case UnsignedInt:
323       return SignedInt;
324     case UnsignedLong:
325       return SignedLong;
326     case UnsignedLongLong:
327       return SignedLongLong;
328     default:
329       llvm_unreachable("Invalid SizeType");
330     }
331   }
getIntMaxType()332   IntType getIntMaxType() const { return IntMaxType; }
getUIntMaxType()333   IntType getUIntMaxType() const {
334     return getCorrespondingUnsignedType(IntMaxType);
335   }
getPtrDiffType(unsigned AddrSpace)336   IntType getPtrDiffType(unsigned AddrSpace) const {
337     return AddrSpace == 0 ? PtrDiffType : getPtrDiffTypeV(AddrSpace);
338   }
getUnsignedPtrDiffType(unsigned AddrSpace)339   IntType getUnsignedPtrDiffType(unsigned AddrSpace) const {
340     return getCorrespondingUnsignedType(getPtrDiffType(AddrSpace));
341   }
getIntPtrType()342   IntType getIntPtrType() const { return IntPtrType; }
getUIntPtrType()343   IntType getUIntPtrType() const {
344     return getCorrespondingUnsignedType(IntPtrType);
345   }
getWCharType()346   IntType getWCharType() const { return WCharType; }
getWIntType()347   IntType getWIntType() const { return WIntType; }
getChar16Type()348   IntType getChar16Type() const { return Char16Type; }
getChar32Type()349   IntType getChar32Type() const { return Char32Type; }
getInt64Type()350   IntType getInt64Type() const { return Int64Type; }
getUInt64Type()351   IntType getUInt64Type() const {
352     return getCorrespondingUnsignedType(Int64Type);
353   }
getInt16Type()354   IntType getInt16Type() const { return Int16Type; }
getUInt16Type()355   IntType getUInt16Type() const {
356     return getCorrespondingUnsignedType(Int16Type);
357   }
getSigAtomicType()358   IntType getSigAtomicType() const { return SigAtomicType; }
getProcessIDType()359   IntType getProcessIDType() const { return ProcessIDType; }
360 
getCorrespondingUnsignedType(IntType T)361   static IntType getCorrespondingUnsignedType(IntType T) {
362     switch (T) {
363     case SignedChar:
364       return UnsignedChar;
365     case SignedShort:
366       return UnsignedShort;
367     case SignedInt:
368       return UnsignedInt;
369     case SignedLong:
370       return UnsignedLong;
371     case SignedLongLong:
372       return UnsignedLongLong;
373     default:
374       llvm_unreachable("Unexpected signed integer type");
375     }
376   }
377 
378   /// In the event this target uses the same number of fractional bits for its
379   /// unsigned types as it does with its signed counterparts, there will be
380   /// exactly one bit of padding.
381   /// Return true if unsigned fixed point types have padding for this target.
doUnsignedFixedPointTypesHavePadding()382   bool doUnsignedFixedPointTypesHavePadding() const {
383     return PaddingOnUnsignedFixedPoint;
384   }
385 
386   /// Return the width (in bits) of the specified integer type enum.
387   ///
388   /// For example, SignedInt -> getIntWidth().
389   unsigned getTypeWidth(IntType T) const;
390 
391   /// Return integer type with specified width.
392   virtual IntType getIntTypeByWidth(unsigned BitWidth, bool IsSigned) const;
393 
394   /// Return the smallest integer type with at least the specified width.
395   virtual IntType getLeastIntTypeByWidth(unsigned BitWidth,
396                                          bool IsSigned) const;
397 
398   /// Return floating point type with specified width. On PPC, there are
399   /// three possible types for 128-bit floating point: "PPC double-double",
400   /// IEEE 754R quad precision, and "long double" (which under the covers
401   /// is represented as one of those two). At this time, there is no support
402   /// for an explicit "PPC double-double" type (i.e. __ibm128) so we only
403   /// need to differentiate between "long double" and IEEE quad precision.
404   RealType getRealTypeByWidth(unsigned BitWidth, bool ExplicitIEEE) const;
405 
406   /// Return the alignment (in bits) of the specified integer type enum.
407   ///
408   /// For example, SignedInt -> getIntAlign().
409   unsigned getTypeAlign(IntType T) const;
410 
411   /// Returns true if the type is signed; false otherwise.
412   static bool isTypeSigned(IntType T);
413 
414   /// Return the width of pointers on this target, for the
415   /// specified address space.
getPointerWidth(unsigned AddrSpace)416   uint64_t getPointerWidth(unsigned AddrSpace) const {
417     return AddrSpace == 0 ? PointerWidth : getPointerWidthV(AddrSpace);
418   }
getPointerAlign(unsigned AddrSpace)419   uint64_t getPointerAlign(unsigned AddrSpace) const {
420     return AddrSpace == 0 ? PointerAlign : getPointerAlignV(AddrSpace);
421   }
422 
423   /// Return the maximum width of pointers on this target.
getMaxPointerWidth()424   virtual uint64_t getMaxPointerWidth() const {
425     return PointerWidth;
426   }
427 
428   /// Get integer value for null pointer.
429   /// \param AddrSpace address space of pointee in source language.
getNullPointerValue(LangAS AddrSpace)430   virtual uint64_t getNullPointerValue(LangAS AddrSpace) const { return 0; }
431 
432   /// Return the size of '_Bool' and C++ 'bool' for this target, in bits.
getBoolWidth()433   unsigned getBoolWidth() const { return BoolWidth; }
434 
435   /// Return the alignment of '_Bool' and C++ 'bool' for this target.
getBoolAlign()436   unsigned getBoolAlign() const { return BoolAlign; }
437 
getCharWidth()438   unsigned getCharWidth() const { return 8; } // FIXME
getCharAlign()439   unsigned getCharAlign() const { return 8; } // FIXME
440 
441   /// Return the size of 'signed short' and 'unsigned short' for this
442   /// target, in bits.
getShortWidth()443   unsigned getShortWidth() const { return 16; } // FIXME
444 
445   /// Return the alignment of 'signed short' and 'unsigned short' for
446   /// this target.
getShortAlign()447   unsigned getShortAlign() const { return 16; } // FIXME
448 
449   /// getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for
450   /// this target, in bits.
getIntWidth()451   unsigned getIntWidth() const { return IntWidth; }
getIntAlign()452   unsigned getIntAlign() const { return IntAlign; }
453 
454   /// getLongWidth/Align - Return the size of 'signed long' and 'unsigned long'
455   /// for this target, in bits.
getLongWidth()456   unsigned getLongWidth() const { return LongWidth; }
getLongAlign()457   unsigned getLongAlign() const { return LongAlign; }
458 
459   /// getLongLongWidth/Align - Return the size of 'signed long long' and
460   /// 'unsigned long long' for this target, in bits.
getLongLongWidth()461   unsigned getLongLongWidth() const { return LongLongWidth; }
getLongLongAlign()462   unsigned getLongLongAlign() const { return LongLongAlign; }
463 
464   /// getShortAccumWidth/Align - Return the size of 'signed short _Accum' and
465   /// 'unsigned short _Accum' for this target, in bits.
getShortAccumWidth()466   unsigned getShortAccumWidth() const { return ShortAccumWidth; }
getShortAccumAlign()467   unsigned getShortAccumAlign() const { return ShortAccumAlign; }
468 
469   /// getAccumWidth/Align - Return the size of 'signed _Accum' and
470   /// 'unsigned _Accum' for this target, in bits.
getAccumWidth()471   unsigned getAccumWidth() const { return AccumWidth; }
getAccumAlign()472   unsigned getAccumAlign() const { return AccumAlign; }
473 
474   /// getLongAccumWidth/Align - Return the size of 'signed long _Accum' and
475   /// 'unsigned long _Accum' for this target, in bits.
getLongAccumWidth()476   unsigned getLongAccumWidth() const { return LongAccumWidth; }
getLongAccumAlign()477   unsigned getLongAccumAlign() const { return LongAccumAlign; }
478 
479   /// getShortFractWidth/Align - Return the size of 'signed short _Fract' and
480   /// 'unsigned short _Fract' for this target, in bits.
getShortFractWidth()481   unsigned getShortFractWidth() const { return ShortFractWidth; }
getShortFractAlign()482   unsigned getShortFractAlign() const { return ShortFractAlign; }
483 
484   /// getFractWidth/Align - Return the size of 'signed _Fract' and
485   /// 'unsigned _Fract' for this target, in bits.
getFractWidth()486   unsigned getFractWidth() const { return FractWidth; }
getFractAlign()487   unsigned getFractAlign() const { return FractAlign; }
488 
489   /// getLongFractWidth/Align - Return the size of 'signed long _Fract' and
490   /// 'unsigned long _Fract' for this target, in bits.
getLongFractWidth()491   unsigned getLongFractWidth() const { return LongFractWidth; }
getLongFractAlign()492   unsigned getLongFractAlign() const { return LongFractAlign; }
493 
494   /// getShortAccumScale/IBits - Return the number of fractional/integral bits
495   /// in a 'signed short _Accum' type.
getShortAccumScale()496   unsigned getShortAccumScale() const { return ShortAccumScale; }
getShortAccumIBits()497   unsigned getShortAccumIBits() const {
498     return ShortAccumWidth - ShortAccumScale - 1;
499   }
500 
501   /// getAccumScale/IBits - Return the number of fractional/integral bits
502   /// in a 'signed _Accum' type.
getAccumScale()503   unsigned getAccumScale() const { return AccumScale; }
getAccumIBits()504   unsigned getAccumIBits() const { return AccumWidth - AccumScale - 1; }
505 
506   /// getLongAccumScale/IBits - Return the number of fractional/integral bits
507   /// in a 'signed long _Accum' type.
getLongAccumScale()508   unsigned getLongAccumScale() const { return LongAccumScale; }
getLongAccumIBits()509   unsigned getLongAccumIBits() const {
510     return LongAccumWidth - LongAccumScale - 1;
511   }
512 
513   /// getUnsignedShortAccumScale/IBits - Return the number of
514   /// fractional/integral bits in a 'unsigned short _Accum' type.
getUnsignedShortAccumScale()515   unsigned getUnsignedShortAccumScale() const {
516     return PaddingOnUnsignedFixedPoint ? ShortAccumScale : ShortAccumScale + 1;
517   }
getUnsignedShortAccumIBits()518   unsigned getUnsignedShortAccumIBits() const {
519     return PaddingOnUnsignedFixedPoint
520                ? getShortAccumIBits()
521                : ShortAccumWidth - getUnsignedShortAccumScale();
522   }
523 
524   /// getUnsignedAccumScale/IBits - Return the number of fractional/integral
525   /// bits in a 'unsigned _Accum' type.
getUnsignedAccumScale()526   unsigned getUnsignedAccumScale() const {
527     return PaddingOnUnsignedFixedPoint ? AccumScale : AccumScale + 1;
528   }
getUnsignedAccumIBits()529   unsigned getUnsignedAccumIBits() const {
530     return PaddingOnUnsignedFixedPoint ? getAccumIBits()
531                                        : AccumWidth - getUnsignedAccumScale();
532   }
533 
534   /// getUnsignedLongAccumScale/IBits - Return the number of fractional/integral
535   /// bits in a 'unsigned long _Accum' type.
getUnsignedLongAccumScale()536   unsigned getUnsignedLongAccumScale() const {
537     return PaddingOnUnsignedFixedPoint ? LongAccumScale : LongAccumScale + 1;
538   }
getUnsignedLongAccumIBits()539   unsigned getUnsignedLongAccumIBits() const {
540     return PaddingOnUnsignedFixedPoint
541                ? getLongAccumIBits()
542                : LongAccumWidth - getUnsignedLongAccumScale();
543   }
544 
545   /// getShortFractScale - Return the number of fractional bits
546   /// in a 'signed short _Fract' type.
getShortFractScale()547   unsigned getShortFractScale() const { return ShortFractWidth - 1; }
548 
549   /// getFractScale - Return the number of fractional bits
550   /// in a 'signed _Fract' type.
getFractScale()551   unsigned getFractScale() const { return FractWidth - 1; }
552 
553   /// getLongFractScale - Return the number of fractional bits
554   /// in a 'signed long _Fract' type.
getLongFractScale()555   unsigned getLongFractScale() const { return LongFractWidth - 1; }
556 
557   /// getUnsignedShortFractScale - Return the number of fractional bits
558   /// in a 'unsigned short _Fract' type.
getUnsignedShortFractScale()559   unsigned getUnsignedShortFractScale() const {
560     return PaddingOnUnsignedFixedPoint ? getShortFractScale()
561                                        : getShortFractScale() + 1;
562   }
563 
564   /// getUnsignedFractScale - Return the number of fractional bits
565   /// in a 'unsigned _Fract' type.
getUnsignedFractScale()566   unsigned getUnsignedFractScale() const {
567     return PaddingOnUnsignedFixedPoint ? getFractScale() : getFractScale() + 1;
568   }
569 
570   /// getUnsignedLongFractScale - Return the number of fractional bits
571   /// in a 'unsigned long _Fract' type.
getUnsignedLongFractScale()572   unsigned getUnsignedLongFractScale() const {
573     return PaddingOnUnsignedFixedPoint ? getLongFractScale()
574                                        : getLongFractScale() + 1;
575   }
576 
577   /// Determine whether the __int128 type is supported on this target.
hasInt128Type()578   virtual bool hasInt128Type() const {
579     return (getPointerWidth(0) >= 64) || getTargetOpts().ForceEnableInt128;
580   } // FIXME
581 
582   /// Determine whether the _ExtInt type is supported on this target. This
583   /// limitation is put into place for ABI reasons.
hasExtIntType()584   virtual bool hasExtIntType() const {
585     return false;
586   }
587 
588   /// Determine whether _Float16 is supported on this target.
hasLegalHalfType()589   virtual bool hasLegalHalfType() const { return HasLegalHalfType; }
590 
591   /// Determine whether the __float128 type is supported on this target.
hasFloat128Type()592   virtual bool hasFloat128Type() const { return HasFloat128; }
593 
594   /// Determine whether the _Float16 type is supported on this target.
hasFloat16Type()595   virtual bool hasFloat16Type() const { return HasFloat16; }
596 
597   /// Determine whether the _BFloat16 type is supported on this target.
hasBFloat16Type()598   virtual bool hasBFloat16Type() const { return HasBFloat16; }
599 
600   /// Determine whether constrained floating point is supported on this target.
hasStrictFP()601   virtual bool hasStrictFP() const { return HasStrictFP; }
602 
603   /// Return the alignment that is the largest alignment ever used for any
604   /// scalar/SIMD data type on the target machine you are compiling for
605   /// (including types with an extended alignment requirement).
getSuitableAlign()606   unsigned getSuitableAlign() const { return SuitableAlign; }
607 
608   /// Return the default alignment for __attribute__((aligned)) on
609   /// this target, to be used if no alignment value is specified.
getDefaultAlignForAttributeAligned()610   unsigned getDefaultAlignForAttributeAligned() const {
611     return DefaultAlignForAttributeAligned;
612   }
613 
614   /// getMinGlobalAlign - Return the minimum alignment of a global variable,
615   /// unless its alignment is explicitly reduced via attributes.
getMinGlobalAlign(uint64_t)616   virtual unsigned getMinGlobalAlign (uint64_t) const {
617     return MinGlobalAlign;
618   }
619 
620   /// Return the largest alignment for which a suitably-sized allocation with
621   /// '::operator new(size_t)' or 'malloc' is guaranteed to produce a
622   /// correctly-aligned pointer.
getNewAlign()623   unsigned getNewAlign() const {
624     return NewAlign ? NewAlign : std::max(LongDoubleAlign, LongLongAlign);
625   }
626 
627   /// getWCharWidth/Align - Return the size of 'wchar_t' for this target, in
628   /// bits.
getWCharWidth()629   unsigned getWCharWidth() const { return getTypeWidth(WCharType); }
getWCharAlign()630   unsigned getWCharAlign() const { return getTypeAlign(WCharType); }
631 
632   /// getChar16Width/Align - Return the size of 'char16_t' for this target, in
633   /// bits.
getChar16Width()634   unsigned getChar16Width() const { return getTypeWidth(Char16Type); }
getChar16Align()635   unsigned getChar16Align() const { return getTypeAlign(Char16Type); }
636 
637   /// getChar32Width/Align - Return the size of 'char32_t' for this target, in
638   /// bits.
getChar32Width()639   unsigned getChar32Width() const { return getTypeWidth(Char32Type); }
getChar32Align()640   unsigned getChar32Align() const { return getTypeAlign(Char32Type); }
641 
642   /// getHalfWidth/Align/Format - Return the size/align/format of 'half'.
getHalfWidth()643   unsigned getHalfWidth() const { return HalfWidth; }
getHalfAlign()644   unsigned getHalfAlign() const { return HalfAlign; }
getHalfFormat()645   const llvm::fltSemantics &getHalfFormat() const { return *HalfFormat; }
646 
647   /// getFloatWidth/Align/Format - Return the size/align/format of 'float'.
getFloatWidth()648   unsigned getFloatWidth() const { return FloatWidth; }
getFloatAlign()649   unsigned getFloatAlign() const { return FloatAlign; }
getFloatFormat()650   const llvm::fltSemantics &getFloatFormat() const { return *FloatFormat; }
651 
652   /// getBFloat16Width/Align/Format - Return the size/align/format of '__bf16'.
getBFloat16Width()653   unsigned getBFloat16Width() const { return BFloat16Width; }
getBFloat16Align()654   unsigned getBFloat16Align() const { return BFloat16Align; }
getBFloat16Format()655   const llvm::fltSemantics &getBFloat16Format() const { return *BFloat16Format; }
656 
657   /// getDoubleWidth/Align/Format - Return the size/align/format of 'double'.
getDoubleWidth()658   unsigned getDoubleWidth() const { return DoubleWidth; }
getDoubleAlign()659   unsigned getDoubleAlign() const { return DoubleAlign; }
getDoubleFormat()660   const llvm::fltSemantics &getDoubleFormat() const { return *DoubleFormat; }
661 
662   /// getLongDoubleWidth/Align/Format - Return the size/align/format of 'long
663   /// double'.
getLongDoubleWidth()664   unsigned getLongDoubleWidth() const { return LongDoubleWidth; }
getLongDoubleAlign()665   unsigned getLongDoubleAlign() const { return LongDoubleAlign; }
getLongDoubleFormat()666   const llvm::fltSemantics &getLongDoubleFormat() const {
667     return *LongDoubleFormat;
668   }
669 
670   /// getFloat128Width/Align/Format - Return the size/align/format of
671   /// '__float128'.
getFloat128Width()672   unsigned getFloat128Width() const { return 128; }
getFloat128Align()673   unsigned getFloat128Align() const { return Float128Align; }
getFloat128Format()674   const llvm::fltSemantics &getFloat128Format() const {
675     return *Float128Format;
676   }
677 
678   /// Return the mangled code of long double.
getLongDoubleMangling()679   virtual const char *getLongDoubleMangling() const { return "e"; }
680 
681   /// Return the mangled code of __float128.
getFloat128Mangling()682   virtual const char *getFloat128Mangling() const { return "g"; }
683 
684   /// Return the mangled code of bfloat.
getBFloat16Mangling()685   virtual const char *getBFloat16Mangling() const {
686     llvm_unreachable("bfloat not implemented on this target");
687   }
688 
689   /// Return the value for the C99 FLT_EVAL_METHOD macro.
getFloatEvalMethod()690   virtual unsigned getFloatEvalMethod() const { return 0; }
691 
692   // getLargeArrayMinWidth/Align - Return the minimum array size that is
693   // 'large' and its alignment.
getLargeArrayMinWidth()694   unsigned getLargeArrayMinWidth() const { return LargeArrayMinWidth; }
getLargeArrayAlign()695   unsigned getLargeArrayAlign() const { return LargeArrayAlign; }
696 
697   /// Return the maximum width lock-free atomic operation which will
698   /// ever be supported for the given target
getMaxAtomicPromoteWidth()699   unsigned getMaxAtomicPromoteWidth() const { return MaxAtomicPromoteWidth; }
700   /// Return the maximum width lock-free atomic operation which can be
701   /// inlined given the supported features of the given target.
getMaxAtomicInlineWidth()702   unsigned getMaxAtomicInlineWidth() const { return MaxAtomicInlineWidth; }
703   /// Set the maximum inline or promote width lock-free atomic operation
704   /// for the given target.
setMaxAtomicWidth()705   virtual void setMaxAtomicWidth() {}
706   /// Returns true if the given target supports lock-free atomic
707   /// operations at the specified width and alignment.
hasBuiltinAtomic(uint64_t AtomicSizeInBits,uint64_t AlignmentInBits)708   virtual bool hasBuiltinAtomic(uint64_t AtomicSizeInBits,
709                                 uint64_t AlignmentInBits) const {
710     return AtomicSizeInBits <= AlignmentInBits &&
711            AtomicSizeInBits <= getMaxAtomicInlineWidth() &&
712            (AtomicSizeInBits <= getCharWidth() ||
713             llvm::isPowerOf2_64(AtomicSizeInBits / getCharWidth()));
714   }
715 
716   /// Return the maximum vector alignment supported for the given target.
getMaxVectorAlign()717   unsigned getMaxVectorAlign() const { return MaxVectorAlign; }
718   /// Return default simd alignment for the given target. Generally, this
719   /// value is type-specific, but this alignment can be used for most of the
720   /// types for the given target.
getSimdDefaultAlign()721   unsigned getSimdDefaultAlign() const { return SimdDefaultAlign; }
722 
getMaxOpenCLWorkGroupSize()723   unsigned getMaxOpenCLWorkGroupSize() const { return MaxOpenCLWorkGroupSize; }
724 
725   /// Return the alignment (in bits) of the thrown exception object. This is
726   /// only meaningful for targets that allocate C++ exceptions in a system
727   /// runtime, such as those using the Itanium C++ ABI.
getExnObjectAlignment()728   virtual unsigned getExnObjectAlignment() const {
729     // Itanium says that an _Unwind_Exception has to be "double-word"
730     // aligned (and thus the end of it is also so-aligned), meaning 16
731     // bytes.  Of course, that was written for the actual Itanium,
732     // which is a 64-bit platform.  Classically, the ABI doesn't really
733     // specify the alignment on other platforms, but in practice
734     // libUnwind declares the struct with __attribute__((aligned)), so
735     // we assume that alignment here.  (It's generally 16 bytes, but
736     // some targets overwrite it.)
737     return getDefaultAlignForAttributeAligned();
738   }
739 
740   /// Return the size of intmax_t and uintmax_t for this target, in bits.
getIntMaxTWidth()741   unsigned getIntMaxTWidth() const {
742     return getTypeWidth(IntMaxType);
743   }
744 
745   // Return the size of unwind_word for this target.
getUnwindWordWidth()746   virtual unsigned getUnwindWordWidth() const { return getPointerWidth(0); }
747 
748   /// Return the "preferred" register width on this target.
getRegisterWidth()749   virtual unsigned getRegisterWidth() const {
750     // Currently we assume the register width on the target matches the pointer
751     // width, we can introduce a new variable for this if/when some target wants
752     // it.
753     return PointerWidth;
754   }
755 
756   /// \brief Returns the default value of the __USER_LABEL_PREFIX__ macro,
757   /// which is the prefix given to user symbols by default.
758   ///
759   /// On most platforms this is "", but it is "_" on some.
getUserLabelPrefix()760   const char *getUserLabelPrefix() const { return UserLabelPrefix; }
761 
762   /// Returns the name of the mcount instrumentation function.
getMCountName()763   const char *getMCountName() const {
764     return MCountName;
765   }
766 
767   /// Check if the Objective-C built-in boolean type should be signed
768   /// char.
769   ///
770   /// Otherwise, if this returns false, the normal built-in boolean type
771   /// should also be used for Objective-C.
useSignedCharForObjCBool()772   bool useSignedCharForObjCBool() const {
773     return UseSignedCharForObjCBool;
774   }
noSignedCharForObjCBool()775   void noSignedCharForObjCBool() {
776     UseSignedCharForObjCBool = false;
777   }
778 
779   /// Check whether the alignment of bit-field types is respected
780   /// when laying out structures.
useBitFieldTypeAlignment()781   bool useBitFieldTypeAlignment() const {
782     return UseBitFieldTypeAlignment;
783   }
784 
785   /// Check whether zero length bitfields should force alignment of
786   /// the next member.
useZeroLengthBitfieldAlignment()787   bool useZeroLengthBitfieldAlignment() const {
788     return UseZeroLengthBitfieldAlignment;
789   }
790 
791   /// Check whether zero length bitfield alignment is respected if they are
792   /// leading members.
useLeadingZeroLengthBitfield()793   bool useLeadingZeroLengthBitfield() const {
794     return UseLeadingZeroLengthBitfield;
795   }
796 
797   /// Get the fixed alignment value in bits for a member that follows
798   /// a zero length bitfield.
getZeroLengthBitfieldBoundary()799   unsigned getZeroLengthBitfieldBoundary() const {
800     return ZeroLengthBitfieldBoundary;
801   }
802 
803   /// Get the maximum alignment in bits for a static variable with
804   /// aligned attribute.
getMaxAlignedAttribute()805   unsigned getMaxAlignedAttribute() const { return MaxAlignedAttribute; }
806 
807   /// Check whether explicit bitfield alignment attributes should be
808   //  honored, as in "__attribute__((aligned(2))) int b : 1;".
useExplicitBitFieldAlignment()809   bool useExplicitBitFieldAlignment() const {
810     return UseExplicitBitFieldAlignment;
811   }
812 
813   /// Check whether this target support '\#pragma options align=mac68k'.
hasAlignMac68kSupport()814   bool hasAlignMac68kSupport() const {
815     return HasAlignMac68kSupport;
816   }
817 
818   /// Return the user string for the specified integer type enum.
819   ///
820   /// For example, SignedShort -> "short".
821   static const char *getTypeName(IntType T);
822 
823   /// Return the constant suffix for the specified integer type enum.
824   ///
825   /// For example, SignedLong -> "L".
826   const char *getTypeConstantSuffix(IntType T) const;
827 
828   /// Return the printf format modifier for the specified
829   /// integer type enum.
830   ///
831   /// For example, SignedLong -> "l".
832   static const char *getTypeFormatModifier(IntType T);
833 
834   /// Check whether the given real type should use the "fpret" flavor of
835   /// Objective-C message passing on this target.
useObjCFPRetForRealType(RealType T)836   bool useObjCFPRetForRealType(RealType T) const {
837     return RealTypeUsesObjCFPRet & (1 << T);
838   }
839 
840   /// Check whether _Complex long double should use the "fp2ret" flavor
841   /// of Objective-C message passing on this target.
useObjCFP2RetForComplexLongDouble()842   bool useObjCFP2RetForComplexLongDouble() const {
843     return ComplexLongDoubleUsesFP2Ret;
844   }
845 
846   /// Check whether llvm intrinsics such as llvm.convert.to.fp16 should be used
847   /// to convert to and from __fp16.
848   /// FIXME: This function should be removed once all targets stop using the
849   /// conversion intrinsics.
useFP16ConversionIntrinsics()850   virtual bool useFP16ConversionIntrinsics() const {
851     return true;
852   }
853 
854   /// Specify if mangling based on address space map should be used or
855   /// not for language specific address spaces
useAddressSpaceMapMangling()856   bool useAddressSpaceMapMangling() const {
857     return UseAddrSpaceMapMangling;
858   }
859 
860   ///===---- Other target property query methods --------------------------===//
861 
862   /// Appends the target-specific \#define values for this
863   /// target set to the specified buffer.
864   virtual void getTargetDefines(const LangOptions &Opts,
865                                 MacroBuilder &Builder) const = 0;
866 
867 
868   /// Return information about target-specific builtins for
869   /// the current primary target, and info about which builtins are non-portable
870   /// across the current set of primary and secondary targets.
871   virtual ArrayRef<Builtin::Info> getTargetBuiltins() const = 0;
872 
873   /// The __builtin_clz* and __builtin_ctz* built-in
874   /// functions are specified to have undefined results for zero inputs, but
875   /// on targets that support these operations in a way that provides
876   /// well-defined results for zero without loss of performance, it is a good
877   /// idea to avoid optimizing based on that undef behavior.
isCLZForZeroUndef()878   virtual bool isCLZForZeroUndef() const { return true; }
879 
880   /// Returns the kind of __builtin_va_list type that should be used
881   /// with this target.
882   virtual BuiltinVaListKind getBuiltinVaListKind() const = 0;
883 
884   /// Returns whether or not type \c __builtin_ms_va_list type is
885   /// available on this target.
hasBuiltinMSVaList()886   bool hasBuiltinMSVaList() const { return HasBuiltinMSVaList; }
887 
888   /// Returns true for RenderScript.
isRenderScriptTarget()889   bool isRenderScriptTarget() const { return IsRenderScriptTarget; }
890 
891   /// Returns whether or not the AArch64 SVE built-in types are
892   /// available on this target.
hasAArch64SVETypes()893   bool hasAArch64SVETypes() const { return HasAArch64SVETypes; }
894 
895   /// Returns whether or not the RISC-V V built-in types are
896   /// available on this target.
hasRISCVVTypes()897   bool hasRISCVVTypes() const { return HasRISCVVTypes; }
898 
899   /// Returns whether or not the AMDGPU unsafe floating point atomics are
900   /// allowed.
allowAMDGPUUnsafeFPAtomics()901   bool allowAMDGPUUnsafeFPAtomics() const { return AllowAMDGPUUnsafeFPAtomics; }
902 
903   /// For ARM targets returns a mask defining which coprocessors are configured
904   /// as Custom Datapath.
getARMCDECoprocMask()905   uint32_t getARMCDECoprocMask() const { return ARMCDECoprocMask; }
906 
907   /// Returns whether the passed in string is a valid clobber in an
908   /// inline asm statement.
909   ///
910   /// This is used by Sema.
911   bool isValidClobber(StringRef Name) const;
912 
913   /// Returns whether the passed in string is a valid register name
914   /// according to GCC.
915   ///
916   /// This is used by Sema for inline asm statements.
917   virtual bool isValidGCCRegisterName(StringRef Name) const;
918 
919   /// Returns the "normalized" GCC register name.
920   ///
921   /// ReturnCannonical true will return the register name without any additions
922   /// such as "{}" or "%" in it's canonical form, for example:
923   /// ReturnCanonical = true and Name = "rax", will return "ax".
924   StringRef getNormalizedGCCRegisterName(StringRef Name,
925                                          bool ReturnCanonical = false) const;
926 
isSPRegName(StringRef)927   virtual bool isSPRegName(StringRef) const { return false; }
928 
929   /// Extracts a register from the passed constraint (if it is a
930   /// single-register constraint) and the asm label expression related to a
931   /// variable in the input or output list of an inline asm statement.
932   ///
933   /// This function is used by Sema in order to diagnose conflicts between
934   /// the clobber list and the input/output lists.
getConstraintRegister(StringRef Constraint,StringRef Expression)935   virtual StringRef getConstraintRegister(StringRef Constraint,
936                                           StringRef Expression) const {
937     return "";
938   }
939 
940   struct ConstraintInfo {
941     enum {
942       CI_None = 0x00,
943       CI_AllowsMemory = 0x01,
944       CI_AllowsRegister = 0x02,
945       CI_ReadWrite = 0x04,         // "+r" output constraint (read and write).
946       CI_HasMatchingInput = 0x08,  // This output operand has a matching input.
947       CI_ImmediateConstant = 0x10, // This operand must be an immediate constant
948       CI_EarlyClobber = 0x20,      // "&" output constraint (early clobber).
949     };
950     unsigned Flags;
951     int TiedOperand;
952     struct {
953       int Min;
954       int Max;
955       bool isConstrained;
956     } ImmRange;
957     llvm::SmallSet<int, 4> ImmSet;
958 
959     std::string ConstraintStr;  // constraint: "=rm"
960     std::string Name;           // Operand name: [foo] with no []'s.
961   public:
ConstraintInfoConstraintInfo962     ConstraintInfo(StringRef ConstraintStr, StringRef Name)
963         : Flags(0), TiedOperand(-1), ConstraintStr(ConstraintStr.str()),
964           Name(Name.str()) {
965       ImmRange.Min = ImmRange.Max = 0;
966       ImmRange.isConstrained = false;
967     }
968 
getConstraintStrConstraintInfo969     const std::string &getConstraintStr() const { return ConstraintStr; }
getNameConstraintInfo970     const std::string &getName() const { return Name; }
isReadWriteConstraintInfo971     bool isReadWrite() const { return (Flags & CI_ReadWrite) != 0; }
earlyClobberConstraintInfo972     bool earlyClobber() { return (Flags & CI_EarlyClobber) != 0; }
allowsRegisterConstraintInfo973     bool allowsRegister() const { return (Flags & CI_AllowsRegister) != 0; }
allowsMemoryConstraintInfo974     bool allowsMemory() const { return (Flags & CI_AllowsMemory) != 0; }
975 
976     /// Return true if this output operand has a matching
977     /// (tied) input operand.
hasMatchingInputConstraintInfo978     bool hasMatchingInput() const { return (Flags & CI_HasMatchingInput) != 0; }
979 
980     /// Return true if this input operand is a matching
981     /// constraint that ties it to an output operand.
982     ///
983     /// If this returns true then getTiedOperand will indicate which output
984     /// operand this is tied to.
hasTiedOperandConstraintInfo985     bool hasTiedOperand() const { return TiedOperand != -1; }
getTiedOperandConstraintInfo986     unsigned getTiedOperand() const {
987       assert(hasTiedOperand() && "Has no tied operand!");
988       return (unsigned)TiedOperand;
989     }
990 
requiresImmediateConstantConstraintInfo991     bool requiresImmediateConstant() const {
992       return (Flags & CI_ImmediateConstant) != 0;
993     }
isValidAsmImmediateConstraintInfo994     bool isValidAsmImmediate(const llvm::APInt &Value) const {
995       if (!ImmSet.empty())
996         return Value.isSignedIntN(32) &&
997                ImmSet.count(Value.getZExtValue()) != 0;
998       return !ImmRange.isConstrained ||
999              (Value.sge(ImmRange.Min) && Value.sle(ImmRange.Max));
1000     }
1001 
setIsReadWriteConstraintInfo1002     void setIsReadWrite() { Flags |= CI_ReadWrite; }
setEarlyClobberConstraintInfo1003     void setEarlyClobber() { Flags |= CI_EarlyClobber; }
setAllowsMemoryConstraintInfo1004     void setAllowsMemory() { Flags |= CI_AllowsMemory; }
setAllowsRegisterConstraintInfo1005     void setAllowsRegister() { Flags |= CI_AllowsRegister; }
setHasMatchingInputConstraintInfo1006     void setHasMatchingInput() { Flags |= CI_HasMatchingInput; }
setRequiresImmediateConstraintInfo1007     void setRequiresImmediate(int Min, int Max) {
1008       Flags |= CI_ImmediateConstant;
1009       ImmRange.Min = Min;
1010       ImmRange.Max = Max;
1011       ImmRange.isConstrained = true;
1012     }
setRequiresImmediateConstraintInfo1013     void setRequiresImmediate(llvm::ArrayRef<int> Exacts) {
1014       Flags |= CI_ImmediateConstant;
1015       for (int Exact : Exacts)
1016         ImmSet.insert(Exact);
1017     }
setRequiresImmediateConstraintInfo1018     void setRequiresImmediate(int Exact) {
1019       Flags |= CI_ImmediateConstant;
1020       ImmSet.insert(Exact);
1021     }
setRequiresImmediateConstraintInfo1022     void setRequiresImmediate() {
1023       Flags |= CI_ImmediateConstant;
1024     }
1025 
1026     /// Indicate that this is an input operand that is tied to
1027     /// the specified output operand.
1028     ///
1029     /// Copy over the various constraint information from the output.
setTiedOperandConstraintInfo1030     void setTiedOperand(unsigned N, ConstraintInfo &Output) {
1031       Output.setHasMatchingInput();
1032       Flags = Output.Flags;
1033       TiedOperand = N;
1034       // Don't copy Name or constraint string.
1035     }
1036   };
1037 
1038   /// Validate register name used for global register variables.
1039   ///
1040   /// This function returns true if the register passed in RegName can be used
1041   /// for global register variables on this target. In addition, it returns
1042   /// true in HasSizeMismatch if the size of the register doesn't match the
1043   /// variable size passed in RegSize.
validateGlobalRegisterVariable(StringRef RegName,unsigned RegSize,bool & HasSizeMismatch)1044   virtual bool validateGlobalRegisterVariable(StringRef RegName,
1045                                               unsigned RegSize,
1046                                               bool &HasSizeMismatch) const {
1047     HasSizeMismatch = false;
1048     return true;
1049   }
1050 
1051   // validateOutputConstraint, validateInputConstraint - Checks that
1052   // a constraint is valid and provides information about it.
1053   // FIXME: These should return a real error instead of just true/false.
1054   bool validateOutputConstraint(ConstraintInfo &Info) const;
1055   bool validateInputConstraint(MutableArrayRef<ConstraintInfo> OutputConstraints,
1056                                ConstraintInfo &info) const;
1057 
validateOutputSize(const llvm::StringMap<bool> & FeatureMap,StringRef,unsigned)1058   virtual bool validateOutputSize(const llvm::StringMap<bool> &FeatureMap,
1059                                   StringRef /*Constraint*/,
1060                                   unsigned /*Size*/) const {
1061     return true;
1062   }
1063 
validateInputSize(const llvm::StringMap<bool> & FeatureMap,StringRef,unsigned)1064   virtual bool validateInputSize(const llvm::StringMap<bool> &FeatureMap,
1065                                  StringRef /*Constraint*/,
1066                                  unsigned /*Size*/) const {
1067     return true;
1068   }
1069   virtual bool
validateConstraintModifier(StringRef,char,unsigned,std::string &)1070   validateConstraintModifier(StringRef /*Constraint*/,
1071                              char /*Modifier*/,
1072                              unsigned /*Size*/,
1073                              std::string &/*SuggestedModifier*/) const {
1074     return true;
1075   }
1076   virtual bool
1077   validateAsmConstraint(const char *&Name,
1078                         TargetInfo::ConstraintInfo &info) const = 0;
1079 
1080   bool resolveSymbolicName(const char *&Name,
1081                            ArrayRef<ConstraintInfo> OutputConstraints,
1082                            unsigned &Index) const;
1083 
1084   // Constraint parm will be left pointing at the last character of
1085   // the constraint.  In practice, it won't be changed unless the
1086   // constraint is longer than one character.
convertConstraint(const char * & Constraint)1087   virtual std::string convertConstraint(const char *&Constraint) const {
1088     // 'p' defaults to 'r', but can be overridden by targets.
1089     if (*Constraint == 'p')
1090       return std::string("r");
1091     return std::string(1, *Constraint);
1092   }
1093 
1094   /// Returns a string of target-specific clobbers, in LLVM format.
1095   virtual const char *getClobbers() const = 0;
1096 
1097   /// Returns true if NaN encoding is IEEE 754-2008.
1098   /// Only MIPS allows a different encoding.
isNan2008()1099   virtual bool isNan2008() const {
1100     return true;
1101   }
1102 
1103   /// Returns the target triple of the primary target.
getTriple()1104   const llvm::Triple &getTriple() const {
1105     return Triple;
1106   }
1107 
1108   /// Returns the target ID if supported.
getTargetID()1109   virtual llvm::Optional<std::string> getTargetID() const { return llvm::None; }
1110 
getDataLayoutString()1111   const char *getDataLayoutString() const {
1112     assert(!DataLayoutString.empty() && "Uninitialized DataLayout!");
1113     return DataLayoutString.c_str();
1114   }
1115 
1116   struct GCCRegAlias {
1117     const char * const Aliases[5];
1118     const char * const Register;
1119   };
1120 
1121   struct AddlRegName {
1122     const char * const Names[5];
1123     const unsigned RegNum;
1124   };
1125 
1126   /// Does this target support "protected" visibility?
1127   ///
1128   /// Any target which dynamic libraries will naturally support
1129   /// something like "default" (meaning that the symbol is visible
1130   /// outside this shared object) and "hidden" (meaning that it isn't)
1131   /// visibilities, but "protected" is really an ELF-specific concept
1132   /// with weird semantics designed around the convenience of dynamic
1133   /// linker implementations.  Which is not to suggest that there's
1134   /// consistent target-independent semantics for "default" visibility
1135   /// either; the entire thing is pretty badly mangled.
hasProtectedVisibility()1136   virtual bool hasProtectedVisibility() const { return true; }
1137 
1138   /// Does this target aim for semantic compatibility with
1139   /// Microsoft C++ code using dllimport/export attributes?
shouldDLLImportComdatSymbols()1140   virtual bool shouldDLLImportComdatSymbols() const {
1141     return getTriple().isWindowsMSVCEnvironment() ||
1142            getTriple().isWindowsItaniumEnvironment() || getTriple().isPS4CPU();
1143   }
1144 
1145   // Does this target have PS4 specific dllimport/export handling?
hasPS4DLLImportExport()1146   virtual bool hasPS4DLLImportExport() const {
1147     return getTriple().isPS4CPU() ||
1148            // Windows Itanium support allows for testing the SCEI flavour of
1149            // dllimport/export handling on a Windows system.
1150            (getTriple().isWindowsItaniumEnvironment() &&
1151             getTriple().getVendor() == llvm::Triple::SCEI);
1152   }
1153 
1154   /// Set forced language options.
1155   ///
1156   /// Apply changes to the target information with respect to certain
1157   /// language options which change the target configuration and adjust
1158   /// the language based on the target options where applicable.
1159   virtual void adjust(LangOptions &Opts);
1160 
1161   /// Adjust target options based on codegen options.
adjustTargetOptions(const CodeGenOptions & CGOpts,TargetOptions & TargetOpts)1162   virtual void adjustTargetOptions(const CodeGenOptions &CGOpts,
1163                                    TargetOptions &TargetOpts) const {}
1164 
1165   /// Initialize the map with the default set of target features for the
1166   /// CPU this should include all legal feature strings on the target.
1167   ///
1168   /// \return False on error (invalid features).
1169   virtual bool initFeatureMap(llvm::StringMap<bool> &Features,
1170                               DiagnosticsEngine &Diags, StringRef CPU,
1171                               const std::vector<std::string> &FeatureVec) const;
1172 
1173   /// Get the ABI currently in use.
getABI()1174   virtual StringRef getABI() const { return StringRef(); }
1175 
1176   /// Get the C++ ABI currently in use.
getCXXABI()1177   TargetCXXABI getCXXABI() const {
1178     return TheCXXABI;
1179   }
1180 
1181   /// Target the specified CPU.
1182   ///
1183   /// \return  False on error (invalid CPU name).
setCPU(const std::string & Name)1184   virtual bool setCPU(const std::string &Name) {
1185     return false;
1186   }
1187 
1188   /// Fill a SmallVectorImpl with the valid values to setCPU.
fillValidCPUList(SmallVectorImpl<StringRef> & Values)1189   virtual void fillValidCPUList(SmallVectorImpl<StringRef> &Values) const {}
1190 
1191   /// Fill a SmallVectorImpl with the valid values for tuning CPU.
fillValidTuneCPUList(SmallVectorImpl<StringRef> & Values)1192   virtual void fillValidTuneCPUList(SmallVectorImpl<StringRef> &Values) const {
1193     fillValidCPUList(Values);
1194   }
1195 
1196   /// brief Determine whether this TargetInfo supports the given CPU name.
isValidCPUName(StringRef Name)1197   virtual bool isValidCPUName(StringRef Name) const {
1198     return true;
1199   }
1200 
1201   /// brief Determine whether this TargetInfo supports the given CPU name for
1202   // tuning.
isValidTuneCPUName(StringRef Name)1203   virtual bool isValidTuneCPUName(StringRef Name) const {
1204     return isValidCPUName(Name);
1205   }
1206 
1207   /// brief Determine whether this TargetInfo supports tune in target attribute.
supportsTargetAttributeTune()1208   virtual bool supportsTargetAttributeTune() const {
1209     return false;
1210   }
1211 
1212   /// Use the specified ABI.
1213   ///
1214   /// \return False on error (invalid ABI name).
setABI(const std::string & Name)1215   virtual bool setABI(const std::string &Name) {
1216     return false;
1217   }
1218 
1219   /// Use the specified unit for FP math.
1220   ///
1221   /// \return False on error (invalid unit name).
setFPMath(StringRef Name)1222   virtual bool setFPMath(StringRef Name) {
1223     return false;
1224   }
1225 
1226   /// Check if target has a given feature enabled
hasFeatureEnabled(const llvm::StringMap<bool> & Features,StringRef Name)1227   virtual bool hasFeatureEnabled(const llvm::StringMap<bool> &Features,
1228                                  StringRef Name) const {
1229     return Features.lookup(Name);
1230   }
1231 
1232   /// Enable or disable a specific target feature;
1233   /// the feature name must be valid.
setFeatureEnabled(llvm::StringMap<bool> & Features,StringRef Name,bool Enabled)1234   virtual void setFeatureEnabled(llvm::StringMap<bool> &Features,
1235                                  StringRef Name,
1236                                  bool Enabled) const {
1237     Features[Name] = Enabled;
1238   }
1239 
1240   /// Determine whether this TargetInfo supports the given feature.
isValidFeatureName(StringRef Feature)1241   virtual bool isValidFeatureName(StringRef Feature) const {
1242     return true;
1243   }
1244 
1245   struct BranchProtectionInfo {
1246     LangOptions::SignReturnAddressScopeKind SignReturnAddr =
1247         LangOptions::SignReturnAddressScopeKind::None;
1248     LangOptions::SignReturnAddressKeyKind SignKey =
1249         LangOptions::SignReturnAddressKeyKind::AKey;
1250     bool BranchTargetEnforcement = false;
1251   };
1252 
1253   /// Determine if this TargetInfo supports the given branch protection
1254   /// specification
validateBranchProtection(StringRef Spec,BranchProtectionInfo & BPI,StringRef & Err)1255   virtual bool validateBranchProtection(StringRef Spec,
1256                                         BranchProtectionInfo &BPI,
1257                                         StringRef &Err) const {
1258     Err = "";
1259     return false;
1260   }
1261 
1262   /// Perform initialization based on the user configured
1263   /// set of features (e.g., +sse4).
1264   ///
1265   /// The list is guaranteed to have at most one entry per feature.
1266   ///
1267   /// The target may modify the features list, to change which options are
1268   /// passed onwards to the backend.
1269   /// FIXME: This part should be fixed so that we can change handleTargetFeatures
1270   /// to merely a TargetInfo initialization routine.
1271   ///
1272   /// \return  False on error.
handleTargetFeatures(std::vector<std::string> & Features,DiagnosticsEngine & Diags)1273   virtual bool handleTargetFeatures(std::vector<std::string> &Features,
1274                                     DiagnosticsEngine &Diags) {
1275     return true;
1276   }
1277 
1278   /// Determine whether the given target has the given feature.
hasFeature(StringRef Feature)1279   virtual bool hasFeature(StringRef Feature) const {
1280     return false;
1281   }
1282 
1283   /// Identify whether this target supports multiversioning of functions,
1284   /// which requires support for cpu_supports and cpu_is functionality.
supportsMultiVersioning()1285   bool supportsMultiVersioning() const { return getTriple().isX86(); }
1286 
1287   /// Identify whether this target supports IFuncs.
supportsIFunc()1288   bool supportsIFunc() const { return getTriple().isOSBinFormatELF(); }
1289 
1290   // Validate the contents of the __builtin_cpu_supports(const char*)
1291   // argument.
validateCpuSupports(StringRef Name)1292   virtual bool validateCpuSupports(StringRef Name) const { return false; }
1293 
1294   // Return the target-specific priority for features/cpus/vendors so
1295   // that they can be properly sorted for checking.
multiVersionSortPriority(StringRef Name)1296   virtual unsigned multiVersionSortPriority(StringRef Name) const {
1297     return 0;
1298   }
1299 
1300   // Validate the contents of the __builtin_cpu_is(const char*)
1301   // argument.
validateCpuIs(StringRef Name)1302   virtual bool validateCpuIs(StringRef Name) const { return false; }
1303 
1304   // Validate a cpu_dispatch/cpu_specific CPU option, which is a different list
1305   // from cpu_is, since it checks via features rather than CPUs directly.
validateCPUSpecificCPUDispatch(StringRef Name)1306   virtual bool validateCPUSpecificCPUDispatch(StringRef Name) const {
1307     return false;
1308   }
1309 
1310   // Get the character to be added for mangling purposes for cpu_specific.
CPUSpecificManglingCharacter(StringRef Name)1311   virtual char CPUSpecificManglingCharacter(StringRef Name) const {
1312     llvm_unreachable(
1313         "cpu_specific Multiversioning not implemented on this target");
1314   }
1315 
1316   // Get a list of the features that make up the CPU option for
1317   // cpu_specific/cpu_dispatch so that it can be passed to llvm as optimization
1318   // options.
getCPUSpecificCPUDispatchFeatures(StringRef Name,llvm::SmallVectorImpl<StringRef> & Features)1319   virtual void getCPUSpecificCPUDispatchFeatures(
1320       StringRef Name, llvm::SmallVectorImpl<StringRef> &Features) const {
1321     llvm_unreachable(
1322         "cpu_specific Multiversioning not implemented on this target");
1323   }
1324 
1325   // Get the cache line size of a given cpu. This method switches over
1326   // the given cpu and returns "None" if the CPU is not found.
getCPUCacheLineSize()1327   virtual Optional<unsigned> getCPUCacheLineSize() const { return None; }
1328 
1329   // Returns maximal number of args passed in registers.
getRegParmMax()1330   unsigned getRegParmMax() const {
1331     assert(RegParmMax < 7 && "RegParmMax value is larger than AST can handle");
1332     return RegParmMax;
1333   }
1334 
1335   /// Whether the target supports thread-local storage.
isTLSSupported()1336   bool isTLSSupported() const {
1337     return TLSSupported;
1338   }
1339 
1340   /// Return the maximum alignment (in bits) of a TLS variable
1341   ///
1342   /// Gets the maximum alignment (in bits) of a TLS variable on this target.
1343   /// Returns zero if there is no such constraint.
getMaxTLSAlign()1344   unsigned getMaxTLSAlign() const { return MaxTLSAlign; }
1345 
1346   /// Whether target supports variable-length arrays.
isVLASupported()1347   bool isVLASupported() const { return VLASupported; }
1348 
1349   /// Whether the target supports SEH __try.
isSEHTrySupported()1350   bool isSEHTrySupported() const {
1351     return getTriple().isOSWindows() &&
1352            (getTriple().isX86() ||
1353             getTriple().getArch() == llvm::Triple::aarch64);
1354   }
1355 
1356   /// Return true if {|} are normal characters in the asm string.
1357   ///
1358   /// If this returns false (the default), then {abc|xyz} is syntax
1359   /// that says that when compiling for asm variant #0, "abc" should be
1360   /// generated, but when compiling for asm variant #1, "xyz" should be
1361   /// generated.
hasNoAsmVariants()1362   bool hasNoAsmVariants() const {
1363     return NoAsmVariants;
1364   }
1365 
1366   /// Return the register number that __builtin_eh_return_regno would
1367   /// return with the specified argument.
1368   /// This corresponds with TargetLowering's getExceptionPointerRegister
1369   /// and getExceptionSelectorRegister in the backend.
getEHDataRegisterNumber(unsigned RegNo)1370   virtual int getEHDataRegisterNumber(unsigned RegNo) const {
1371     return -1;
1372   }
1373 
1374   /// Return the section to use for C++ static initialization functions.
getStaticInitSectionSpecifier()1375   virtual const char *getStaticInitSectionSpecifier() const {
1376     return nullptr;
1377   }
1378 
getAddressSpaceMap()1379   const LangASMap &getAddressSpaceMap() const { return *AddrSpaceMap; }
1380 
1381   /// Map from the address space field in builtin description strings to the
1382   /// language address space.
getOpenCLBuiltinAddressSpace(unsigned AS)1383   virtual LangAS getOpenCLBuiltinAddressSpace(unsigned AS) const {
1384     return getLangASFromTargetAS(AS);
1385   }
1386 
1387   /// Map from the address space field in builtin description strings to the
1388   /// language address space.
getCUDABuiltinAddressSpace(unsigned AS)1389   virtual LangAS getCUDABuiltinAddressSpace(unsigned AS) const {
1390     return getLangASFromTargetAS(AS);
1391   }
1392 
1393   /// Return an AST address space which can be used opportunistically
1394   /// for constant global memory. It must be possible to convert pointers into
1395   /// this address space to LangAS::Default. If no such address space exists,
1396   /// this may return None, and such optimizations will be disabled.
getConstantAddressSpace()1397   virtual llvm::Optional<LangAS> getConstantAddressSpace() const {
1398     return LangAS::Default;
1399   }
1400 
1401   /// Return a target-specific GPU grid value based on the GVIDX enum \p gv
getGridValue(llvm::omp::GVIDX gv)1402   unsigned getGridValue(llvm::omp::GVIDX gv) const {
1403     assert(GridValues != nullptr && "GridValues not initialized");
1404     return GridValues[gv];
1405   }
1406 
1407   /// Retrieve the name of the platform as it is used in the
1408   /// availability attribute.
getPlatformName()1409   StringRef getPlatformName() const { return PlatformName; }
1410 
1411   /// Retrieve the minimum desired version of the platform, to
1412   /// which the program should be compiled.
getPlatformMinVersion()1413   VersionTuple getPlatformMinVersion() const { return PlatformMinVersion; }
1414 
isBigEndian()1415   bool isBigEndian() const { return BigEndian; }
isLittleEndian()1416   bool isLittleEndian() const { return !BigEndian; }
1417 
1418   /// Whether the option -fextend-arguments={32,64} is supported on the target.
supportsExtendIntArgs()1419   virtual bool supportsExtendIntArgs() const { return false; }
1420 
1421   /// Gets the default calling convention for the given target and
1422   /// declaration context.
getDefaultCallingConv()1423   virtual CallingConv getDefaultCallingConv() const {
1424     // Not all targets will specify an explicit calling convention that we can
1425     // express.  This will always do the right thing, even though it's not
1426     // an explicit calling convention.
1427     return CC_C;
1428   }
1429 
1430   enum CallingConvCheckResult {
1431     CCCR_OK,
1432     CCCR_Warning,
1433     CCCR_Ignore,
1434     CCCR_Error,
1435   };
1436 
1437   /// Determines whether a given calling convention is valid for the
1438   /// target. A calling convention can either be accepted, produce a warning
1439   /// and be substituted with the default calling convention, or (someday)
1440   /// produce an error (such as using thiscall on a non-instance function).
checkCallingConvention(CallingConv CC)1441   virtual CallingConvCheckResult checkCallingConvention(CallingConv CC) const {
1442     switch (CC) {
1443       default:
1444         return CCCR_Warning;
1445       case CC_C:
1446         return CCCR_OK;
1447     }
1448   }
1449 
1450   enum CallingConvKind {
1451     CCK_Default,
1452     CCK_ClangABI4OrPS4,
1453     CCK_MicrosoftWin64
1454   };
1455 
1456   virtual CallingConvKind getCallingConvKind(bool ClangABICompat4) const;
1457 
1458   /// Controls if __builtin_longjmp / __builtin_setjmp can be lowered to
1459   /// llvm.eh.sjlj.longjmp / llvm.eh.sjlj.setjmp.
hasSjLjLowering()1460   virtual bool hasSjLjLowering() const {
1461     return false;
1462   }
1463 
1464   /// Check if the target supports CFProtection branch.
1465   virtual bool
1466   checkCFProtectionBranchSupported(DiagnosticsEngine &Diags) const;
1467 
1468   /// Check if the target supports CFProtection branch.
1469   virtual bool
1470   checkCFProtectionReturnSupported(DiagnosticsEngine &Diags) const;
1471 
1472   /// Whether target allows to overalign ABI-specified preferred alignment
allowsLargerPreferedTypeAlignment()1473   virtual bool allowsLargerPreferedTypeAlignment() const { return true; }
1474 
1475   /// Whether target defaults to the `power` alignment rules of AIX.
defaultsToAIXPowerAlignment()1476   virtual bool defaultsToAIXPowerAlignment() const { return false; }
1477 
1478   /// Set supported OpenCL extensions and optional core features.
setSupportedOpenCLOpts()1479   virtual void setSupportedOpenCLOpts() {}
1480 
1481   virtual void supportAllOpenCLOpts(bool V = true) {
1482 #define OPENCLEXTNAME(Ext)                                                     \
1483   setFeatureEnabled(getTargetOpts().OpenCLFeaturesMap, #Ext, V);
1484 #include "clang/Basic/OpenCLExtensions.def"
1485   }
1486 
1487   /// Set supported OpenCL extensions as written on command line
setCommandLineOpenCLOpts()1488   virtual void setCommandLineOpenCLOpts() {
1489     for (const auto &Ext : getTargetOpts().OpenCLExtensionsAsWritten) {
1490       bool IsPrefixed = (Ext[0] == '+' || Ext[0] == '-');
1491       std::string Name = IsPrefixed ? Ext.substr(1) : Ext;
1492       bool V = IsPrefixed ? Ext[0] == '+' : true;
1493 
1494       if (Name == "all") {
1495         supportAllOpenCLOpts(V);
1496         continue;
1497       }
1498 
1499       getTargetOpts().OpenCLFeaturesMap[Name] = V;
1500     }
1501   }
1502 
1503   /// Get supported OpenCL extensions and optional core features.
getSupportedOpenCLOpts()1504   llvm::StringMap<bool> &getSupportedOpenCLOpts() {
1505     return getTargetOpts().OpenCLFeaturesMap;
1506   }
1507 
1508   /// Get const supported OpenCL extensions and optional core features.
getSupportedOpenCLOpts()1509   const llvm::StringMap<bool> &getSupportedOpenCLOpts() const {
1510     return getTargetOpts().OpenCLFeaturesMap;
1511   }
1512 
1513   /// Get address space for OpenCL type.
1514   virtual LangAS getOpenCLTypeAddrSpace(OpenCLTypeKind TK) const;
1515 
1516   /// \returns Target specific vtbl ptr address space.
getVtblPtrAddressSpace()1517   virtual unsigned getVtblPtrAddressSpace() const {
1518     return 0;
1519   }
1520 
1521   /// \returns If a target requires an address within a target specific address
1522   /// space \p AddressSpace to be converted in order to be used, then return the
1523   /// corresponding target specific DWARF address space.
1524   ///
1525   /// \returns Otherwise return None and no conversion will be emitted in the
1526   /// DWARF.
getDWARFAddressSpace(unsigned AddressSpace)1527   virtual Optional<unsigned> getDWARFAddressSpace(unsigned AddressSpace) const {
1528     return None;
1529   }
1530 
1531   /// \returns The version of the SDK which was used during the compilation if
1532   /// one was specified, or an empty version otherwise.
getSDKVersion()1533   const llvm::VersionTuple &getSDKVersion() const {
1534     return getTargetOpts().SDKVersion;
1535   }
1536 
1537   /// Check the target is valid after it is fully initialized.
validateTarget(DiagnosticsEngine & Diags)1538   virtual bool validateTarget(DiagnosticsEngine &Diags) const {
1539     return true;
1540   }
1541 
1542   /// Check that OpenCL target has valid options setting based on OpenCL
1543   /// version.
1544   virtual bool validateOpenCLTarget(const LangOptions &Opts,
1545                                     DiagnosticsEngine &Diags) const;
1546 
setAuxTarget(const TargetInfo * Aux)1547   virtual void setAuxTarget(const TargetInfo *Aux) {}
1548 
1549   /// Whether target allows debuginfo types for decl only variables/functions.
allowDebugInfoForExternalRef()1550   virtual bool allowDebugInfoForExternalRef() const { return false; }
1551 
1552 protected:
1553   /// Copy type and layout related info.
1554   void copyAuxTarget(const TargetInfo *Aux);
getPointerWidthV(unsigned AddrSpace)1555   virtual uint64_t getPointerWidthV(unsigned AddrSpace) const {
1556     return PointerWidth;
1557   }
getPointerAlignV(unsigned AddrSpace)1558   virtual uint64_t getPointerAlignV(unsigned AddrSpace) const {
1559     return PointerAlign;
1560   }
getPtrDiffTypeV(unsigned AddrSpace)1561   virtual enum IntType getPtrDiffTypeV(unsigned AddrSpace) const {
1562     return PtrDiffType;
1563   }
1564   virtual ArrayRef<const char *> getGCCRegNames() const = 0;
1565   virtual ArrayRef<GCCRegAlias> getGCCRegAliases() const = 0;
getGCCAddlRegNames()1566   virtual ArrayRef<AddlRegName> getGCCAddlRegNames() const {
1567     return None;
1568   }
1569 
1570  private:
1571   // Assert the values for the fractional and integral bits for each fixed point
1572   // type follow the restrictions given in clause 6.2.6.3 of N1169.
1573   void CheckFixedPointBits() const;
1574 };
1575 
1576 }  // end namespace clang
1577 
1578 #endif
1579