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