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/ADT/DenseMap.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Support/DataTypes.h"
40 /// Enum used to categorize the alignment types stored by LayoutAlignElem
42 INVALID_ALIGN = 0, ///< An invalid alignment
43 INTEGER_ALIGN = 'i', ///< Integer type alignment
44 VECTOR_ALIGN = 'v', ///< Vector type alignment
45 FLOAT_ALIGN = 'f', ///< Floating point type alignment
46 AGGREGATE_ALIGN = 'a', ///< Aggregate alignment
47 STACK_ALIGN = 's' ///< Stack objects alignment
50 /// Layout alignment element.
52 /// Stores the alignment data associated with a given alignment type (integer,
53 /// vector, float) and type bit width.
55 /// @note The unusual order of elements in the structure attempts to reduce
56 /// padding and make the structure slightly more cache friendly.
57 struct LayoutAlignElem {
58 unsigned AlignType : 8; ///< Alignment type (AlignTypeEnum)
59 unsigned TypeBitWidth : 24; ///< Type bit width
60 unsigned ABIAlign : 16; ///< ABI alignment for this type/bitw
61 unsigned PrefAlign : 16; ///< Pref. alignment for this type/bitw
64 static LayoutAlignElem get(AlignTypeEnum align_type, unsigned abi_align,
65 unsigned pref_align, uint32_t bit_width);
66 /// Equality predicate
67 bool operator==(const LayoutAlignElem &rhs) const;
70 /// Layout pointer alignment element.
72 /// Stores the alignment data associated with a given pointer and address space.
74 /// @note The unusual order of elements in the structure attempts to reduce
75 /// padding and make the structure slightly more cache friendly.
76 struct PointerAlignElem {
77 unsigned ABIAlign; ///< ABI alignment for this type/bitw
78 unsigned PrefAlign; ///< Pref. alignment for this type/bitw
79 uint32_t TypeBitWidth; ///< Type bit width
80 uint32_t AddressSpace; ///< Address space for the pointer type
83 static PointerAlignElem get(uint32_t addr_space, unsigned abi_align,
84 unsigned pref_align, uint32_t bit_width);
85 /// Equality predicate
86 bool operator==(const PointerAlignElem &rhs) const;
90 /// DataLayout - This class holds a parsed version of the target data layout
91 /// string in a module and provides methods for querying it. The target data
92 /// layout string is specified *by the target* - a frontend generating LLVM IR
93 /// is required to generate the right target data for the target being codegen'd
94 /// to. If some measure of portability is desired, an empty string may be
95 /// specified in the module.
96 class DataLayout : public ImmutablePass {
98 bool LittleEndian; ///< Defaults to false
99 unsigned StackNaturalAlign; ///< Stack natural alignment
101 SmallVector<unsigned char, 8> LegalIntWidths; ///< Legal Integers.
103 /// Alignments- Where the primitive type alignment data is stored.
106 /// @note Could support multiple size pointer alignments, e.g., 32-bit
107 /// pointers vs. 64-bit pointers by extending LayoutAlignment, but for now,
109 SmallVector<LayoutAlignElem, 16> Alignments;
110 DenseMap<unsigned, PointerAlignElem> Pointers;
112 /// InvalidAlignmentElem - This member is a signal that a requested alignment
113 /// type and bit width were not found in the SmallVector.
114 static const LayoutAlignElem InvalidAlignmentElem;
116 /// InvalidPointerElem - This member is a signal that a requested pointer
117 /// type and bit width were not found in the DenseSet.
118 static const PointerAlignElem InvalidPointerElem;
120 // The StructType -> StructLayout map.
121 mutable void *LayoutMap;
123 //! Set/initialize target alignments
124 void setAlignment(AlignTypeEnum align_type, unsigned abi_align,
125 unsigned pref_align, uint32_t bit_width);
126 unsigned getAlignmentInfo(AlignTypeEnum align_type, uint32_t bit_width,
127 bool ABIAlign, Type *Ty) const;
129 //! Set/initialize pointer alignments
130 void setPointerAlignment(uint32_t addr_space, unsigned abi_align,
131 unsigned pref_align, uint32_t bit_width);
133 //! Internal helper method that returns requested alignment for type.
134 unsigned getAlignment(Type *Ty, bool abi_or_pref) const;
136 /// Valid alignment predicate.
138 /// Predicate that tests a LayoutAlignElem reference returned by get() against
139 /// InvalidAlignmentElem.
140 bool validAlignment(const LayoutAlignElem &align) const {
141 return &align != &InvalidAlignmentElem;
144 /// Valid pointer predicate.
146 /// Predicate that tests a PointerAlignElem reference returned by get() against
147 /// InvalidPointerElem.
148 bool validPointer(const PointerAlignElem &align) const {
149 return &align != &InvalidPointerElem;
152 /// Parses a target data specification string. Assert if the string is
154 void parseSpecifier(StringRef LayoutDescription);
159 /// @note This has to exist, because this is a pass, but it should never be
163 /// Constructs a DataLayout from a specification string. See init().
164 explicit DataLayout(StringRef LayoutDescription)
165 : ImmutablePass(ID) {
166 init(LayoutDescription);
169 /// Initialize target data from properties stored in the module.
170 explicit DataLayout(const Module *M);
172 DataLayout(const DataLayout &TD) :
174 LittleEndian(TD.isLittleEndian()),
175 LegalIntWidths(TD.LegalIntWidths),
176 Alignments(TD.Alignments),
177 Pointers(TD.Pointers),
181 ~DataLayout(); // Not virtual, do not subclass this class
183 /// Parse a data layout string (with fallback to default values). Ensure that
184 /// the data layout pass is registered.
185 void init(StringRef LayoutDescription);
187 /// Layout endianness...
188 bool isLittleEndian() const { return LittleEndian; }
189 bool isBigEndian() const { return !LittleEndian; }
191 /// getStringRepresentation - Return the string representation of the
192 /// DataLayout. This representation is in the same format accepted by the
193 /// string constructor above.
194 std::string getStringRepresentation() const;
196 /// isLegalInteger - This function returns true if the specified type is
197 /// known to be a native integer type supported by the CPU. For example,
198 /// i64 is not native on most 32-bit CPUs and i37 is not native on any known
199 /// one. This returns false if the integer width is not legal.
201 /// The width is specified in bits.
203 bool isLegalInteger(unsigned Width) const {
204 for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
205 if (LegalIntWidths[i] == Width)
210 bool isIllegalInteger(unsigned Width) const {
211 return !isLegalInteger(Width);
214 /// Returns true if the given alignment exceeds the natural stack alignment.
215 bool exceedsNaturalStackAlignment(unsigned Align) const {
216 return (StackNaturalAlign != 0) && (Align > StackNaturalAlign);
219 /// fitsInLegalInteger - This function returns true if the specified type fits
220 /// in a native integer type supported by the CPU. For example, if the CPU
221 /// only supports i32 as a native integer type, then i27 fits in a legal
222 // integer type but i45 does not.
223 bool fitsInLegalInteger(unsigned Width) const {
224 for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
225 if (Width <= LegalIntWidths[i])
230 /// Layout pointer alignment
231 /// FIXME: The defaults need to be removed once all of
232 /// the backends/clients are updated.
233 unsigned getPointerABIAlignment(unsigned AS = 0) const {
234 DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
235 if (val == Pointers.end()) {
236 val = Pointers.find(0);
238 return val->second.ABIAlign;
240 /// Return target's alignment for stack-based pointers
241 /// FIXME: The defaults need to be removed once all of
242 /// the backends/clients are updated.
243 unsigned getPointerPrefAlignment(unsigned AS = 0) const {
244 DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
245 if (val == Pointers.end()) {
246 val = Pointers.find(0);
248 return val->second.PrefAlign;
250 /// Layout pointer size
251 /// FIXME: The defaults need to be removed once all of
252 /// the backends/clients are updated.
253 unsigned getPointerSize(unsigned AS = 0) const {
254 DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
255 if (val == Pointers.end()) {
256 val = Pointers.find(0);
258 return val->second.TypeBitWidth;
260 /// Layout pointer size, in bits
261 /// FIXME: The defaults need to be removed once all of
262 /// the backends/clients are updated.
263 unsigned getPointerSizeInBits(unsigned AS = 0) const {
264 return getPointerSize(AS) * 8;
268 /// Type SizeInBits StoreSizeInBits AllocSizeInBits[*]
269 /// ---- ---------- --------------- ---------------
278 /// X86_FP80 80 80 96
280 /// [*] The alloc size depends on the alignment, and thus on the target.
281 /// These values are for x86-32 linux.
283 /// getTypeSizeInBits - Return the number of bits necessary to hold the
284 /// specified type. For example, returns 36 for i36 and 80 for x86_fp80.
285 /// The type passed must have a size (Type::isSized() must return true).
286 uint64_t getTypeSizeInBits(Type* Ty) const;
288 /// getTypeStoreSize - Return the maximum number of bytes that may be
289 /// overwritten by storing the specified type. For example, returns 5
290 /// for i36 and 10 for x86_fp80.
291 uint64_t getTypeStoreSize(Type *Ty) const {
292 return (getTypeSizeInBits(Ty)+7)/8;
295 /// getTypeStoreSizeInBits - Return the maximum number of bits that may be
296 /// overwritten by storing the specified type; always a multiple of 8. For
297 /// example, returns 40 for i36 and 80 for x86_fp80.
298 uint64_t getTypeStoreSizeInBits(Type *Ty) const {
299 return 8*getTypeStoreSize(Ty);
302 /// getTypeAllocSize - Return the offset in bytes between successive objects
303 /// of the specified type, including alignment padding. This is the amount
304 /// that alloca reserves for this type. For example, returns 12 or 16 for
305 /// x86_fp80, depending on alignment.
306 uint64_t getTypeAllocSize(Type* Ty) const {
307 // Round up to the next alignment boundary.
308 return RoundUpAlignment(getTypeStoreSize(Ty), getABITypeAlignment(Ty));
311 /// getTypeAllocSizeInBits - Return the offset in bits between successive
312 /// objects of the specified type, including alignment padding; always a
313 /// multiple of 8. This is the amount that alloca reserves for this type.
314 /// For example, returns 96 or 128 for x86_fp80, depending on alignment.
315 uint64_t getTypeAllocSizeInBits(Type* Ty) const {
316 return 8*getTypeAllocSize(Ty);
319 /// getABITypeAlignment - Return the minimum ABI-required alignment for the
321 unsigned getABITypeAlignment(Type *Ty) const;
323 /// getABIIntegerTypeAlignment - Return the minimum ABI-required alignment for
324 /// an integer type of the specified bitwidth.
325 unsigned getABIIntegerTypeAlignment(unsigned BitWidth) const;
328 /// getCallFrameTypeAlignment - Return the minimum ABI-required alignment
329 /// for the specified type when it is part of a call frame.
330 unsigned getCallFrameTypeAlignment(Type *Ty) const;
333 /// getPrefTypeAlignment - Return the preferred stack/global alignment for
334 /// the specified type. This is always at least as good as the ABI alignment.
335 unsigned getPrefTypeAlignment(Type *Ty) const;
337 /// getPreferredTypeAlignmentShift - Return the preferred alignment for the
338 /// specified type, returned as log2 of the value (a shift amount).
340 unsigned getPreferredTypeAlignmentShift(Type *Ty) const;
342 /// getIntPtrType - Return an integer type with size at least as big as that
343 /// of a pointer in the given address space.
344 IntegerType *getIntPtrType(LLVMContext &C, unsigned AddressSpace = 0) const;
346 /// getIntPtrType - Return an integer (vector of integer) type with size at
347 /// least as big as that of a pointer of the given pointer (vector of pointer)
349 Type *getIntPtrType(Type *) const;
351 /// getIndexedOffset - return the offset from the beginning of the type for
352 /// the specified indices. This is used to implement getelementptr.
354 uint64_t getIndexedOffset(Type *Ty, ArrayRef<Value *> Indices) const;
356 /// getStructLayout - Return a StructLayout object, indicating the alignment
357 /// of the struct, its size, and the offsets of its fields. Note that this
358 /// information is lazily cached.
359 const StructLayout *getStructLayout(StructType *Ty) const;
361 /// getPreferredAlignment - Return the preferred alignment of the specified
362 /// global. This includes an explicitly requested alignment (if the global
364 unsigned getPreferredAlignment(const GlobalVariable *GV) const;
366 /// getPreferredAlignmentLog - Return the preferred alignment of the
367 /// specified global, returned in log form. This includes an explicitly
368 /// requested alignment (if the global has one).
369 unsigned getPreferredAlignmentLog(const GlobalVariable *GV) const;
371 /// RoundUpAlignment - Round the specified value up to the next alignment
372 /// boundary specified by Alignment. For example, 7 rounded up to an
373 /// alignment boundary of 4 is 8. 8 rounded up to the alignment boundary of 4
374 /// is 8 because it is already aligned.
375 template <typename UIntTy>
376 static UIntTy RoundUpAlignment(UIntTy Val, unsigned Alignment) {
377 assert((Alignment & (Alignment-1)) == 0 && "Alignment must be power of 2!");
378 return (Val + (Alignment-1)) & ~UIntTy(Alignment-1);
381 static char ID; // Pass identification, replacement for typeid
384 /// StructLayout - used to lazily calculate structure layout information for a
385 /// target machine, based on the DataLayout structure.
389 unsigned StructAlignment;
390 unsigned NumElements;
391 uint64_t MemberOffsets[1]; // variable sized array!
394 uint64_t getSizeInBytes() const {
398 uint64_t getSizeInBits() const {
402 unsigned getAlignment() const {
403 return StructAlignment;
406 /// getElementContainingOffset - Given a valid byte offset into the structure,
407 /// return the structure index that contains it.
409 unsigned getElementContainingOffset(uint64_t Offset) const;
411 uint64_t getElementOffset(unsigned Idx) const {
412 assert(Idx < NumElements && "Invalid element idx!");
413 return MemberOffsets[Idx];
416 uint64_t getElementOffsetInBits(unsigned Idx) const {
417 return getElementOffset(Idx)*8;
421 friend class DataLayout; // Only DataLayout can create this class
422 StructLayout(StructType *ST, const DataLayout &TD);
425 } // End llvm namespace