1 //===--------- llvm/DataLayout.h - Data size & alignment info ---*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines layout 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.
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.
18 //===----------------------------------------------------------------------===//
20 #ifndef LLVM_DATALAYOUT_H
21 #define LLVM_DATALAYOUT_H
23 #include "llvm/Pass.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/Support/DataTypes.h"
39 /// Enum used to categorize the alignment types stored by LayoutAlignElem
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
48 /// Layout alignment element.
50 /// Stores the alignment data associated with a given alignment type (pointer,
51 /// integer, vector, float) and type bit width.
53 /// @note The unusual order of elements in the structure attempts to reduce
54 /// padding and make the structure slightly more cache friendly.
55 struct LayoutAlignElem {
56 unsigned AlignType : 8; ///< Alignment type (AlignTypeEnum)
57 unsigned TypeBitWidth : 24; ///< Type bit width
58 unsigned ABIAlign : 16; ///< ABI alignment for this type/bitw
59 unsigned PrefAlign : 16; ///< Pref. alignment for this type/bitw
62 static LayoutAlignElem get(AlignTypeEnum align_type, unsigned abi_align,
63 unsigned pref_align, uint32_t bit_width);
64 /// Equality predicate
65 bool operator==(const LayoutAlignElem &rhs) const;
68 /// DataLayout - This class holds a parsed version of the target data layout
69 /// string in a module and provides methods for querying it. The target data
70 /// layout string is specified *by the target* - a frontend generating LLVM IR
71 /// is required to generate the right target data for the target being codegen'd
72 /// to. If some measure of portability is desired, an empty string may be
73 /// specified in the module.
74 class DataLayout : public ImmutablePass {
76 bool LittleEndian; ///< Defaults to false
77 unsigned PointerMemSize; ///< Pointer size in bytes
78 unsigned PointerABIAlign; ///< Pointer ABI alignment
79 unsigned PointerPrefAlign; ///< Pointer preferred alignment
80 unsigned StackNaturalAlign; ///< Stack natural alignment
82 SmallVector<unsigned char, 8> LegalIntWidths; ///< Legal Integers.
84 /// Alignments- Where the primitive type alignment data is stored.
87 /// @note Could support multiple size pointer alignments, e.g., 32-bit
88 /// pointers vs. 64-bit pointers by extending LayoutAlignment, but for now,
90 SmallVector<LayoutAlignElem, 16> Alignments;
92 /// InvalidAlignmentElem - This member is a signal that a requested alignment
93 /// type and bit width were not found in the SmallVector.
94 static const LayoutAlignElem InvalidAlignmentElem;
96 // The StructType -> StructLayout map.
97 mutable void *LayoutMap;
99 //! Set/initialize target alignments
100 void setAlignment(AlignTypeEnum align_type, unsigned abi_align,
101 unsigned pref_align, uint32_t bit_width);
102 unsigned getAlignmentInfo(AlignTypeEnum align_type, uint32_t bit_width,
103 bool ABIAlign, Type *Ty) const;
104 //! Internal helper method that returns requested alignment for type.
105 unsigned getAlignment(Type *Ty, bool abi_or_pref) const;
107 /// Valid alignment predicate.
109 /// Predicate that tests a LayoutAlignElem reference returned by get() against
110 /// InvalidAlignmentElem.
111 bool validAlignment(const LayoutAlignElem &align) const {
112 return &align != &InvalidAlignmentElem;
115 /// Initialise a DataLayout object with default values, ensure that the
116 /// target data pass is registered.
122 /// @note This has to exist, because this is a pass, but it should never be
126 /// Constructs a DataLayout from a specification string. See init().
127 explicit DataLayout(StringRef LayoutDescription)
128 : ImmutablePass(ID) {
129 std::string errMsg = parseSpecifier(LayoutDescription, this);
130 assert(errMsg == "" && "Invalid target data layout string.");
134 /// Parses a target data specification string. Returns an error message
135 /// if the string is malformed, or the empty string on success. Optionally
136 /// initialises a DataLayout object if passed a non-null pointer.
137 static std::string parseSpecifier(StringRef LayoutDescription,
140 /// Initialize target data from properties stored in the module.
141 explicit DataLayout(const Module *M);
143 DataLayout(const DataLayout &TD) :
145 LittleEndian(TD.isLittleEndian()),
146 PointerMemSize(TD.PointerMemSize),
147 PointerABIAlign(TD.PointerABIAlign),
148 PointerPrefAlign(TD.PointerPrefAlign),
149 LegalIntWidths(TD.LegalIntWidths),
150 Alignments(TD.Alignments),
154 ~DataLayout(); // Not virtual, do not subclass this class
156 /// Layout endianness...
157 bool isLittleEndian() const { return LittleEndian; }
158 bool isBigEndian() const { return !LittleEndian; }
160 /// getStringRepresentation - Return the string representation of the
161 /// DataLayout. This representation is in the same format accepted by the
162 /// string constructor above.
163 std::string getStringRepresentation() const;
165 /// isLegalInteger - This function returns true if the specified type is
166 /// known to be a native integer type supported by the CPU. For example,
167 /// i64 is not native on most 32-bit CPUs and i37 is not native on any known
168 /// one. This returns false if the integer width is not legal.
170 /// The width is specified in bits.
172 bool isLegalInteger(unsigned Width) const {
173 for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
174 if (LegalIntWidths[i] == Width)
179 bool isIllegalInteger(unsigned Width) const {
180 return !isLegalInteger(Width);
183 /// Returns true if the given alignment exceeds the natural stack alignment.
184 bool exceedsNaturalStackAlignment(unsigned Align) const {
185 return (StackNaturalAlign != 0) && (Align > StackNaturalAlign);
188 /// fitsInLegalInteger - This function returns true if the specified type fits
189 /// in a native integer type supported by the CPU. For example, if the CPU
190 /// only supports i32 as a native integer type, then i27 fits in a legal
191 // integer type but i45 does not.
192 bool fitsInLegalInteger(unsigned Width) const {
193 for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
194 if (Width <= LegalIntWidths[i])
199 /// Layout pointer alignment
200 unsigned getPointerABIAlignment() const { return PointerABIAlign; }
201 /// Return layout's alignment for stack-based pointers
202 unsigned getPointerPrefAlignment() const { return PointerPrefAlign; }
203 /// Layout pointer size
204 unsigned getPointerSize() const { return PointerMemSize; }
205 /// Layout pointer size, in bits
206 unsigned getPointerSizeInBits() const { return 8*PointerMemSize; }
210 /// Type SizeInBits StoreSizeInBits AllocSizeInBits[*]
211 /// ---- ---------- --------------- ---------------
220 /// X86_FP80 80 80 96
222 /// [*] The alloc size depends on the alignment, and thus on the target.
223 /// These values are for x86-32 linux.
225 /// getTypeSizeInBits - Return the number of bits necessary to hold the
226 /// specified type. For example, returns 36 for i36 and 80 for x86_fp80.
227 uint64_t getTypeSizeInBits(Type* Ty) const;
229 /// getTypeStoreSize - Return the maximum number of bytes that may be
230 /// overwritten by storing the specified type. For example, returns 5
231 /// for i36 and 10 for x86_fp80.
232 uint64_t getTypeStoreSize(Type *Ty) const {
233 return (getTypeSizeInBits(Ty)+7)/8;
236 /// getTypeStoreSizeInBits - Return the maximum number of bits that may be
237 /// overwritten by storing the specified type; always a multiple of 8. For
238 /// example, returns 40 for i36 and 80 for x86_fp80.
239 uint64_t getTypeStoreSizeInBits(Type *Ty) const {
240 return 8*getTypeStoreSize(Ty);
243 /// getTypeAllocSize - Return the offset in bytes between successive objects
244 /// of the specified type, including alignment padding. This is the amount
245 /// that alloca reserves for this type. For example, returns 12 or 16 for
246 /// x86_fp80, depending on alignment.
247 uint64_t getTypeAllocSize(Type* Ty) const {
248 // Round up to the next alignment boundary.
249 return RoundUpAlignment(getTypeStoreSize(Ty), getABITypeAlignment(Ty));
252 /// getTypeAllocSizeInBits - Return the offset in bits between successive
253 /// objects of the specified type, including alignment padding; always a
254 /// multiple of 8. This is the amount that alloca reserves for this type.
255 /// For example, returns 96 or 128 for x86_fp80, depending on alignment.
256 uint64_t getTypeAllocSizeInBits(Type* Ty) const {
257 return 8*getTypeAllocSize(Ty);
260 /// getABITypeAlignment - Return the minimum ABI-required alignment for the
262 unsigned getABITypeAlignment(Type *Ty) const;
264 /// getABIIntegerTypeAlignment - Return the minimum ABI-required alignment for
265 /// an integer type of the specified bitwidth.
266 unsigned getABIIntegerTypeAlignment(unsigned BitWidth) const;
269 /// getCallFrameTypeAlignment - Return the minimum ABI-required alignment
270 /// for the specified type when it is part of a call frame.
271 unsigned getCallFrameTypeAlignment(Type *Ty) const;
274 /// getPrefTypeAlignment - Return the preferred stack/global alignment for
275 /// the specified type. This is always at least as good as the ABI alignment.
276 unsigned getPrefTypeAlignment(Type *Ty) const;
278 /// getPreferredTypeAlignmentShift - Return the preferred alignment for the
279 /// specified type, returned as log2 of the value (a shift amount).
281 unsigned getPreferredTypeAlignmentShift(Type *Ty) const;
283 /// getIntPtrType - Return an unsigned integer type that is the same size or
284 /// greater to the host pointer size.
286 IntegerType *getIntPtrType(LLVMContext &C) const;
288 /// getIndexedOffset - return the offset from the beginning of the type for
289 /// the specified indices. This is used to implement getelementptr.
291 uint64_t getIndexedOffset(Type *Ty, ArrayRef<Value *> Indices) const;
293 /// getStructLayout - Return a StructLayout object, indicating the alignment
294 /// of the struct, its size, and the offsets of its fields. Note that this
295 /// information is lazily cached.
296 const StructLayout *getStructLayout(StructType *Ty) const;
298 /// getPreferredAlignment - Return the preferred alignment of the specified
299 /// global. This includes an explicitly requested alignment (if the global
301 unsigned getPreferredAlignment(const GlobalVariable *GV) const;
303 /// getPreferredAlignmentLog - Return the preferred alignment of the
304 /// specified global, returned in log form. This includes an explicitly
305 /// requested alignment (if the global has one).
306 unsigned getPreferredAlignmentLog(const GlobalVariable *GV) const;
308 /// RoundUpAlignment - Round the specified value up to the next alignment
309 /// boundary specified by Alignment. For example, 7 rounded up to an
310 /// alignment boundary of 4 is 8. 8 rounded up to the alignment boundary of 4
311 /// is 8 because it is already aligned.
312 template <typename UIntTy>
313 static UIntTy RoundUpAlignment(UIntTy Val, unsigned Alignment) {
314 assert((Alignment & (Alignment-1)) == 0 && "Alignment must be power of 2!");
315 return (Val + (Alignment-1)) & ~UIntTy(Alignment-1);
318 static char ID; // Pass identification, replacement for typeid
321 /// StructLayout - used to lazily calculate structure layout information for a
322 /// target machine, based on the DataLayout structure.
326 unsigned StructAlignment;
327 unsigned NumElements;
328 uint64_t MemberOffsets[1]; // variable sized array!
331 uint64_t getSizeInBytes() const {
335 uint64_t getSizeInBits() const {
339 unsigned getAlignment() const {
340 return StructAlignment;
343 /// getElementContainingOffset - Given a valid byte offset into the structure,
344 /// return the structure index that contains it.
346 unsigned getElementContainingOffset(uint64_t Offset) const;
348 uint64_t getElementOffset(unsigned Idx) const {
349 assert(Idx < NumElements && "Invalid element idx!");
350 return MemberOffsets[Idx];
353 uint64_t getElementOffsetInBits(unsigned Idx) const {
354 return getElementOffset(Idx)*8;
358 friend class DataLayout; // Only DataLayout can create this class
359 StructLayout(StructType *ST, const DataLayout &TD);
362 } // End llvm namespace