Home | History | Annotate | Download | only in Target
      1 //===-- llvm/Target/TargetData.h - Data size & alignment info ---*- 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 // This file defines target properties related to datatype size/offset/alignment
     11 // information.  It uses lazy annotations to cache information about how
     12 // structure types are laid out and used.
     13 //
     14 // This structure should be created once, filled in if the defaults are not
     15 // correct and then passed around by const&.  None of the members functions
     16 // require modification to the object.
     17 //
     18 //===----------------------------------------------------------------------===//
     19 
     20 #ifndef LLVM_TARGET_TARGETDATA_H
     21 #define LLVM_TARGET_TARGETDATA_H
     22 
     23 #include "llvm/Pass.h"
     24 #include "llvm/ADT/SmallVector.h"
     25 #include "llvm/Support/DataTypes.h"
     26 
     27 namespace llvm {
     28 
     29 class Value;
     30 class Type;
     31 class IntegerType;
     32 class StructType;
     33 class StructLayout;
     34 class GlobalVariable;
     35 class LLVMContext;
     36 template<typename T>
     37 class ArrayRef;
     38 
     39 /// Enum used to categorize the alignment types stored by TargetAlignElem
     40 enum AlignTypeEnum {
     41   INTEGER_ALIGN = 'i',               ///< Integer type alignment
     42   VECTOR_ALIGN = 'v',                ///< Vector type alignment
     43   FLOAT_ALIGN = 'f',                 ///< Floating point type alignment
     44   AGGREGATE_ALIGN = 'a',             ///< Aggregate alignment
     45   STACK_ALIGN = 's'                  ///< Stack objects alignment
     46 };
     47 /// Target alignment element.
     48 ///
     49 /// Stores the alignment data associated with a given alignment type (pointer,
     50 /// integer, vector, float) and type bit width.
     51 ///
     52 /// @note The unusual order of elements in the structure attempts to reduce
     53 /// padding and make the structure slightly more cache friendly.
     54 struct TargetAlignElem {
     55   AlignTypeEnum       AlignType : 8;  //< Alignment type (AlignTypeEnum)
     56   unsigned            ABIAlign;       //< ABI alignment for this type/bitw
     57   unsigned            PrefAlign;      //< Pref. alignment for this type/bitw
     58   uint32_t            TypeBitWidth;   //< Type bit width
     59 
     60   /// Initializer
     61   static TargetAlignElem get(AlignTypeEnum align_type, unsigned abi_align,
     62                              unsigned pref_align, uint32_t bit_width);
     63   /// Equality predicate
     64   bool operator==(const TargetAlignElem &rhs) const;
     65 };
     66 
     67 class TargetData : public ImmutablePass {
     68 private:
     69   bool          LittleEndian;          ///< Defaults to false
     70   unsigned      PointerMemSize;        ///< Pointer size in bytes
     71   unsigned      PointerABIAlign;       ///< Pointer ABI alignment
     72   unsigned      PointerPrefAlign;      ///< Pointer preferred alignment
     73 
     74   SmallVector<unsigned char, 8> LegalIntWidths; ///< Legal Integers.
     75 
     76   /// Alignments- Where the primitive type alignment data is stored.
     77   ///
     78   /// @sa init().
     79   /// @note Could support multiple size pointer alignments, e.g., 32-bit
     80   /// pointers vs. 64-bit pointers by extending TargetAlignment, but for now,
     81   /// we don't.
     82   SmallVector<TargetAlignElem, 16> Alignments;
     83 
     84   /// InvalidAlignmentElem - This member is a signal that a requested alignment
     85   /// type and bit width were not found in the SmallVector.
     86   static const TargetAlignElem InvalidAlignmentElem;
     87 
     88   // The StructType -> StructLayout map.
     89   mutable void *LayoutMap;
     90 
     91   //! Set/initialize target alignments
     92   void setAlignment(AlignTypeEnum align_type, unsigned abi_align,
     93                     unsigned pref_align, uint32_t bit_width);
     94   unsigned getAlignmentInfo(AlignTypeEnum align_type, uint32_t bit_width,
     95                             bool ABIAlign, Type *Ty) const;
     96   //! Internal helper method that returns requested alignment for type.
     97   unsigned getAlignment(Type *Ty, bool abi_or_pref) const;
     98 
     99   /// Valid alignment predicate.
    100   ///
    101   /// Predicate that tests a TargetAlignElem reference returned by get() against
    102   /// InvalidAlignmentElem.
    103   bool validAlignment(const TargetAlignElem &align) const {
    104     return &align != &InvalidAlignmentElem;
    105   }
    106 
    107 public:
    108   /// Default ctor.
    109   ///
    110   /// @note This has to exist, because this is a pass, but it should never be
    111   /// used.
    112   TargetData();
    113 
    114   /// Constructs a TargetData from a specification string. See init().
    115   explicit TargetData(StringRef TargetDescription)
    116     : ImmutablePass(ID) {
    117     init(TargetDescription);
    118   }
    119 
    120   /// Initialize target data from properties stored in the module.
    121   explicit TargetData(const Module *M);
    122 
    123   TargetData(const TargetData &TD) :
    124     ImmutablePass(ID),
    125     LittleEndian(TD.isLittleEndian()),
    126     PointerMemSize(TD.PointerMemSize),
    127     PointerABIAlign(TD.PointerABIAlign),
    128     PointerPrefAlign(TD.PointerPrefAlign),
    129     LegalIntWidths(TD.LegalIntWidths),
    130     Alignments(TD.Alignments),
    131     LayoutMap(0)
    132   { }
    133 
    134   ~TargetData();  // Not virtual, do not subclass this class
    135 
    136   //! Parse a target data layout string and initialize TargetData alignments.
    137   void init(StringRef TargetDescription);
    138 
    139   /// Target endianness...
    140   bool isLittleEndian() const { return LittleEndian; }
    141   bool isBigEndian() const { return !LittleEndian; }
    142 
    143   /// getStringRepresentation - Return the string representation of the
    144   /// TargetData.  This representation is in the same format accepted by the
    145   /// string constructor above.
    146   std::string getStringRepresentation() const;
    147 
    148   /// isLegalInteger - This function returns true if the specified type is
    149   /// known to be a native integer type supported by the CPU.  For example,
    150   /// i64 is not native on most 32-bit CPUs and i37 is not native on any known
    151   /// one.  This returns false if the integer width is not legal.
    152   ///
    153   /// The width is specified in bits.
    154   ///
    155   bool isLegalInteger(unsigned Width) const {
    156     for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
    157       if (LegalIntWidths[i] == Width)
    158         return true;
    159     return false;
    160   }
    161 
    162   bool isIllegalInteger(unsigned Width) const {
    163     return !isLegalInteger(Width);
    164   }
    165 
    166   /// fitsInLegalInteger - This function returns true if the specified type fits
    167   /// in a native integer type supported by the CPU.  For example, if the CPU
    168   /// only supports i32 as a native integer type, then i27 fits in a legal
    169   // integer type but i45 does not.
    170   bool fitsInLegalInteger(unsigned Width) const {
    171     for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
    172       if (Width <= LegalIntWidths[i])
    173         return true;
    174     return false;
    175   }
    176 
    177   /// Target pointer alignment
    178   unsigned getPointerABIAlignment() const { return PointerABIAlign; }
    179   /// Return target's alignment for stack-based pointers
    180   unsigned getPointerPrefAlignment() const { return PointerPrefAlign; }
    181   /// Target pointer size
    182   unsigned getPointerSize()         const { return PointerMemSize; }
    183   /// Target pointer size, in bits
    184   unsigned getPointerSizeInBits()   const { return 8*PointerMemSize; }
    185 
    186   /// Size examples:
    187   ///
    188   /// Type        SizeInBits  StoreSizeInBits  AllocSizeInBits[*]
    189   /// ----        ----------  ---------------  ---------------
    190   ///  i1            1           8                8
    191   ///  i8            8           8                8
    192   ///  i19          19          24               32
    193   ///  i32          32          32               32
    194   ///  i100        100         104              128
    195   ///  i128        128         128              128
    196   ///  Float        32          32               32
    197   ///  Double       64          64               64
    198   ///  X86_FP80     80          80               96
    199   ///
    200   /// [*] The alloc size depends on the alignment, and thus on the target.
    201   ///     These values are for x86-32 linux.
    202 
    203   /// getTypeSizeInBits - Return the number of bits necessary to hold the
    204   /// specified type.  For example, returns 36 for i36 and 80 for x86_fp80.
    205   uint64_t getTypeSizeInBits(Type* Ty) const;
    206 
    207   /// getTypeStoreSize - Return the maximum number of bytes that may be
    208   /// overwritten by storing the specified type.  For example, returns 5
    209   /// for i36 and 10 for x86_fp80.
    210   uint64_t getTypeStoreSize(Type *Ty) const {
    211     return (getTypeSizeInBits(Ty)+7)/8;
    212   }
    213 
    214   /// getTypeStoreSizeInBits - Return the maximum number of bits that may be
    215   /// overwritten by storing the specified type; always a multiple of 8.  For
    216   /// example, returns 40 for i36 and 80 for x86_fp80.
    217   uint64_t getTypeStoreSizeInBits(Type *Ty) const {
    218     return 8*getTypeStoreSize(Ty);
    219   }
    220 
    221   /// getTypeAllocSize - Return the offset in bytes between successive objects
    222   /// of the specified type, including alignment padding.  This is the amount
    223   /// that alloca reserves for this type.  For example, returns 12 or 16 for
    224   /// x86_fp80, depending on alignment.
    225   uint64_t getTypeAllocSize(Type* Ty) const {
    226     // Round up to the next alignment boundary.
    227     return RoundUpAlignment(getTypeStoreSize(Ty), getABITypeAlignment(Ty));
    228   }
    229 
    230   /// getTypeAllocSizeInBits - Return the offset in bits between successive
    231   /// objects of the specified type, including alignment padding; always a
    232   /// multiple of 8.  This is the amount that alloca reserves for this type.
    233   /// For example, returns 96 or 128 for x86_fp80, depending on alignment.
    234   uint64_t getTypeAllocSizeInBits(Type* Ty) const {
    235     return 8*getTypeAllocSize(Ty);
    236   }
    237 
    238   /// getABITypeAlignment - Return the minimum ABI-required alignment for the
    239   /// specified type.
    240   unsigned getABITypeAlignment(Type *Ty) const;
    241 
    242   /// getABIIntegerTypeAlignment - Return the minimum ABI-required alignment for
    243   /// an integer type of the specified bitwidth.
    244   unsigned getABIIntegerTypeAlignment(unsigned BitWidth) const;
    245 
    246 
    247   /// getCallFrameTypeAlignment - Return the minimum ABI-required alignment
    248   /// for the specified type when it is part of a call frame.
    249   unsigned getCallFrameTypeAlignment(Type *Ty) const;
    250 
    251 
    252   /// getPrefTypeAlignment - Return the preferred stack/global alignment for
    253   /// the specified type.  This is always at least as good as the ABI alignment.
    254   unsigned getPrefTypeAlignment(Type *Ty) const;
    255 
    256   /// getPreferredTypeAlignmentShift - Return the preferred alignment for the
    257   /// specified type, returned as log2 of the value (a shift amount).
    258   ///
    259   unsigned getPreferredTypeAlignmentShift(Type *Ty) const;
    260 
    261   /// getIntPtrType - Return an unsigned integer type that is the same size or
    262   /// greater to the host pointer size.
    263   ///
    264   IntegerType *getIntPtrType(LLVMContext &C) const;
    265 
    266   /// getIndexedOffset - return the offset from the beginning of the type for
    267   /// the specified indices.  This is used to implement getelementptr.
    268   ///
    269   uint64_t getIndexedOffset(Type *Ty, ArrayRef<Value *> Indices) const;
    270 
    271   /// getStructLayout - Return a StructLayout object, indicating the alignment
    272   /// of the struct, its size, and the offsets of its fields.  Note that this
    273   /// information is lazily cached.
    274   const StructLayout *getStructLayout(StructType *Ty) const;
    275 
    276   /// getPreferredAlignment - Return the preferred alignment of the specified
    277   /// global.  This includes an explicitly requested alignment (if the global
    278   /// has one).
    279   unsigned getPreferredAlignment(const GlobalVariable *GV) const;
    280 
    281   /// getPreferredAlignmentLog - Return the preferred alignment of the
    282   /// specified global, returned in log form.  This includes an explicitly
    283   /// requested alignment (if the global has one).
    284   unsigned getPreferredAlignmentLog(const GlobalVariable *GV) const;
    285 
    286   /// RoundUpAlignment - Round the specified value up to the next alignment
    287   /// boundary specified by Alignment.  For example, 7 rounded up to an
    288   /// alignment boundary of 4 is 8.  8 rounded up to the alignment boundary of 4
    289   /// is 8 because it is already aligned.
    290   template <typename UIntTy>
    291   static UIntTy RoundUpAlignment(UIntTy Val, unsigned Alignment) {
    292     assert((Alignment & (Alignment-1)) == 0 && "Alignment must be power of 2!");
    293     return (Val + (Alignment-1)) & ~UIntTy(Alignment-1);
    294   }
    295 
    296   static char ID; // Pass identification, replacement for typeid
    297 };
    298 
    299 /// StructLayout - used to lazily calculate structure layout information for a
    300 /// target machine, based on the TargetData structure.
    301 ///
    302 class StructLayout {
    303   uint64_t StructSize;
    304   unsigned StructAlignment;
    305   unsigned NumElements;
    306   uint64_t MemberOffsets[1];  // variable sized array!
    307 public:
    308 
    309   uint64_t getSizeInBytes() const {
    310     return StructSize;
    311   }
    312 
    313   uint64_t getSizeInBits() const {
    314     return 8*StructSize;
    315   }
    316 
    317   unsigned getAlignment() const {
    318     return StructAlignment;
    319   }
    320 
    321   /// getElementContainingOffset - Given a valid byte offset into the structure,
    322   /// return the structure index that contains it.
    323   ///
    324   unsigned getElementContainingOffset(uint64_t Offset) const;
    325 
    326   uint64_t getElementOffset(unsigned Idx) const {
    327     assert(Idx < NumElements && "Invalid element idx!");
    328     return MemberOffsets[Idx];
    329   }
    330 
    331   uint64_t getElementOffsetInBits(unsigned Idx) const {
    332     return getElementOffset(Idx)*8;
    333   }
    334 
    335 private:
    336   friend class TargetData;   // Only TargetData can create this class
    337   StructLayout(StructType *ST, const TargetData &TD);
    338 };
    339 
    340 } // End llvm namespace
    341 
    342 #endif
    343