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