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