]> granicus.if.org Git - clang/blob - include/clang/Basic/TargetInfo.h
5885532b91db68a22972ba919410cdd92d582f96
[clang] / include / clang / Basic / TargetInfo.h
1 //===--- TargetInfo.h - Expose information about the target -----*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 ///
10 /// \file
11 /// \brief Defines the clang::TargetInfo interface.
12 ///
13 //===----------------------------------------------------------------------===//
14
15 #ifndef LLVM_CLANG_BASIC_TARGETINFO_H
16 #define LLVM_CLANG_BASIC_TARGETINFO_H
17
18 #include "clang/Basic/AddressSpaces.h"
19 #include "clang/Basic/LLVM.h"
20 #include "clang/Basic/Specifiers.h"
21 #include "clang/Basic/TargetCXXABI.h"
22 #include "clang/Basic/TargetOptions.h"
23 #include "clang/Basic/VersionTuple.h"
24 #include "llvm/ADT/APInt.h"
25 #include "llvm/ADT/IntrusiveRefCntPtr.h"
26 #include "llvm/ADT/Optional.h"
27 #include "llvm/ADT/SmallSet.h"
28 #include "llvm/ADT/StringMap.h"
29 #include "llvm/ADT/StringRef.h"
30 #include "llvm/ADT/Triple.h"
31 #include "llvm/IR/DataLayout.h"
32 #include "llvm/Support/DataTypes.h"
33 #include <cassert>
34 #include <string>
35 #include <vector>
36
37 namespace llvm {
38 struct fltSemantics;
39 }
40
41 namespace clang {
42 class DiagnosticsEngine;
43 class LangOptions;
44 class CodeGenOptions;
45 class MacroBuilder;
46 class QualType;
47 class SourceLocation;
48 class SourceManager;
49
50 namespace Builtin { struct Info; }
51
52 /// \brief Exposes information about the current target.
53 ///
54 class TargetInfo : public RefCountedBase<TargetInfo> {
55   std::shared_ptr<TargetOptions> TargetOpts;
56   llvm::Triple Triple;
57 protected:
58   // Target values set by the ctor of the actual target implementation.  Default
59   // values are specified by the TargetInfo constructor.
60   bool BigEndian;
61   bool TLSSupported;
62   bool NoAsmVariants;  // True if {|} are normal characters.
63   bool HasFloat128;
64   unsigned char PointerWidth, PointerAlign;
65   unsigned char BoolWidth, BoolAlign;
66   unsigned char IntWidth, IntAlign;
67   unsigned char HalfWidth, HalfAlign;
68   unsigned char FloatWidth, FloatAlign;
69   unsigned char DoubleWidth, DoubleAlign;
70   unsigned char LongDoubleWidth, LongDoubleAlign, Float128Align;
71   unsigned char LargeArrayMinWidth, LargeArrayAlign;
72   unsigned char LongWidth, LongAlign;
73   unsigned char LongLongWidth, LongLongAlign;
74   unsigned char SuitableAlign;
75   unsigned char DefaultAlignForAttributeAligned;
76   unsigned char MinGlobalAlign;
77   unsigned char MaxAtomicPromoteWidth, MaxAtomicInlineWidth;
78   unsigned short MaxVectorAlign;
79   unsigned short MaxTLSAlign;
80   unsigned short SimdDefaultAlign;
81   unsigned short NewAlign;
82   std::unique_ptr<llvm::DataLayout> DataLayout;
83   const char *MCountName;
84   const llvm::fltSemantics *HalfFormat, *FloatFormat, *DoubleFormat,
85     *LongDoubleFormat, *Float128Format;
86   unsigned char RegParmMax, SSERegParmMax;
87   TargetCXXABI TheCXXABI;
88   const LangAS::Map *AddrSpaceMap;
89
90   mutable StringRef PlatformName;
91   mutable VersionTuple PlatformMinVersion;
92
93   unsigned HasAlignMac68kSupport : 1;
94   unsigned RealTypeUsesObjCFPRet : 3;
95   unsigned ComplexLongDoubleUsesFP2Ret : 1;
96
97   unsigned HasBuiltinMSVaList : 1;
98
99   unsigned IsRenderScriptTarget : 1;
100
101   // TargetInfo Constructor.  Default initializes all fields.
102   TargetInfo(const llvm::Triple &T);
103
104   void resetDataLayout(StringRef DL) {
105     DataLayout.reset(new llvm::DataLayout(DL));
106   }
107
108 public:
109   /// \brief Construct a target for the given options.
110   ///
111   /// \param Opts - The options to use to initialize the target. The target may
112   /// modify the options to canonicalize the target feature information to match
113   /// what the backend expects.
114   static TargetInfo *
115   CreateTargetInfo(DiagnosticsEngine &Diags,
116                    const std::shared_ptr<TargetOptions> &Opts);
117
118   virtual ~TargetInfo();
119
120   /// \brief Retrieve the target options.
121   TargetOptions &getTargetOpts() const {
122     assert(TargetOpts && "Missing target options");
123     return *TargetOpts;
124   }
125
126   ///===---- Target Data Type Query Methods -------------------------------===//
127   enum IntType {
128     NoInt = 0,
129     SignedChar,
130     UnsignedChar,
131     SignedShort,
132     UnsignedShort,
133     SignedInt,
134     UnsignedInt,
135     SignedLong,
136     UnsignedLong,
137     SignedLongLong,
138     UnsignedLongLong
139   };
140
141   enum RealType {
142     NoFloat = 255,
143     Float = 0,
144     Double,
145     LongDouble,
146     Float128
147   };
148
149   /// \brief The different kinds of __builtin_va_list types defined by
150   /// the target implementation.
151   enum BuiltinVaListKind {
152     /// typedef char* __builtin_va_list;
153     CharPtrBuiltinVaList = 0,
154
155     /// typedef void* __builtin_va_list;
156     VoidPtrBuiltinVaList,
157
158     /// __builtin_va_list as defined by the AArch64 ABI
159     /// http://infocenter.arm.com/help/topic/com.arm.doc.ihi0055a/IHI0055A_aapcs64.pdf
160     AArch64ABIBuiltinVaList,
161
162     /// __builtin_va_list as defined by the PNaCl ABI:
163     /// http://www.chromium.org/nativeclient/pnacl/bitcode-abi#TOC-Machine-Types
164     PNaClABIBuiltinVaList,
165
166     /// __builtin_va_list as defined by the Power ABI:
167     /// https://www.power.org
168     ///        /resources/downloads/Power-Arch-32-bit-ABI-supp-1.0-Embedded.pdf
169     PowerABIBuiltinVaList,
170
171     /// __builtin_va_list as defined by the x86-64 ABI:
172     /// http://refspecs.linuxbase.org/elf/x86_64-abi-0.21.pdf
173     X86_64ABIBuiltinVaList,
174
175     /// __builtin_va_list as defined by ARM AAPCS ABI
176     /// http://infocenter.arm.com
177     //        /help/topic/com.arm.doc.ihi0042d/IHI0042D_aapcs.pdf
178     AAPCSABIBuiltinVaList,
179
180     // typedef struct __va_list_tag
181     //   {
182     //     long __gpr;
183     //     long __fpr;
184     //     void *__overflow_arg_area;
185     //     void *__reg_save_area;
186     //   } va_list[1];
187     SystemZBuiltinVaList
188   };
189
190 protected:
191   IntType SizeType, IntMaxType, PtrDiffType, IntPtrType, WCharType,
192           WIntType, Char16Type, Char32Type, Int64Type, SigAtomicType,
193           ProcessIDType;
194
195   /// \brief Whether Objective-C's built-in boolean type should be signed char.
196   ///
197   /// Otherwise, when this flag is not set, the normal built-in boolean type is
198   /// used.
199   unsigned UseSignedCharForObjCBool : 1;
200
201   /// Control whether the alignment of bit-field types is respected when laying
202   /// out structures. If true, then the alignment of the bit-field type will be
203   /// used to (a) impact the alignment of the containing structure, and (b)
204   /// ensure that the individual bit-field will not straddle an alignment
205   /// boundary.
206   unsigned UseBitFieldTypeAlignment : 1;
207
208   /// \brief Whether zero length bitfields (e.g., int : 0;) force alignment of
209   /// the next bitfield.
210   ///
211   /// If the alignment of the zero length bitfield is greater than the member
212   /// that follows it, `bar', `bar' will be aligned as the type of the
213   /// zero-length bitfield.
214   unsigned UseZeroLengthBitfieldAlignment : 1;
215
216   /// \brief  Whether explicit bit field alignment attributes are honored.
217   unsigned UseExplicitBitFieldAlignment : 1;
218
219   /// If non-zero, specifies a fixed alignment value for bitfields that follow
220   /// zero length bitfield, regardless of the zero length bitfield type.
221   unsigned ZeroLengthBitfieldBoundary;
222
223   /// \brief Specify if mangling based on address space map should be used or
224   /// not for language specific address spaces
225   bool UseAddrSpaceMapMangling;
226
227 public:
228   IntType getSizeType() const { return SizeType; }
229   IntType getIntMaxType() const { return IntMaxType; }
230   IntType getUIntMaxType() const {
231     return getCorrespondingUnsignedType(IntMaxType);
232   }
233   IntType getPtrDiffType(unsigned AddrSpace) const {
234     return AddrSpace == 0 ? PtrDiffType : getPtrDiffTypeV(AddrSpace);
235   }
236   IntType getIntPtrType() const { return IntPtrType; }
237   IntType getUIntPtrType() const {
238     return getCorrespondingUnsignedType(IntPtrType);
239   }
240   IntType getWCharType() const { return WCharType; }
241   IntType getWIntType() const { return WIntType; }
242   IntType getChar16Type() const { return Char16Type; }
243   IntType getChar32Type() const { return Char32Type; }
244   IntType getInt64Type() const { return Int64Type; }
245   IntType getUInt64Type() const {
246     return getCorrespondingUnsignedType(Int64Type);
247   }
248   IntType getSigAtomicType() const { return SigAtomicType; }
249   IntType getProcessIDType() const { return ProcessIDType; }
250
251   static IntType getCorrespondingUnsignedType(IntType T) {
252     switch (T) {
253     case SignedChar:
254       return UnsignedChar;
255     case SignedShort:
256       return UnsignedShort;
257     case SignedInt:
258       return UnsignedInt;
259     case SignedLong:
260       return UnsignedLong;
261     case SignedLongLong:
262       return UnsignedLongLong;
263     default:
264       llvm_unreachable("Unexpected signed integer type");
265     }
266   }
267
268   /// \brief Return the width (in bits) of the specified integer type enum.
269   ///
270   /// For example, SignedInt -> getIntWidth().
271   unsigned getTypeWidth(IntType T) const;
272
273   /// \brief Return integer type with specified width.
274   virtual IntType getIntTypeByWidth(unsigned BitWidth, bool IsSigned) const;
275
276   /// \brief Return the smallest integer type with at least the specified width.
277   virtual IntType getLeastIntTypeByWidth(unsigned BitWidth,
278                                          bool IsSigned) const;
279
280   /// \brief Return floating point type with specified width.
281   RealType getRealTypeByWidth(unsigned BitWidth) const;
282
283   /// \brief Return the alignment (in bits) of the specified integer type enum.
284   ///
285   /// For example, SignedInt -> getIntAlign().
286   unsigned getTypeAlign(IntType T) const;
287
288   /// \brief Returns true if the type is signed; false otherwise.
289   static bool isTypeSigned(IntType T);
290
291   /// \brief Return the width of pointers on this target, for the
292   /// specified address space.
293   uint64_t getPointerWidth(unsigned AddrSpace) const {
294     return AddrSpace == 0 ? PointerWidth : getPointerWidthV(AddrSpace);
295   }
296   uint64_t getPointerAlign(unsigned AddrSpace) const {
297     return AddrSpace == 0 ? PointerAlign : getPointerAlignV(AddrSpace);
298   }
299
300   /// \brief Return the maximum width of pointers on this target.
301   virtual uint64_t getMaxPointerWidth() const {
302     return PointerWidth;
303   }
304
305   /// \brief Get integer value for null pointer.
306   /// \param AddrSpace address space of pointee in source language.
307   virtual uint64_t getNullPointerValue(unsigned AddrSpace) const {
308     return 0;
309   }
310
311   /// \brief Return the size of '_Bool' and C++ 'bool' for this target, in bits.
312   unsigned getBoolWidth() const { return BoolWidth; }
313
314   /// \brief Return the alignment of '_Bool' and C++ 'bool' for this target.
315   unsigned getBoolAlign() const { return BoolAlign; }
316
317   unsigned getCharWidth() const { return 8; } // FIXME
318   unsigned getCharAlign() const { return 8; } // FIXME
319
320   /// \brief Return the size of 'signed short' and 'unsigned short' for this
321   /// target, in bits.
322   unsigned getShortWidth() const { return 16; } // FIXME
323
324   /// \brief Return the alignment of 'signed short' and 'unsigned short' for
325   /// this target.
326   unsigned getShortAlign() const { return 16; } // FIXME
327
328   /// getIntWidth/Align - Return the size of 'signed int' and 'unsigned int' for
329   /// this target, in bits.
330   unsigned getIntWidth() const { return IntWidth; }
331   unsigned getIntAlign() const { return IntAlign; }
332
333   /// getLongWidth/Align - Return the size of 'signed long' and 'unsigned long'
334   /// for this target, in bits.
335   unsigned getLongWidth() const { return LongWidth; }
336   unsigned getLongAlign() const { return LongAlign; }
337
338   /// getLongLongWidth/Align - Return the size of 'signed long long' and
339   /// 'unsigned long long' for this target, in bits.
340   unsigned getLongLongWidth() const { return LongLongWidth; }
341   unsigned getLongLongAlign() const { return LongLongAlign; }
342
343   /// \brief Determine whether the __int128 type is supported on this target.
344   virtual bool hasInt128Type() const {
345     return getPointerWidth(0) >= 64;
346   } // FIXME
347
348   /// \brief Determine whether the __float128 type is supported on this target.
349   virtual bool hasFloat128Type() const { return HasFloat128; }
350
351   /// \brief Return the alignment that is suitable for storing any
352   /// object with a fundamental alignment requirement.
353   unsigned getSuitableAlign() const { return SuitableAlign; }
354
355   /// \brief Return the default alignment for __attribute__((aligned)) on
356   /// this target, to be used if no alignment value is specified.
357   unsigned getDefaultAlignForAttributeAligned() const {
358     return DefaultAlignForAttributeAligned;
359   }
360
361   /// getMinGlobalAlign - Return the minimum alignment of a global variable,
362   /// unless its alignment is explicitly reduced via attributes.
363   unsigned getMinGlobalAlign() const { return MinGlobalAlign; }
364
365   /// Return the largest alignment for which a suitably-sized allocation with
366   /// '::operator new(size_t)' is guaranteed to produce a correctly-aligned
367   /// pointer.
368   unsigned getNewAlign() const {
369     return NewAlign ? NewAlign : std::max(LongDoubleAlign, LongLongAlign);
370   }
371
372   /// getWCharWidth/Align - Return the size of 'wchar_t' for this target, in
373   /// bits.
374   unsigned getWCharWidth() const { return getTypeWidth(WCharType); }
375   unsigned getWCharAlign() const { return getTypeAlign(WCharType); }
376
377   /// getChar16Width/Align - Return the size of 'char16_t' for this target, in
378   /// bits.
379   unsigned getChar16Width() const { return getTypeWidth(Char16Type); }
380   unsigned getChar16Align() const { return getTypeAlign(Char16Type); }
381
382   /// getChar32Width/Align - Return the size of 'char32_t' for this target, in
383   /// bits.
384   unsigned getChar32Width() const { return getTypeWidth(Char32Type); }
385   unsigned getChar32Align() const { return getTypeAlign(Char32Type); }
386
387   /// getHalfWidth/Align/Format - Return the size/align/format of 'half'.
388   unsigned getHalfWidth() const { return HalfWidth; }
389   unsigned getHalfAlign() const { return HalfAlign; }
390   const llvm::fltSemantics &getHalfFormat() const { return *HalfFormat; }
391
392   /// getFloatWidth/Align/Format - Return the size/align/format of 'float'.
393   unsigned getFloatWidth() const { return FloatWidth; }
394   unsigned getFloatAlign() const { return FloatAlign; }
395   const llvm::fltSemantics &getFloatFormat() const { return *FloatFormat; }
396
397   /// getDoubleWidth/Align/Format - Return the size/align/format of 'double'.
398   unsigned getDoubleWidth() const { return DoubleWidth; }
399   unsigned getDoubleAlign() const { return DoubleAlign; }
400   const llvm::fltSemantics &getDoubleFormat() const { return *DoubleFormat; }
401
402   /// getLongDoubleWidth/Align/Format - Return the size/align/format of 'long
403   /// double'.
404   unsigned getLongDoubleWidth() const { return LongDoubleWidth; }
405   unsigned getLongDoubleAlign() const { return LongDoubleAlign; }
406   const llvm::fltSemantics &getLongDoubleFormat() const {
407     return *LongDoubleFormat;
408   }
409
410   /// getFloat128Width/Align/Format - Return the size/align/format of
411   /// '__float128'.
412   unsigned getFloat128Width() const { return 128; }
413   unsigned getFloat128Align() const { return Float128Align; }
414   const llvm::fltSemantics &getFloat128Format() const {
415     return *Float128Format;
416   }
417
418   /// \brief Return true if the 'long double' type should be mangled like
419   /// __float128.
420   virtual bool useFloat128ManglingForLongDouble() const { return false; }
421
422   /// \brief Return the value for the C99 FLT_EVAL_METHOD macro.
423   virtual unsigned getFloatEvalMethod() const { return 0; }
424
425   // getLargeArrayMinWidth/Align - Return the minimum array size that is
426   // 'large' and its alignment.
427   unsigned getLargeArrayMinWidth() const { return LargeArrayMinWidth; }
428   unsigned getLargeArrayAlign() const { return LargeArrayAlign; }
429
430   /// \brief Return the maximum width lock-free atomic operation which will
431   /// ever be supported for the given target
432   unsigned getMaxAtomicPromoteWidth() const { return MaxAtomicPromoteWidth; }
433   /// \brief Return the maximum width lock-free atomic operation which can be
434   /// inlined given the supported features of the given target.
435   unsigned getMaxAtomicInlineWidth() const { return MaxAtomicInlineWidth; }
436   /// \brief Returns true if the given target supports lock-free atomic
437   /// operations at the specified width and alignment.
438   virtual bool hasBuiltinAtomic(uint64_t AtomicSizeInBits,
439                                 uint64_t AlignmentInBits) const {
440     return AtomicSizeInBits <= AlignmentInBits &&
441            AtomicSizeInBits <= getMaxAtomicInlineWidth() &&
442            (AtomicSizeInBits <= getCharWidth() ||
443             llvm::isPowerOf2_64(AtomicSizeInBits / getCharWidth()));
444   }
445
446   /// \brief Return the maximum vector alignment supported for the given target.
447   unsigned getMaxVectorAlign() const { return MaxVectorAlign; }
448   /// \brief Return default simd alignment for the given target. Generally, this
449   /// value is type-specific, but this alignment can be used for most of the
450   /// types for the given target.
451   unsigned getSimdDefaultAlign() const { return SimdDefaultAlign; }
452
453   /// Return the alignment (in bits) of the thrown exception object. This is
454   /// only meaningful for targets that allocate C++ exceptions in a system
455   /// runtime, such as those using the Itanium C++ ABI.
456   virtual unsigned getExnObjectAlignment() const {
457     // Itanium says that an _Unwind_Exception has to be "double-word"
458     // aligned (and thus the end of it is also so-aligned), meaning 16
459     // bytes.  Of course, that was written for the actual Itanium,
460     // which is a 64-bit platform.  Classically, the ABI doesn't really
461     // specify the alignment on other platforms, but in practice
462     // libUnwind declares the struct with __attribute__((aligned)), so
463     // we assume that alignment here.  (It's generally 16 bytes, but
464     // some targets overwrite it.)
465     return getDefaultAlignForAttributeAligned();
466   }
467
468   /// \brief Return the size of intmax_t and uintmax_t for this target, in bits.
469   unsigned getIntMaxTWidth() const {
470     return getTypeWidth(IntMaxType);
471   }
472
473   // Return the size of unwind_word for this target.
474   virtual unsigned getUnwindWordWidth() const { return getPointerWidth(0); }
475
476   /// \brief Return the "preferred" register width on this target.
477   virtual unsigned getRegisterWidth() const {
478     // Currently we assume the register width on the target matches the pointer
479     // width, we can introduce a new variable for this if/when some target wants
480     // it.
481     return PointerWidth;
482   }
483
484   /// \brief Returns the name of the mcount instrumentation function.
485   const char *getMCountName() const {
486     return MCountName;
487   }
488
489   /// \brief Check if the Objective-C built-in boolean type should be signed
490   /// char.
491   ///
492   /// Otherwise, if this returns false, the normal built-in boolean type
493   /// should also be used for Objective-C.
494   bool useSignedCharForObjCBool() const {
495     return UseSignedCharForObjCBool;
496   }
497   void noSignedCharForObjCBool() {
498     UseSignedCharForObjCBool = false;
499   }
500
501   /// \brief Check whether the alignment of bit-field types is respected
502   /// when laying out structures.
503   bool useBitFieldTypeAlignment() const {
504     return UseBitFieldTypeAlignment;
505   }
506
507   /// \brief Check whether zero length bitfields should force alignment of
508   /// the next member.
509   bool useZeroLengthBitfieldAlignment() const {
510     return UseZeroLengthBitfieldAlignment;
511   }
512
513   /// \brief Get the fixed alignment value in bits for a member that follows
514   /// a zero length bitfield.
515   unsigned getZeroLengthBitfieldBoundary() const {
516     return ZeroLengthBitfieldBoundary;
517   }
518
519   /// \brief Check whether explicit bitfield alignment attributes should be
520   //  honored, as in "__attribute__((aligned(2))) int b : 1;".
521   bool useExplicitBitFieldAlignment() const {
522     return UseExplicitBitFieldAlignment;
523   }
524
525   /// \brief Check whether this target support '\#pragma options align=mac68k'.
526   bool hasAlignMac68kSupport() const {
527     return HasAlignMac68kSupport;
528   }
529
530   /// \brief Return the user string for the specified integer type enum.
531   ///
532   /// For example, SignedShort -> "short".
533   static const char *getTypeName(IntType T);
534
535   /// \brief Return the constant suffix for the specified integer type enum.
536   ///
537   /// For example, SignedLong -> "L".
538   const char *getTypeConstantSuffix(IntType T) const;
539
540   /// \brief Return the printf format modifier for the specified
541   /// integer type enum.
542   ///
543   /// For example, SignedLong -> "l".
544   static const char *getTypeFormatModifier(IntType T);
545
546   /// \brief Check whether the given real type should use the "fpret" flavor of
547   /// Objective-C message passing on this target.
548   bool useObjCFPRetForRealType(RealType T) const {
549     return RealTypeUsesObjCFPRet & (1 << T);
550   }
551
552   /// \brief Check whether _Complex long double should use the "fp2ret" flavor
553   /// of Objective-C message passing on this target.
554   bool useObjCFP2RetForComplexLongDouble() const {
555     return ComplexLongDoubleUsesFP2Ret;
556   }
557
558   /// \brief Specify if mangling based on address space map should be used or
559   /// not for language specific address spaces
560   bool useAddressSpaceMapMangling() const {
561     return UseAddrSpaceMapMangling;
562   }
563
564   ///===---- Other target property query methods --------------------------===//
565
566   /// \brief Appends the target-specific \#define values for this
567   /// target set to the specified buffer.
568   virtual void getTargetDefines(const LangOptions &Opts,
569                                 MacroBuilder &Builder) const = 0;
570
571
572   /// Return information about target-specific builtins for
573   /// the current primary target, and info about which builtins are non-portable
574   /// across the current set of primary and secondary targets.
575   virtual ArrayRef<Builtin::Info> getTargetBuiltins() const = 0;
576
577   /// The __builtin_clz* and __builtin_ctz* built-in
578   /// functions are specified to have undefined results for zero inputs, but
579   /// on targets that support these operations in a way that provides
580   /// well-defined results for zero without loss of performance, it is a good
581   /// idea to avoid optimizing based on that undef behavior.
582   virtual bool isCLZForZeroUndef() const { return true; }
583
584   /// \brief Returns the kind of __builtin_va_list type that should be used
585   /// with this target.
586   virtual BuiltinVaListKind getBuiltinVaListKind() const = 0;
587
588   /// Returns whether or not type \c __builtin_ms_va_list type is
589   /// available on this target.
590   bool hasBuiltinMSVaList() const { return HasBuiltinMSVaList; }
591
592   /// Returns true for RenderScript.
593   bool isRenderScriptTarget() const { return IsRenderScriptTarget; }
594
595   /// \brief Returns whether the passed in string is a valid clobber in an
596   /// inline asm statement.
597   ///
598   /// This is used by Sema.
599   bool isValidClobber(StringRef Name) const;
600
601   /// \brief Returns whether the passed in string is a valid register name
602   /// according to GCC.
603   ///
604   /// This is used by Sema for inline asm statements.
605   bool isValidGCCRegisterName(StringRef Name) const;
606
607   /// \brief Returns the "normalized" GCC register name.
608   ///
609   /// ReturnCannonical true will return the register name without any additions
610   /// such as "{}" or "%" in it's canonical form, for example:
611   /// ReturnCanonical = true and Name = "rax", will return "ax".
612   StringRef getNormalizedGCCRegisterName(StringRef Name,
613                                          bool ReturnCanonical = false) const;
614  
615   virtual StringRef getConstraintRegister(const StringRef &Constraint,
616                                           const StringRef &Expression) const {
617     return "";
618   }
619
620   struct ConstraintInfo {
621     enum {
622       CI_None = 0x00,
623       CI_AllowsMemory = 0x01,
624       CI_AllowsRegister = 0x02,
625       CI_ReadWrite = 0x04,         // "+r" output constraint (read and write).
626       CI_HasMatchingInput = 0x08,  // This output operand has a matching input.
627       CI_ImmediateConstant = 0x10, // This operand must be an immediate constant
628       CI_EarlyClobber = 0x20,      // "&" output constraint (early clobber).
629     };
630     unsigned Flags;
631     int TiedOperand;
632     struct {
633       int Min;
634       int Max;
635     } ImmRange;
636     llvm::SmallSet<int, 4> ImmSet;
637
638     std::string ConstraintStr;  // constraint: "=rm"
639     std::string Name;           // Operand name: [foo] with no []'s.
640   public:
641     ConstraintInfo(StringRef ConstraintStr, StringRef Name)
642         : Flags(0), TiedOperand(-1), ConstraintStr(ConstraintStr.str()),
643           Name(Name.str()) {
644       ImmRange.Min = ImmRange.Max = 0;
645     }
646
647     const std::string &getConstraintStr() const { return ConstraintStr; }
648     const std::string &getName() const { return Name; }
649     bool isReadWrite() const { return (Flags & CI_ReadWrite) != 0; }
650     bool earlyClobber() { return (Flags & CI_EarlyClobber) != 0; }
651     bool allowsRegister() const { return (Flags & CI_AllowsRegister) != 0; }
652     bool allowsMemory() const { return (Flags & CI_AllowsMemory) != 0; }
653
654     /// \brief Return true if this output operand has a matching
655     /// (tied) input operand.
656     bool hasMatchingInput() const { return (Flags & CI_HasMatchingInput) != 0; }
657
658     /// \brief Return true if this input operand is a matching
659     /// constraint that ties it to an output operand.
660     ///
661     /// If this returns true then getTiedOperand will indicate which output
662     /// operand this is tied to.
663     bool hasTiedOperand() const { return TiedOperand != -1; }
664     unsigned getTiedOperand() const {
665       assert(hasTiedOperand() && "Has no tied operand!");
666       return (unsigned)TiedOperand;
667     }
668
669     bool requiresImmediateConstant() const {
670       return (Flags & CI_ImmediateConstant) != 0;
671     }
672     bool isValidAsmImmediate(const llvm::APInt &Value) const {
673       return (Value.sge(ImmRange.Min) && Value.sle(ImmRange.Max)) ||
674              ImmSet.count(Value.getZExtValue()) != 0;
675     }
676
677     void setIsReadWrite() { Flags |= CI_ReadWrite; }
678     void setEarlyClobber() { Flags |= CI_EarlyClobber; }
679     void setAllowsMemory() { Flags |= CI_AllowsMemory; }
680     void setAllowsRegister() { Flags |= CI_AllowsRegister; }
681     void setHasMatchingInput() { Flags |= CI_HasMatchingInput; }
682     void setRequiresImmediate(int Min, int Max) {
683       Flags |= CI_ImmediateConstant;
684       ImmRange.Min = Min;
685       ImmRange.Max = Max;
686     }
687     void setRequiresImmediate(llvm::ArrayRef<int> Exacts) {
688       Flags |= CI_ImmediateConstant;
689       for (int Exact : Exacts)
690         ImmSet.insert(Exact);
691     }
692     void setRequiresImmediate(int Exact) {
693       Flags |= CI_ImmediateConstant;
694       ImmSet.insert(Exact);
695     }
696     void setRequiresImmediate() {
697       Flags |= CI_ImmediateConstant;
698       ImmRange.Min = INT_MIN;
699       ImmRange.Max = INT_MAX;
700     }
701
702     /// \brief Indicate that this is an input operand that is tied to
703     /// the specified output operand.
704     ///
705     /// Copy over the various constraint information from the output.
706     void setTiedOperand(unsigned N, ConstraintInfo &Output) {
707       Output.setHasMatchingInput();
708       Flags = Output.Flags;
709       TiedOperand = N;
710       // Don't copy Name or constraint string.
711     }
712   };
713
714   /// \brief Validate register name used for global register variables.
715   ///
716   /// This function returns true if the register passed in RegName can be used
717   /// for global register variables on this target. In addition, it returns
718   /// true in HasSizeMismatch if the size of the register doesn't match the
719   /// variable size passed in RegSize.
720   virtual bool validateGlobalRegisterVariable(StringRef RegName,
721                                               unsigned RegSize,
722                                               bool &HasSizeMismatch) const {
723     HasSizeMismatch = false;
724     return true;
725   }
726
727   // validateOutputConstraint, validateInputConstraint - Checks that
728   // a constraint is valid and provides information about it.
729   // FIXME: These should return a real error instead of just true/false.
730   bool validateOutputConstraint(ConstraintInfo &Info) const;
731   bool validateInputConstraint(MutableArrayRef<ConstraintInfo> OutputConstraints,
732                                ConstraintInfo &info) const;
733
734   virtual bool validateOutputSize(StringRef /*Constraint*/,
735                                   unsigned /*Size*/) const {
736     return true;
737   }
738
739   virtual bool validateInputSize(StringRef /*Constraint*/,
740                                  unsigned /*Size*/) const {
741     return true;
742   }
743   virtual bool
744   validateConstraintModifier(StringRef /*Constraint*/,
745                              char /*Modifier*/,
746                              unsigned /*Size*/,
747                              std::string &/*SuggestedModifier*/) const {
748     return true;
749   }
750   virtual bool
751   validateAsmConstraint(const char *&Name,
752                         TargetInfo::ConstraintInfo &info) const = 0;
753
754   bool resolveSymbolicName(const char *&Name,
755                            ArrayRef<ConstraintInfo> OutputConstraints,
756                            unsigned &Index) const;
757
758   // Constraint parm will be left pointing at the last character of
759   // the constraint.  In practice, it won't be changed unless the
760   // constraint is longer than one character.
761   virtual std::string convertConstraint(const char *&Constraint) const {
762     // 'p' defaults to 'r', but can be overridden by targets.
763     if (*Constraint == 'p')
764       return std::string("r");
765     return std::string(1, *Constraint);
766   }
767
768   /// \brief Returns a string of target-specific clobbers, in LLVM format.
769   virtual const char *getClobbers() const = 0;
770
771   /// \brief Returns true if NaN encoding is IEEE 754-2008.
772   /// Only MIPS allows a different encoding.
773   virtual bool isNan2008() const {
774     return true;
775   }
776
777   /// \brief Returns the target triple of the primary target.
778   const llvm::Triple &getTriple() const {
779     return Triple;
780   }
781
782   const llvm::DataLayout &getDataLayout() const {
783     assert(DataLayout && "Uninitialized DataLayout!");
784     return *DataLayout;
785   }
786
787   struct GCCRegAlias {
788     const char * const Aliases[5];
789     const char * const Register;
790   };
791
792   struct AddlRegName {
793     const char * const Names[5];
794     const unsigned RegNum;
795   };
796
797   /// \brief Does this target support "protected" visibility?
798   ///
799   /// Any target which dynamic libraries will naturally support
800   /// something like "default" (meaning that the symbol is visible
801   /// outside this shared object) and "hidden" (meaning that it isn't)
802   /// visibilities, but "protected" is really an ELF-specific concept
803   /// with weird semantics designed around the convenience of dynamic
804   /// linker implementations.  Which is not to suggest that there's
805   /// consistent target-independent semantics for "default" visibility
806   /// either; the entire thing is pretty badly mangled.
807   virtual bool hasProtectedVisibility() const { return true; }
808
809   /// \brief An optional hook that targets can implement to perform semantic
810   /// checking on attribute((section("foo"))) specifiers.
811   ///
812   /// In this case, "foo" is passed in to be checked.  If the section
813   /// specifier is invalid, the backend should return a non-empty string
814   /// that indicates the problem.
815   ///
816   /// This hook is a simple quality of implementation feature to catch errors
817   /// and give good diagnostics in cases when the assembler or code generator
818   /// would otherwise reject the section specifier.
819   ///
820   virtual std::string isValidSectionSpecifier(StringRef SR) const {
821     return "";
822   }
823
824   /// \brief Set forced language options.
825   ///
826   /// Apply changes to the target information with respect to certain
827   /// language options which change the target configuration and adjust
828   /// the language based on the target options where applicable.
829   virtual void adjust(LangOptions &Opts);
830
831   /// \brief Adjust target options based on codegen options.
832   virtual void adjustTargetOptions(const CodeGenOptions &CGOpts,
833                                    TargetOptions &TargetOpts) const {}
834
835   /// \brief Initialize the map with the default set of target features for the
836   /// CPU this should include all legal feature strings on the target.
837   ///
838   /// \return False on error (invalid features).
839   virtual bool initFeatureMap(llvm::StringMap<bool> &Features,
840                               DiagnosticsEngine &Diags, StringRef CPU,
841                               const std::vector<std::string> &FeatureVec) const;
842
843   /// \brief Get the ABI currently in use.
844   virtual StringRef getABI() const { return StringRef(); }
845
846   /// \brief Get the C++ ABI currently in use.
847   TargetCXXABI getCXXABI() const {
848     return TheCXXABI;
849   }
850
851   /// \brief Target the specified CPU.
852   ///
853   /// \return  False on error (invalid CPU name).
854   virtual bool setCPU(const std::string &Name) {
855     return false;
856   }
857
858   /// \brief Use the specified ABI.
859   ///
860   /// \return False on error (invalid ABI name).
861   virtual bool setABI(const std::string &Name) {
862     return false;
863   }
864
865   /// \brief Use the specified unit for FP math.
866   ///
867   /// \return False on error (invalid unit name).
868   virtual bool setFPMath(StringRef Name) {
869     return false;
870   }
871
872   /// \brief Enable or disable a specific target feature;
873   /// the feature name must be valid.
874   virtual void setFeatureEnabled(llvm::StringMap<bool> &Features,
875                                  StringRef Name,
876                                  bool Enabled) const {
877     Features[Name] = Enabled;
878   }
879
880   /// \brief Perform initialization based on the user configured
881   /// set of features (e.g., +sse4).
882   ///
883   /// The list is guaranteed to have at most one entry per feature.
884   ///
885   /// The target may modify the features list, to change which options are
886   /// passed onwards to the backend.
887   /// FIXME: This part should be fixed so that we can change handleTargetFeatures
888   /// to merely a TargetInfo initialization routine.
889   ///
890   /// \return  False on error.
891   virtual bool handleTargetFeatures(std::vector<std::string> &Features,
892                                     DiagnosticsEngine &Diags) {
893     return true;
894   }
895
896   /// \brief Determine whether the given target has the given feature.
897   virtual bool hasFeature(StringRef Feature) const {
898     return false;
899   }
900
901   // \brief Validate the contents of the __builtin_cpu_supports(const char*)
902   // argument.
903   virtual bool validateCpuSupports(StringRef Name) const { return false; }
904
905   // \brief Returns maximal number of args passed in registers.
906   unsigned getRegParmMax() const {
907     assert(RegParmMax < 7 && "RegParmMax value is larger than AST can handle");
908     return RegParmMax;
909   }
910
911   /// \brief Whether the target supports thread-local storage.
912   bool isTLSSupported() const {
913     return TLSSupported;
914   }
915
916   /// \brief Return the maximum alignment (in bits) of a TLS variable
917   ///
918   /// Gets the maximum alignment (in bits) of a TLS variable on this target.
919   /// Returns zero if there is no such constraint.
920   unsigned short getMaxTLSAlign() const {
921     return MaxTLSAlign;
922   }
923
924   /// \brief Whether the target supports SEH __try.
925   bool isSEHTrySupported() const {
926     return getTriple().isOSWindows() &&
927            (getTriple().getArch() == llvm::Triple::x86 ||
928             getTriple().getArch() == llvm::Triple::x86_64);
929   }
930
931   /// \brief Return true if {|} are normal characters in the asm string.
932   ///
933   /// If this returns false (the default), then {abc|xyz} is syntax
934   /// that says that when compiling for asm variant #0, "abc" should be
935   /// generated, but when compiling for asm variant #1, "xyz" should be
936   /// generated.
937   bool hasNoAsmVariants() const {
938     return NoAsmVariants;
939   }
940
941   /// \brief Return the register number that __builtin_eh_return_regno would
942   /// return with the specified argument.
943   /// This corresponds with TargetLowering's getExceptionPointerRegister
944   /// and getExceptionSelectorRegister in the backend.
945   virtual int getEHDataRegisterNumber(unsigned RegNo) const {
946     return -1;
947   }
948
949   /// \brief Return the section to use for C++ static initialization functions.
950   virtual const char *getStaticInitSectionSpecifier() const {
951     return nullptr;
952   }
953
954   const LangAS::Map &getAddressSpaceMap() const {
955     return *AddrSpaceMap;
956   }
957
958   /// \brief Return an AST address space which can be used opportunistically
959   /// for constant global memory. It must be possible to convert pointers into
960   /// this address space to LangAS::Default. If no such address space exists,
961   /// this may return None, and such optimizations will be disabled.
962   virtual llvm::Optional<unsigned> getConstantAddressSpace() const {
963     return LangAS::Default;
964   }
965
966   /// \brief Retrieve the name of the platform as it is used in the
967   /// availability attribute.
968   StringRef getPlatformName() const { return PlatformName; }
969
970   /// \brief Retrieve the minimum desired version of the platform, to
971   /// which the program should be compiled.
972   VersionTuple getPlatformMinVersion() const { return PlatformMinVersion; }
973
974   bool isBigEndian() const { return BigEndian; }
975   bool isLittleEndian() const { return !BigEndian; }
976
977   enum CallingConvMethodType {
978     CCMT_Unknown,
979     CCMT_Member,
980     CCMT_NonMember
981   };
982
983   /// \brief Gets the default calling convention for the given target and
984   /// declaration context.
985   virtual CallingConv getDefaultCallingConv(CallingConvMethodType MT) const {
986     // Not all targets will specify an explicit calling convention that we can
987     // express.  This will always do the right thing, even though it's not
988     // an explicit calling convention.
989     return CC_C;
990   }
991
992   enum CallingConvCheckResult {
993     CCCR_OK,
994     CCCR_Warning,
995     CCCR_Ignore,
996   };
997
998   /// \brief Determines whether a given calling convention is valid for the
999   /// target. A calling convention can either be accepted, produce a warning
1000   /// and be substituted with the default calling convention, or (someday)
1001   /// produce an error (such as using thiscall on a non-instance function).
1002   virtual CallingConvCheckResult checkCallingConvention(CallingConv CC) const {
1003     switch (CC) {
1004       default:
1005         return CCCR_Warning;
1006       case CC_C:
1007         return CCCR_OK;
1008     }
1009   }
1010
1011   /// Controls if __builtin_longjmp / __builtin_setjmp can be lowered to
1012   /// llvm.eh.sjlj.longjmp / llvm.eh.sjlj.setjmp.
1013   virtual bool hasSjLjLowering() const {
1014     return false;
1015   }
1016
1017   /// \brief Whether target allows to overalign ABI-specified preferred alignment
1018   virtual bool allowsLargerPreferedTypeAlignment() const { return true; }
1019
1020   /// \brief Set supported OpenCL extensions and optional core features.
1021   virtual void setSupportedOpenCLOpts() {}
1022
1023   /// \brief Set supported OpenCL extensions as written on command line
1024   virtual void setOpenCLExtensionOpts() {
1025     for (const auto &Ext : getTargetOpts().OpenCLExtensionsAsWritten) {
1026       getTargetOpts().SupportedOpenCLOptions.support(Ext);
1027     }
1028   }
1029
1030   /// \brief Get supported OpenCL extensions and optional core features.
1031   OpenCLOptions &getSupportedOpenCLOpts() {
1032     return getTargetOpts().SupportedOpenCLOptions;
1033   }
1034
1035   /// \brief Get const supported OpenCL extensions and optional core features.
1036   const OpenCLOptions &getSupportedOpenCLOpts() const {
1037       return getTargetOpts().SupportedOpenCLOptions;
1038   }
1039
1040   /// \brief Get OpenCL image type address space.
1041   virtual LangAS::ID getOpenCLImageAddrSpace() const {
1042     return LangAS::opencl_global;
1043   }
1044
1045   /// \returns Target specific vtbl ptr address space.
1046   virtual unsigned getVtblPtrAddressSpace() const {
1047     return 0;
1048   }
1049
1050   /// \returns If a target requires an address within a target specific address
1051   /// space \p AddressSpace to be converted in order to be used, then return the
1052   /// corresponding target specific DWARF address space.
1053   ///
1054   /// \returns Otherwise return None and no conversion will be emitted in the
1055   /// DWARF.
1056   virtual Optional<unsigned> getDWARFAddressSpace(unsigned AddressSpace) const {
1057     return None;
1058   }
1059
1060   /// \brief Check the target is valid after it is fully initialized.
1061   virtual bool validateTarget(DiagnosticsEngine &Diags) const {
1062     return true;
1063   }
1064
1065 protected:
1066   virtual uint64_t getPointerWidthV(unsigned AddrSpace) const {
1067     return PointerWidth;
1068   }
1069   virtual uint64_t getPointerAlignV(unsigned AddrSpace) const {
1070     return PointerAlign;
1071   }
1072   virtual enum IntType getPtrDiffTypeV(unsigned AddrSpace) const {
1073     return PtrDiffType;
1074   }
1075   virtual ArrayRef<const char *> getGCCRegNames() const = 0;
1076   virtual ArrayRef<GCCRegAlias> getGCCRegAliases() const = 0;
1077   virtual ArrayRef<AddlRegName> getGCCAddlRegNames() const {
1078     return None;
1079   }
1080 };
1081
1082 }  // end namespace clang
1083
1084 #endif