LLVM API Documentation

DataLayout.h
Go to the documentation of this file.
00001 //===--------- llvm/DataLayout.h - Data size & alignment info ---*- C++ -*-===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file defines layout properties related to datatype size/offset/alignment
00011 // information.  It uses lazy annotations to cache information about how
00012 // structure types are laid out and used.
00013 //
00014 // This structure should be created once, filled in if the defaults are not
00015 // correct and then passed around by const&.  None of the members functions
00016 // require modification to the object.
00017 //
00018 //===----------------------------------------------------------------------===//
00019 
00020 #ifndef LLVM_IR_DATALAYOUT_H
00021 #define LLVM_IR_DATALAYOUT_H
00022 
00023 #include "llvm/ADT/DenseMap.h"
00024 #include "llvm/ADT/SmallVector.h"
00025 #include "llvm/IR/DerivedTypes.h"
00026 #include "llvm/IR/Type.h"
00027 #include "llvm/Pass.h"
00028 #include "llvm/Support/DataTypes.h"
00029 
00030 // This needs to be outside of the namespace, to avoid conflict with llvm-c
00031 // decl.
00032 typedef struct LLVMOpaqueTargetData *LLVMTargetDataRef;
00033 
00034 namespace llvm {
00035 
00036 class Value;
00037 class Type;
00038 class IntegerType;
00039 class StructType;
00040 class StructLayout;
00041 class Triple;
00042 class GlobalVariable;
00043 class LLVMContext;
00044 template<typename T>
00045 class ArrayRef;
00046 
00047 /// Enum used to categorize the alignment types stored by LayoutAlignElem
00048 enum AlignTypeEnum {
00049   INVALID_ALIGN = 0,
00050   INTEGER_ALIGN = 'i',
00051   VECTOR_ALIGN = 'v',
00052   FLOAT_ALIGN = 'f',
00053   AGGREGATE_ALIGN = 'a'
00054 };
00055 
00056 // FIXME: Currently the DataLayout string carries a "preferred alignment"
00057 // for types. As the DataLayout is module/global, this should likely be
00058 // sunk down to an FTTI element that is queried rather than a global
00059 // preference.
00060 
00061 /// \brief Layout alignment element.
00062 ///
00063 /// Stores the alignment data associated with a given alignment type (integer,
00064 /// vector, float) and type bit width.
00065 ///
00066 /// \note The unusual order of elements in the structure attempts to reduce
00067 /// padding and make the structure slightly more cache friendly.
00068 struct LayoutAlignElem {
00069   /// \brief Alignment type from \c AlignTypeEnum
00070   unsigned AlignType : 8;
00071   unsigned TypeBitWidth : 24;
00072   unsigned ABIAlign : 16;
00073   unsigned PrefAlign : 16;
00074 
00075   static LayoutAlignElem get(AlignTypeEnum align_type, unsigned abi_align,
00076                              unsigned pref_align, uint32_t bit_width);
00077   bool operator==(const LayoutAlignElem &rhs) const;
00078 };
00079 
00080 /// \brief Layout pointer alignment element.
00081 ///
00082 /// Stores the alignment data associated with a given pointer and address space.
00083 ///
00084 /// \note The unusual order of elements in the structure attempts to reduce
00085 /// padding and make the structure slightly more cache friendly.
00086 struct PointerAlignElem {
00087   unsigned ABIAlign;
00088   unsigned PrefAlign;
00089   uint32_t TypeByteWidth;
00090   uint32_t AddressSpace;
00091 
00092   /// Initializer
00093   static PointerAlignElem get(uint32_t AddressSpace, unsigned ABIAlign,
00094                               unsigned PrefAlign, uint32_t TypeByteWidth);
00095   bool operator==(const PointerAlignElem &rhs) const;
00096 };
00097 
00098 /// \brief A parsed version of the target data layout string in and methods for
00099 /// querying it.
00100 ///
00101 /// The target data layout string is specified *by the target* - a frontend
00102 /// generating LLVM IR is required to generate the right target data for the
00103 /// target being codegen'd to.
00104 class DataLayout {
00105 private:
00106   /// Defaults to false.
00107   bool BigEndian;
00108 
00109   unsigned StackNaturalAlign;
00110 
00111   enum ManglingModeT { MM_None, MM_ELF, MM_MachO, MM_WINCOFF, MM_Mips };
00112   ManglingModeT ManglingMode;
00113 
00114   SmallVector<unsigned char, 8> LegalIntWidths;
00115 
00116   /// \brief Primitive type alignment data.
00117   SmallVector<LayoutAlignElem, 16> Alignments;
00118 
00119   typedef SmallVector<PointerAlignElem, 8> PointersTy;
00120   PointersTy Pointers;
00121 
00122   PointersTy::const_iterator
00123   findPointerLowerBound(uint32_t AddressSpace) const {
00124     return const_cast<DataLayout *>(this)->findPointerLowerBound(AddressSpace);
00125   }
00126 
00127   PointersTy::iterator findPointerLowerBound(uint32_t AddressSpace);
00128 
00129   /// This member is a signal that a requested alignment type and bit width were
00130   /// not found in the SmallVector.
00131   static const LayoutAlignElem InvalidAlignmentElem;
00132 
00133   /// This member is a signal that a requested pointer type and bit width were
00134   /// not found in the DenseSet.
00135   static const PointerAlignElem InvalidPointerElem;
00136 
00137   // The StructType -> StructLayout map.
00138   mutable void *LayoutMap;
00139 
00140   void setAlignment(AlignTypeEnum align_type, unsigned abi_align,
00141                     unsigned pref_align, uint32_t bit_width);
00142   unsigned getAlignmentInfo(AlignTypeEnum align_type, uint32_t bit_width,
00143                             bool ABIAlign, Type *Ty) const;
00144   void setPointerAlignment(uint32_t AddrSpace, unsigned ABIAlign,
00145                            unsigned PrefAlign, uint32_t TypeByteWidth);
00146 
00147   /// Internal helper method that returns requested alignment for type.
00148   unsigned getAlignment(Type *Ty, bool abi_or_pref) const;
00149 
00150   /// \brief Valid alignment predicate.
00151   ///
00152   /// Predicate that tests a LayoutAlignElem reference returned by get() against
00153   /// InvalidAlignmentElem.
00154   bool validAlignment(const LayoutAlignElem &align) const {
00155     return &align != &InvalidAlignmentElem;
00156   }
00157 
00158   /// \brief Valid pointer predicate.
00159   ///
00160   /// Predicate that tests a PointerAlignElem reference returned by get()
00161   /// against \c InvalidPointerElem.
00162   bool validPointer(const PointerAlignElem &align) const {
00163     return &align != &InvalidPointerElem;
00164   }
00165 
00166   /// Parses a target data specification string. Assert if the string is
00167   /// malformed.
00168   void parseSpecifier(StringRef LayoutDescription);
00169 
00170   // Free all internal data structures.
00171   void clear();
00172 
00173 public:
00174   /// Constructs a DataLayout from a specification string. See reset().
00175   explicit DataLayout(StringRef LayoutDescription) : LayoutMap(nullptr) {
00176     reset(LayoutDescription);
00177   }
00178 
00179   /// Initialize target data from properties stored in the module.
00180   explicit DataLayout(const Module *M);
00181 
00182   void init(const Module *M);
00183 
00184   DataLayout(const DataLayout &DL) : LayoutMap(nullptr) { *this = DL; }
00185 
00186   DataLayout &operator=(const DataLayout &DL) {
00187     clear();
00188     BigEndian = DL.isBigEndian();
00189     StackNaturalAlign = DL.StackNaturalAlign;
00190     ManglingMode = DL.ManglingMode;
00191     LegalIntWidths = DL.LegalIntWidths;
00192     Alignments = DL.Alignments;
00193     Pointers = DL.Pointers;
00194     return *this;
00195   }
00196 
00197   bool operator==(const DataLayout &Other) const;
00198   bool operator!=(const DataLayout &Other) const { return !(*this == Other); }
00199 
00200   ~DataLayout(); // Not virtual, do not subclass this class
00201 
00202   /// Parse a data layout string (with fallback to default values).
00203   void reset(StringRef LayoutDescription);
00204 
00205   /// Layout endianness...
00206   bool isLittleEndian() const { return !BigEndian; }
00207   bool isBigEndian() const { return BigEndian; }
00208 
00209   /// \brief Returns the string representation of the DataLayout.
00210   ///
00211   /// This representation is in the same format accepted by the string
00212   /// constructor above.
00213   std::string getStringRepresentation() const;
00214 
00215   /// \brief Returns true if the specified type is known to be a native integer
00216   /// type supported by the CPU.
00217   ///
00218   /// For example, i64 is not native on most 32-bit CPUs and i37 is not native
00219   /// on any known one. This returns false if the integer width is not legal.
00220   ///
00221   /// The width is specified in bits.
00222   bool isLegalInteger(unsigned Width) const {
00223     for (unsigned LegalIntWidth : LegalIntWidths)
00224       if (LegalIntWidth == Width)
00225         return true;
00226     return false;
00227   }
00228 
00229   bool isIllegalInteger(unsigned Width) const { return !isLegalInteger(Width); }
00230 
00231   /// Returns true if the given alignment exceeds the natural stack alignment.
00232   bool exceedsNaturalStackAlignment(unsigned Align) const {
00233     return (StackNaturalAlign != 0) && (Align > StackNaturalAlign);
00234   }
00235 
00236   unsigned getStackAlignment() const { return StackNaturalAlign; }
00237 
00238   bool hasMicrosoftFastStdCallMangling() const {
00239     return ManglingMode == MM_WINCOFF;
00240   }
00241 
00242   bool hasLinkerPrivateGlobalPrefix() const { return ManglingMode == MM_MachO; }
00243 
00244   const char *getLinkerPrivateGlobalPrefix() const {
00245     if (ManglingMode == MM_MachO)
00246       return "l";
00247     return getPrivateGlobalPrefix();
00248   }
00249 
00250   char getGlobalPrefix() const {
00251     switch (ManglingMode) {
00252     case MM_None:
00253     case MM_ELF:
00254     case MM_Mips:
00255       return '\0';
00256     case MM_MachO:
00257     case MM_WINCOFF:
00258       return '_';
00259     }
00260     llvm_unreachable("invalid mangling mode");
00261   }
00262 
00263   const char *getPrivateGlobalPrefix() const {
00264     switch (ManglingMode) {
00265     case MM_None:
00266       return "";
00267     case MM_ELF:
00268       return ".L";
00269     case MM_Mips:
00270       return "$";
00271     case MM_MachO:
00272     case MM_WINCOFF:
00273       return "L";
00274     }
00275     llvm_unreachable("invalid mangling mode");
00276   }
00277 
00278   static const char *getManglingComponent(const Triple &T);
00279 
00280   /// \brief Returns true if the specified type fits in a native integer type
00281   /// supported by the CPU.
00282   ///
00283   /// For example, if the CPU only supports i32 as a native integer type, then
00284   /// i27 fits in a legal integer type but i45 does not.
00285   bool fitsInLegalInteger(unsigned Width) const {
00286     for (unsigned LegalIntWidth : LegalIntWidths)
00287       if (Width <= LegalIntWidth)
00288         return true;
00289     return false;
00290   }
00291 
00292   /// Layout pointer alignment
00293   /// FIXME: The defaults need to be removed once all of
00294   /// the backends/clients are updated.
00295   unsigned getPointerABIAlignment(unsigned AS = 0) const;
00296 
00297   /// Return target's alignment for stack-based pointers
00298   /// FIXME: The defaults need to be removed once all of
00299   /// the backends/clients are updated.
00300   unsigned getPointerPrefAlignment(unsigned AS = 0) const;
00301 
00302   /// Layout pointer size
00303   /// FIXME: The defaults need to be removed once all of
00304   /// the backends/clients are updated.
00305   unsigned getPointerSize(unsigned AS = 0) const;
00306 
00307   /// Layout pointer size, in bits
00308   /// FIXME: The defaults need to be removed once all of
00309   /// the backends/clients are updated.
00310   unsigned getPointerSizeInBits(unsigned AS = 0) const {
00311     return getPointerSize(AS) * 8;
00312   }
00313 
00314   /// Layout pointer size, in bits, based on the type.  If this function is
00315   /// called with a pointer type, then the type size of the pointer is returned.
00316   /// If this function is called with a vector of pointers, then the type size
00317   /// of the pointer is returned.  This should only be called with a pointer or
00318   /// vector of pointers.
00319   unsigned getPointerTypeSizeInBits(Type *) const;
00320 
00321   unsigned getPointerTypeSize(Type *Ty) const {
00322     return getPointerTypeSizeInBits(Ty) / 8;
00323   }
00324 
00325   /// Size examples:
00326   ///
00327   /// Type        SizeInBits  StoreSizeInBits  AllocSizeInBits[*]
00328   /// ----        ----------  ---------------  ---------------
00329   ///  i1            1           8                8
00330   ///  i8            8           8                8
00331   ///  i19          19          24               32
00332   ///  i32          32          32               32
00333   ///  i100        100         104              128
00334   ///  i128        128         128              128
00335   ///  Float        32          32               32
00336   ///  Double       64          64               64
00337   ///  X86_FP80     80          80               96
00338   ///
00339   /// [*] The alloc size depends on the alignment, and thus on the target.
00340   ///     These values are for x86-32 linux.
00341 
00342   /// \brief Returns the number of bits necessary to hold the specified type.
00343   ///
00344   /// For example, returns 36 for i36 and 80 for x86_fp80. The type passed must
00345   /// have a size (Type::isSized() must return true).
00346   uint64_t getTypeSizeInBits(Type *Ty) const;
00347 
00348   /// \brief Returns the maximum number of bytes that may be overwritten by
00349   /// storing the specified type.
00350   ///
00351   /// For example, returns 5 for i36 and 10 for x86_fp80.
00352   uint64_t getTypeStoreSize(Type *Ty) const {
00353     return (getTypeSizeInBits(Ty) + 7) / 8;
00354   }
00355 
00356   /// \brief Returns the maximum number of bits that may be overwritten by
00357   /// storing the specified type; always a multiple of 8.
00358   ///
00359   /// For example, returns 40 for i36 and 80 for x86_fp80.
00360   uint64_t getTypeStoreSizeInBits(Type *Ty) const {
00361     return 8 * getTypeStoreSize(Ty);
00362   }
00363 
00364   /// \brief Returns the offset in bytes between successive objects of the
00365   /// specified type, including alignment padding.
00366   ///
00367   /// This is the amount that alloca reserves for this type. For example,
00368   /// returns 12 or 16 for x86_fp80, depending on alignment.
00369   uint64_t getTypeAllocSize(Type *Ty) const {
00370     // Round up to the next alignment boundary.
00371     return RoundUpToAlignment(getTypeStoreSize(Ty), getABITypeAlignment(Ty));
00372   }
00373 
00374   /// \brief Returns the offset in bits between successive objects of the
00375   /// specified type, including alignment padding; always a multiple of 8.
00376   ///
00377   /// This is the amount that alloca reserves for this type. For example,
00378   /// returns 96 or 128 for x86_fp80, depending on alignment.
00379   uint64_t getTypeAllocSizeInBits(Type *Ty) const {
00380     return 8 * getTypeAllocSize(Ty);
00381   }
00382 
00383   /// \brief Returns the minimum ABI-required alignment for the specified type.
00384   unsigned getABITypeAlignment(Type *Ty) const;
00385 
00386   /// \brief Returns the minimum ABI-required alignment for an integer type of
00387   /// the specified bitwidth.
00388   unsigned getABIIntegerTypeAlignment(unsigned BitWidth) const;
00389 
00390   /// \brief Returns the preferred stack/global alignment for the specified
00391   /// type.
00392   ///
00393   /// This is always at least as good as the ABI alignment.
00394   unsigned getPrefTypeAlignment(Type *Ty) const;
00395 
00396   /// \brief Returns the preferred alignment for the specified type, returned as
00397   /// log2 of the value (a shift amount).
00398   unsigned getPreferredTypeAlignmentShift(Type *Ty) const;
00399 
00400   /// \brief Returns an integer type with size at least as big as that of a
00401   /// pointer in the given address space.
00402   IntegerType *getIntPtrType(LLVMContext &C, unsigned AddressSpace = 0) const;
00403 
00404   /// \brief Returns an integer (vector of integer) type with size at least as
00405   /// big as that of a pointer of the given pointer (vector of pointer) type.
00406   Type *getIntPtrType(Type *) const;
00407 
00408   /// \brief Returns the smallest integer type with size at least as big as
00409   /// Width bits.
00410   Type *getSmallestLegalIntType(LLVMContext &C, unsigned Width = 0) const;
00411 
00412   /// \brief Returns the largest legal integer type, or null if none are set.
00413   Type *getLargestLegalIntType(LLVMContext &C) const {
00414     unsigned LargestSize = getLargestLegalIntTypeSize();
00415     return (LargestSize == 0) ? nullptr : Type::getIntNTy(C, LargestSize);
00416   }
00417 
00418   /// \brief Returns the size of largest legal integer type size, or 0 if none
00419   /// are set.
00420   unsigned getLargestLegalIntTypeSize() const;
00421 
00422   /// \brief Returns the offset from the beginning of the type for the specified
00423   /// indices.
00424   ///
00425   /// This is used to implement getelementptr.
00426   uint64_t getIndexedOffset(Type *Ty, ArrayRef<Value *> Indices) const;
00427 
00428   /// \brief Returns a StructLayout object, indicating the alignment of the
00429   /// struct, its size, and the offsets of its fields.
00430   ///
00431   /// Note that this information is lazily cached.
00432   const StructLayout *getStructLayout(StructType *Ty) const;
00433 
00434   /// \brief Returns the preferred alignment of the specified global.
00435   ///
00436   /// This includes an explicitly requested alignment (if the global has one).
00437   unsigned getPreferredAlignment(const GlobalVariable *GV) const;
00438 
00439   /// \brief Returns the preferred alignment of the specified global, returned
00440   /// in log form.
00441   ///
00442   /// This includes an explicitly requested alignment (if the global has one).
00443   unsigned getPreferredAlignmentLog(const GlobalVariable *GV) const;
00444 };
00445 
00446 inline DataLayout *unwrap(LLVMTargetDataRef P) {
00447   return reinterpret_cast<DataLayout *>(P);
00448 }
00449 
00450 inline LLVMTargetDataRef wrap(const DataLayout *P) {
00451   return reinterpret_cast<LLVMTargetDataRef>(const_cast<DataLayout *>(P));
00452 }
00453 
00454 class DataLayoutPass : public ImmutablePass {
00455   DataLayout DL;
00456 
00457 public:
00458   /// This has to exist, because this is a pass, but it should never be used.
00459   DataLayoutPass();
00460   ~DataLayoutPass();
00461 
00462   const DataLayout &getDataLayout() const { return DL; }
00463 
00464   static char ID; // Pass identification, replacement for typeid
00465 
00466   bool doFinalization(Module &M) override;
00467   bool doInitialization(Module &M) override;
00468 };
00469 
00470 /// Used to lazily calculate structure layout information for a target machine,
00471 /// based on the DataLayout structure.
00472 class StructLayout {
00473   uint64_t StructSize;
00474   unsigned StructAlignment;
00475   unsigned NumElements;
00476   uint64_t MemberOffsets[1]; // variable sized array!
00477 public:
00478   uint64_t getSizeInBytes() const { return StructSize; }
00479 
00480   uint64_t getSizeInBits() const { return 8 * StructSize; }
00481 
00482   unsigned getAlignment() const { return StructAlignment; }
00483 
00484   /// \brief Given a valid byte offset into the structure, returns the structure
00485   /// index that contains it.
00486   unsigned getElementContainingOffset(uint64_t Offset) const;
00487 
00488   uint64_t getElementOffset(unsigned Idx) const {
00489     assert(Idx < NumElements && "Invalid element idx!");
00490     return MemberOffsets[Idx];
00491   }
00492 
00493   uint64_t getElementOffsetInBits(unsigned Idx) const {
00494     return getElementOffset(Idx) * 8;
00495   }
00496 
00497 private:
00498   friend class DataLayout; // Only DataLayout can create this class
00499   StructLayout(StructType *ST, const DataLayout &DL);
00500 };
00501 
00502 // The implementation of this method is provided inline as it is particularly
00503 // well suited to constant folding when called on a specific Type subclass.
00504 inline uint64_t DataLayout::getTypeSizeInBits(Type *Ty) const {
00505   assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
00506   switch (Ty->getTypeID()) {
00507   case Type::LabelTyID:
00508     return getPointerSizeInBits(0);
00509   case Type::PointerTyID:
00510     return getPointerSizeInBits(Ty->getPointerAddressSpace());
00511   case Type::ArrayTyID: {
00512     ArrayType *ATy = cast<ArrayType>(Ty);
00513     return ATy->getNumElements() *
00514            getTypeAllocSizeInBits(ATy->getElementType());
00515   }
00516   case Type::StructTyID:
00517     // Get the layout annotation... which is lazily created on demand.
00518     return getStructLayout(cast<StructType>(Ty))->getSizeInBits();
00519   case Type::IntegerTyID:
00520     return Ty->getIntegerBitWidth();
00521   case Type::HalfTyID:
00522     return 16;
00523   case Type::FloatTyID:
00524     return 32;
00525   case Type::DoubleTyID:
00526   case Type::X86_MMXTyID:
00527     return 64;
00528   case Type::PPC_FP128TyID:
00529   case Type::FP128TyID:
00530     return 128;
00531   // In memory objects this is always aligned to a higher boundary, but
00532   // only 80 bits contain information.
00533   case Type::X86_FP80TyID:
00534     return 80;
00535   case Type::VectorTyID: {
00536     VectorType *VTy = cast<VectorType>(Ty);
00537     return VTy->getNumElements() * getTypeSizeInBits(VTy->getElementType());
00538   }
00539   default:
00540     llvm_unreachable("DataLayout::getTypeSizeInBits(): Unsupported type");
00541   }
00542 }
00543 
00544 } // End llvm namespace
00545 
00546 #endif