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/ADT/DenseMap.h"
26 #include "llvm/Support/DataTypes.h"
40 /// Enum used to categorize the alignment types stored by LayoutAlignElem
42 INTEGER_ALIGN = 'i', ///< Integer type alignment
43 VECTOR_ALIGN = 'v', ///< Vector type alignment
44 FLOAT_ALIGN = 'f', ///< Floating point type alignment
45 AGGREGATE_ALIGN = 'a', ///< Aggregate alignment
46 STACK_ALIGN = 's' ///< Stack objects alignment
49 /// Layout alignment element.
51 /// Stores the alignment data associated with a given alignment type (integer,
52 /// vector, float) and type bit width.
54 /// @note The unusual order of elements in the structure attempts to reduce
55 /// padding and make the structure slightly more cache friendly.
56 struct LayoutAlignElem {
57 unsigned AlignType : 8; ///< Alignment type (AlignTypeEnum)
58 unsigned TypeBitWidth : 24; ///< Type bit width
59 unsigned ABIAlign : 16; ///< ABI alignment for this type/bitw
60 unsigned PrefAlign : 16; ///< Pref. alignment for this type/bitw
63 static LayoutAlignElem get(AlignTypeEnum align_type, unsigned abi_align,
64 unsigned pref_align, uint32_t bit_width);
65 /// Equality predicate
66 bool operator==(const LayoutAlignElem &rhs) const;
69 /// Layout pointer alignment element.
71 /// Stores the alignment data associated with a given pointer and address space.
73 /// @note The unusual order of elements in the structure attempts to reduce
74 /// padding and make the structure slightly more cache friendly.
75 struct PointerAlignElem {
76 unsigned ABIAlign; ///< ABI alignment for this type/bitw
77 unsigned PrefAlign; ///< Pref. alignment for this type/bitw
78 uint32_t TypeBitWidth; ///< Type bit width
79 uint32_t AddressSpace; ///< Address space for the pointer type
82 static PointerAlignElem get(uint32_t addr_space, unsigned abi_align,
83 unsigned pref_align, uint32_t bit_width);
84 /// Equality predicate
85 bool operator==(const PointerAlignElem &rhs) const;
89 /// DataLayout - This class holds a parsed version of the target data layout
90 /// string in a module and provides methods for querying it. The target data
91 /// layout string is specified *by the target* - a frontend generating LLVM IR
92 /// is required to generate the right target data for the target being codegen'd
93 /// to. If some measure of portability is desired, an empty string may be
94 /// specified in the module.
95 class DataLayout : public ImmutablePass {
97 bool LittleEndian; ///< Defaults to false
98 unsigned StackNaturalAlign; ///< Stack natural alignment
100 SmallVector<unsigned char, 8> LegalIntWidths; ///< Legal Integers.
102 /// Alignments- Where the primitive type alignment data is stored.
105 /// @note Could support multiple size pointer alignments, e.g., 32-bit
106 /// pointers vs. 64-bit pointers by extending LayoutAlignment, but for now,
108 SmallVector<LayoutAlignElem, 16> Alignments;
109 DenseMap<unsigned, PointerAlignElem> Pointers;
111 /// InvalidAlignmentElem - This member is a signal that a requested alignment
112 /// type and bit width were not found in the SmallVector.
113 static const LayoutAlignElem InvalidAlignmentElem;
115 /// InvalidPointerElem - This member is a signal that a requested pointer
116 /// type and bit width were not found in the DenseSet.
117 static const PointerAlignElem InvalidPointerElem;
119 // The StructType -> StructLayout map.
120 mutable void *LayoutMap;
122 //! Set/initialize target alignments
123 void setAlignment(AlignTypeEnum align_type, unsigned abi_align,
124 unsigned pref_align, uint32_t bit_width);
125 unsigned getAlignmentInfo(AlignTypeEnum align_type, uint32_t bit_width,
126 bool ABIAlign, Type *Ty) const;
128 //! Set/initialize pointer alignments
129 void setPointerAlignment(uint32_t addr_space, unsigned abi_align,
130 unsigned pref_align, uint32_t bit_width);
132 //! Internal helper method that returns requested alignment for type.
133 unsigned getAlignment(Type *Ty, bool abi_or_pref) const;
135 /// Valid alignment predicate.
137 /// Predicate that tests a LayoutAlignElem reference returned by get() against
138 /// InvalidAlignmentElem.
139 bool validAlignment(const LayoutAlignElem &align) const {
140 return &align != &InvalidAlignmentElem;
143 /// Valid pointer predicate.
145 /// Predicate that tests a PointerAlignElem reference returned by get() against
146 /// InvalidPointerElem.
147 bool validPointer(const PointerAlignElem &align) const {
148 return &align != &InvalidPointerElem;
151 /// Initialise a DataLayout object with default values, ensure that the
152 /// target data pass is registered.
158 /// @note This has to exist, because this is a pass, but it should never be
162 /// Constructs a DataLayout from a specification string. See init().
163 explicit DataLayout(StringRef LayoutDescription)
164 : ImmutablePass(ID) {
165 std::string errMsg = parseSpecifier(LayoutDescription, this);
166 assert(errMsg == "" && "Invalid target data layout string.");
170 /// Parses a target data specification string. Returns an error message
171 /// if the string is malformed, or the empty string on success. Optionally
172 /// initialises a DataLayout object if passed a non-null pointer.
173 static std::string parseSpecifier(StringRef LayoutDescription,
176 /// Initialize target data from properties stored in the module.
177 explicit DataLayout(const Module *M);
179 DataLayout(const DataLayout &TD) :
181 LittleEndian(TD.isLittleEndian()),
182 LegalIntWidths(TD.LegalIntWidths),
183 Alignments(TD.Alignments),
184 Pointers(TD.Pointers),
188 ~DataLayout(); // Not virtual, do not subclass this class
190 /// Layout endianness...
191 bool isLittleEndian() const { return LittleEndian; }
192 bool isBigEndian() const { return !LittleEndian; }
194 /// getStringRepresentation - Return the string representation of the
195 /// DataLayout. This representation is in the same format accepted by the
196 /// string constructor above.
197 std::string getStringRepresentation() const;
199 /// isLegalInteger - This function returns true if the specified type is
200 /// known to be a native integer type supported by the CPU. For example,
201 /// i64 is not native on most 32-bit CPUs and i37 is not native on any known
202 /// one. This returns false if the integer width is not legal.
204 /// The width is specified in bits.
206 bool isLegalInteger(unsigned Width) const {
207 for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
208 if (LegalIntWidths[i] == Width)
213 bool isIllegalInteger(unsigned Width) const {
214 return !isLegalInteger(Width);
217 /// Returns true if the given alignment exceeds the natural stack alignment.
218 bool exceedsNaturalStackAlignment(unsigned Align) const {
219 return (StackNaturalAlign != 0) && (Align > StackNaturalAlign);
222 /// fitsInLegalInteger - This function returns true if the specified type fits
223 /// in a native integer type supported by the CPU. For example, if the CPU
224 /// only supports i32 as a native integer type, then i27 fits in a legal
225 // integer type but i45 does not.
226 bool fitsInLegalInteger(unsigned Width) const {
227 for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
228 if (Width <= LegalIntWidths[i])
233 /// Layout pointer alignment
234 /// FIXME: The defaults need to be removed once all of
235 /// the backends/clients are updated.
236 unsigned getPointerABIAlignment(unsigned AS = 0) const {
237 DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
238 if (val == Pointers.end()) {
239 val = Pointers.find(0);
241 return val->second.ABIAlign;
243 /// Return target's alignment for stack-based pointers
244 /// FIXME: The defaults need to be removed once all of
245 /// the backends/clients are updated.
246 unsigned getPointerPrefAlignment(unsigned AS = 0) const {
247 DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
248 if (val == Pointers.end()) {
249 val = Pointers.find(0);
251 return val->second.PrefAlign;
253 /// Layout pointer size
254 /// FIXME: The defaults need to be removed once all of
255 /// the backends/clients are updated.
256 unsigned getPointerSize(unsigned AS = 0) const {
257 DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
258 if (val == Pointers.end()) {
259 val = Pointers.find(0);
261 return val->second.TypeBitWidth;
263 /// Layout pointer size, in bits
264 /// FIXME: The defaults need to be removed once all of
265 /// the backends/clients are updated.
266 unsigned getPointerSizeInBits(unsigned AS = 0) const {
267 DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
268 if (val == Pointers.end()) {
269 val = Pointers.find(0);
271 return 8*val->second.TypeBitWidth;
275 /// Type SizeInBits StoreSizeInBits AllocSizeInBits[*]
276 /// ---- ---------- --------------- ---------------
285 /// X86_FP80 80 80 96
287 /// [*] The alloc size depends on the alignment, and thus on the target.
288 /// These values are for x86-32 linux.
290 /// getTypeSizeInBits - Return the number of bits necessary to hold the
291 /// specified type. For example, returns 36 for i36 and 80 for x86_fp80.
292 uint64_t getTypeSizeInBits(Type* Ty) const;
294 /// getTypeStoreSize - Return the maximum number of bytes that may be
295 /// overwritten by storing the specified type. For example, returns 5
296 /// for i36 and 10 for x86_fp80.
297 uint64_t getTypeStoreSize(Type *Ty) const {
298 return (getTypeSizeInBits(Ty)+7)/8;
301 /// getTypeStoreSizeInBits - Return the maximum number of bits that may be
302 /// overwritten by storing the specified type; always a multiple of 8. For
303 /// example, returns 40 for i36 and 80 for x86_fp80.
304 uint64_t getTypeStoreSizeInBits(Type *Ty) const {
305 return 8*getTypeStoreSize(Ty);
308 /// getTypeAllocSize - Return the offset in bytes between successive objects
309 /// of the specified type, including alignment padding. This is the amount
310 /// that alloca reserves for this type. For example, returns 12 or 16 for
311 /// x86_fp80, depending on alignment.
312 uint64_t getTypeAllocSize(Type* Ty) const {
313 // Round up to the next alignment boundary.
314 return RoundUpAlignment(getTypeStoreSize(Ty), getABITypeAlignment(Ty));
317 /// getTypeAllocSizeInBits - Return the offset in bits between successive
318 /// objects of the specified type, including alignment padding; always a
319 /// multiple of 8. This is the amount that alloca reserves for this type.
320 /// For example, returns 96 or 128 for x86_fp80, depending on alignment.
321 uint64_t getTypeAllocSizeInBits(Type* Ty) const {
322 return 8*getTypeAllocSize(Ty);
325 /// getABITypeAlignment - Return the minimum ABI-required alignment for the
327 unsigned getABITypeAlignment(Type *Ty) const;
329 /// getABIIntegerTypeAlignment - Return the minimum ABI-required alignment for
330 /// an integer type of the specified bitwidth.
331 unsigned getABIIntegerTypeAlignment(unsigned BitWidth) const;
334 /// getCallFrameTypeAlignment - Return the minimum ABI-required alignment
335 /// for the specified type when it is part of a call frame.
336 unsigned getCallFrameTypeAlignment(Type *Ty) const;
339 /// getPrefTypeAlignment - Return the preferred stack/global alignment for
340 /// the specified type. This is always at least as good as the ABI alignment.
341 unsigned getPrefTypeAlignment(Type *Ty) const;
343 /// getPreferredTypeAlignmentShift - Return the preferred alignment for the
344 /// specified type, returned as log2 of the value (a shift amount).
346 unsigned getPreferredTypeAlignmentShift(Type *Ty) const;
348 /// getIntPtrType - Return an unsigned integer type that is the same size or
349 /// greater to the host pointer size.
350 /// FIXME: Need to remove the default argument when the rest of the LLVM code
351 /// base has been updated.
352 IntegerType *getIntPtrType(LLVMContext &C, unsigned AddressSpace = 0) const;
354 /// getIndexedOffset - return the offset from the beginning of the type for
355 /// the specified indices. This is used to implement getelementptr.
357 uint64_t getIndexedOffset(Type *Ty, ArrayRef<Value *> Indices) const;
359 /// getStructLayout - Return a StructLayout object, indicating the alignment
360 /// of the struct, its size, and the offsets of its fields. Note that this
361 /// information is lazily cached.
362 const StructLayout *getStructLayout(StructType *Ty) const;
364 /// getPreferredAlignment - Return the preferred alignment of the specified
365 /// global. This includes an explicitly requested alignment (if the global
367 unsigned getPreferredAlignment(const GlobalVariable *GV) const;
369 /// getPreferredAlignmentLog - Return the preferred alignment of the
370 /// specified global, returned in log form. This includes an explicitly
371 /// requested alignment (if the global has one).
372 unsigned getPreferredAlignmentLog(const GlobalVariable *GV) const;
374 /// RoundUpAlignment - Round the specified value up to the next alignment
375 /// boundary specified by Alignment. For example, 7 rounded up to an
376 /// alignment boundary of 4 is 8. 8 rounded up to the alignment boundary of 4
377 /// is 8 because it is already aligned.
378 template <typename UIntTy>
379 static UIntTy RoundUpAlignment(UIntTy Val, unsigned Alignment) {
380 assert((Alignment & (Alignment-1)) == 0 && "Alignment must be power of 2!");
381 return (Val + (Alignment-1)) & ~UIntTy(Alignment-1);
384 static char ID; // Pass identification, replacement for typeid
387 /// StructLayout - used to lazily calculate structure layout information for a
388 /// target machine, based on the DataLayout structure.
392 unsigned StructAlignment;
393 unsigned NumElements;
394 uint64_t MemberOffsets[1]; // variable sized array!
397 uint64_t getSizeInBytes() const {
401 uint64_t getSizeInBits() const {
405 unsigned getAlignment() const {
406 return StructAlignment;
409 /// getElementContainingOffset - Given a valid byte offset into the structure,
410 /// return the structure index that contains it.
412 unsigned getElementContainingOffset(uint64_t Offset) const;
414 uint64_t getElementOffset(unsigned Idx) const {
415 assert(Idx < NumElements && "Invalid element idx!");
416 return MemberOffsets[Idx];
419 uint64_t getElementOffsetInBits(unsigned Idx) const {
420 return getElementOffset(Idx)*8;
424 friend class DataLayout; // Only DataLayout can create this class
425 StructLayout(StructType *ST, const DataLayout &TD);
428 } // End llvm namespace