• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===--------- llvm/DataLayout.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 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.
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_IR_DATALAYOUT_H
21 #define LLVM_IR_DATALAYOUT_H
22 
23 #include "llvm/ADT/DenseMap.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/Pass.h"
26 #include "llvm/Support/DataTypes.h"
27 
28 namespace llvm {
29 
30 class Value;
31 class Type;
32 class IntegerType;
33 class StructType;
34 class StructLayout;
35 class GlobalVariable;
36 class LLVMContext;
37 template<typename T>
38 class ArrayRef;
39 
40 /// Enum used to categorize the alignment types stored by LayoutAlignElem
41 enum AlignTypeEnum {
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
48 };
49 
50 /// Layout alignment element.
51 ///
52 /// Stores the alignment data associated with a given alignment type (integer,
53 /// vector, float) and type bit width.
54 ///
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
62 
63   /// Initializer
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;
68 };
69 
70 /// Layout pointer alignment element.
71 ///
72 /// Stores the alignment data associated with a given pointer and address space.
73 ///
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
81 
82   /// Initializer
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;
87 };
88 
89 
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 {
97 private:
98   bool          LittleEndian;          ///< Defaults to false
99   unsigned      StackNaturalAlign;     ///< Stack natural alignment
100 
101   SmallVector<unsigned char, 8> LegalIntWidths; ///< Legal Integers.
102 
103   /// Alignments - Where the primitive type alignment data is stored.
104   ///
105   /// @sa init().
106   /// @note Could support multiple size pointer alignments, e.g., 32-bit
107   /// pointers vs. 64-bit pointers by extending LayoutAlignment, but for now,
108   /// we don't.
109   SmallVector<LayoutAlignElem, 16> Alignments;
110   DenseMap<unsigned, PointerAlignElem> Pointers;
111 
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;
115 
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;
119 
120   // The StructType -> StructLayout map.
121   mutable void *LayoutMap;
122 
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;
128 
129   //! Set/initialize pointer alignments
130   void setPointerAlignment(uint32_t addr_space, unsigned abi_align,
131       unsigned pref_align, uint32_t bit_width);
132 
133   //! Internal helper method that returns requested alignment for type.
134   unsigned getAlignment(Type *Ty, bool abi_or_pref) const;
135 
136   /// Valid alignment predicate.
137   ///
138   /// Predicate that tests a LayoutAlignElem reference returned by get() against
139   /// InvalidAlignmentElem.
validAlignment(const LayoutAlignElem & align)140   bool validAlignment(const LayoutAlignElem &align) const {
141     return &align != &InvalidAlignmentElem;
142   }
143 
144   /// Valid pointer predicate.
145   ///
146   /// Predicate that tests a PointerAlignElem reference returned by get() against
147   /// InvalidPointerElem.
validPointer(const PointerAlignElem & align)148   bool validPointer(const PointerAlignElem &align) const {
149     return &align != &InvalidPointerElem;
150   }
151 
152   /// Parses a target data specification string. Assert if the string is
153   /// malformed.
154   void parseSpecifier(StringRef LayoutDescription);
155 
156 public:
157   /// Default ctor.
158   ///
159   /// @note This has to exist, because this is a pass, but it should never be
160   /// used.
161   DataLayout();
162 
163   /// Constructs a DataLayout from a specification string. See init().
DataLayout(StringRef LayoutDescription)164   explicit DataLayout(StringRef LayoutDescription)
165     : ImmutablePass(ID) {
166     init(LayoutDescription);
167   }
168 
169   /// Initialize target data from properties stored in the module.
170   explicit DataLayout(const Module *M);
171 
DataLayout(const DataLayout & TD)172   DataLayout(const DataLayout &TD) :
173     ImmutablePass(ID),
174     LittleEndian(TD.isLittleEndian()),
175     StackNaturalAlign(TD.StackNaturalAlign),
176     LegalIntWidths(TD.LegalIntWidths),
177     Alignments(TD.Alignments),
178     Pointers(TD.Pointers),
179     LayoutMap(0)
180   { }
181 
182   ~DataLayout();  // Not virtual, do not subclass this class
183 
184   /// DataLayout is an immutable pass, but holds state.  This allows the pass
185   /// manager to clear its mutable state.
186   bool doFinalization(Module &M);
187 
188   /// Parse a data layout string (with fallback to default values). Ensure that
189   /// the data layout pass is registered.
190   void init(StringRef LayoutDescription);
191 
192   /// Layout endianness...
isLittleEndian()193   bool isLittleEndian() const { return LittleEndian; }
isBigEndian()194   bool isBigEndian() const { return !LittleEndian; }
195 
196   /// getStringRepresentation - Return the string representation of the
197   /// DataLayout.  This representation is in the same format accepted by the
198   /// string constructor above.
199   std::string getStringRepresentation() const;
200 
201   /// isLegalInteger - This function returns true if the specified type is
202   /// known to be a native integer type supported by the CPU.  For example,
203   /// i64 is not native on most 32-bit CPUs and i37 is not native on any known
204   /// one.  This returns false if the integer width is not legal.
205   ///
206   /// The width is specified in bits.
207   ///
isLegalInteger(unsigned Width)208   bool isLegalInteger(unsigned Width) const {
209     for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
210       if (LegalIntWidths[i] == Width)
211         return true;
212     return false;
213   }
214 
isIllegalInteger(unsigned Width)215   bool isIllegalInteger(unsigned Width) const {
216     return !isLegalInteger(Width);
217   }
218 
219   /// Returns true if the given alignment exceeds the natural stack alignment.
exceedsNaturalStackAlignment(unsigned Align)220   bool exceedsNaturalStackAlignment(unsigned Align) const {
221     return (StackNaturalAlign != 0) && (Align > StackNaturalAlign);
222   }
223 
224   /// fitsInLegalInteger - This function returns true if the specified type fits
225   /// in a native integer type supported by the CPU.  For example, if the CPU
226   /// only supports i32 as a native integer type, then i27 fits in a legal
227   // integer type but i45 does not.
fitsInLegalInteger(unsigned Width)228   bool fitsInLegalInteger(unsigned Width) const {
229     for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
230       if (Width <= LegalIntWidths[i])
231         return true;
232     return false;
233   }
234 
235   /// Layout pointer alignment
236   /// FIXME: The defaults need to be removed once all of
237   /// the backends/clients are updated.
238   unsigned getPointerABIAlignment(unsigned AS = 0)  const {
239     DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
240     if (val == Pointers.end()) {
241       val = Pointers.find(0);
242     }
243     return val->second.ABIAlign;
244   }
245   /// Return target's alignment for stack-based pointers
246   /// FIXME: The defaults need to be removed once all of
247   /// the backends/clients are updated.
248   unsigned getPointerPrefAlignment(unsigned AS = 0) const {
249     DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
250     if (val == Pointers.end()) {
251       val = Pointers.find(0);
252     }
253     return val->second.PrefAlign;
254   }
255   /// Layout pointer size
256   /// FIXME: The defaults need to be removed once all of
257   /// the backends/clients are updated.
258   unsigned getPointerSize(unsigned AS = 0)          const {
259     DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
260     if (val == Pointers.end()) {
261       val = Pointers.find(0);
262     }
263     return val->second.TypeBitWidth;
264   }
265   /// Layout pointer size, in bits
266   /// FIXME: The defaults need to be removed once all of
267   /// the backends/clients are updated.
268   unsigned getPointerSizeInBits(unsigned AS = 0)    const {
269     return getPointerSize(AS) * 8;
270   }
271   /// Size examples:
272   ///
273   /// Type        SizeInBits  StoreSizeInBits  AllocSizeInBits[*]
274   /// ----        ----------  ---------------  ---------------
275   ///  i1            1           8                8
276   ///  i8            8           8                8
277   ///  i19          19          24               32
278   ///  i32          32          32               32
279   ///  i100        100         104              128
280   ///  i128        128         128              128
281   ///  Float        32          32               32
282   ///  Double       64          64               64
283   ///  X86_FP80     80          80               96
284   ///
285   /// [*] The alloc size depends on the alignment, and thus on the target.
286   ///     These values are for x86-32 linux.
287 
288   /// getTypeSizeInBits - Return the number of bits necessary to hold the
289   /// specified type.  For example, returns 36 for i36 and 80 for x86_fp80.
290   /// The type passed must have a size (Type::isSized() must return true).
291   uint64_t getTypeSizeInBits(Type *Ty) const;
292 
293   /// getTypeStoreSize - Return the maximum number of bytes that may be
294   /// overwritten by storing the specified type.  For example, returns 5
295   /// for i36 and 10 for x86_fp80.
getTypeStoreSize(Type * Ty)296   uint64_t getTypeStoreSize(Type *Ty) const {
297     return (getTypeSizeInBits(Ty)+7)/8;
298   }
299 
300   /// getTypeStoreSizeInBits - Return the maximum number of bits that may be
301   /// overwritten by storing the specified type; always a multiple of 8.  For
302   /// example, returns 40 for i36 and 80 for x86_fp80.
getTypeStoreSizeInBits(Type * Ty)303   uint64_t getTypeStoreSizeInBits(Type *Ty) const {
304     return 8*getTypeStoreSize(Ty);
305   }
306 
307   /// getTypeAllocSize - Return the offset in bytes between successive objects
308   /// of the specified type, including alignment padding.  This is the amount
309   /// that alloca reserves for this type.  For example, returns 12 or 16 for
310   /// x86_fp80, depending on alignment.
getTypeAllocSize(Type * Ty)311   uint64_t getTypeAllocSize(Type *Ty) const {
312     // Round up to the next alignment boundary.
313     return RoundUpAlignment(getTypeStoreSize(Ty), getABITypeAlignment(Ty));
314   }
315 
316   /// getTypeAllocSizeInBits - Return the offset in bits between successive
317   /// objects of the specified type, including alignment padding; always a
318   /// multiple of 8.  This is the amount that alloca reserves for this type.
319   /// For example, returns 96 or 128 for x86_fp80, depending on alignment.
getTypeAllocSizeInBits(Type * Ty)320   uint64_t getTypeAllocSizeInBits(Type *Ty) const {
321     return 8*getTypeAllocSize(Ty);
322   }
323 
324   /// getABITypeAlignment - Return the minimum ABI-required alignment for the
325   /// specified type.
326   unsigned getABITypeAlignment(Type *Ty) const;
327 
328   /// getABIIntegerTypeAlignment - Return the minimum ABI-required alignment for
329   /// an integer type of the specified bitwidth.
330   unsigned getABIIntegerTypeAlignment(unsigned BitWidth) const;
331 
332   /// getCallFrameTypeAlignment - Return the minimum ABI-required alignment
333   /// for the specified type when it is part of a call frame.
334   unsigned getCallFrameTypeAlignment(Type *Ty) const;
335 
336   /// getPrefTypeAlignment - Return the preferred stack/global alignment for
337   /// the specified type.  This is always at least as good as the ABI alignment.
338   unsigned getPrefTypeAlignment(Type *Ty) const;
339 
340   /// getPreferredTypeAlignmentShift - Return the preferred alignment for the
341   /// specified type, returned as log2 of the value (a shift amount).
342   unsigned getPreferredTypeAlignmentShift(Type *Ty) const;
343 
344   /// getIntPtrType - Return an integer type with size at least as big as that
345   /// of a pointer in the given address space.
346   IntegerType *getIntPtrType(LLVMContext &C, unsigned AddressSpace = 0) const;
347 
348   /// getIntPtrType - Return an integer (vector of integer) type with size at
349   /// least as big as that of a pointer of the given pointer (vector of pointer)
350   /// type.
351   Type *getIntPtrType(Type *) const;
352 
353   /// getIndexedOffset - return the offset from the beginning of the type for
354   /// the specified indices.  This is used to implement getelementptr.
355   uint64_t getIndexedOffset(Type *Ty, ArrayRef<Value *> Indices) const;
356 
357   /// getStructLayout - Return a StructLayout object, indicating the alignment
358   /// of the struct, its size, and the offsets of its fields.  Note that this
359   /// information is lazily cached.
360   const StructLayout *getStructLayout(StructType *Ty) const;
361 
362   /// getPreferredAlignment - Return the preferred alignment of the specified
363   /// global.  This includes an explicitly requested alignment (if the global
364   /// has one).
365   unsigned getPreferredAlignment(const GlobalVariable *GV) const;
366 
367   /// getPreferredAlignmentLog - Return the preferred alignment of the
368   /// specified global, returned in log form.  This includes an explicitly
369   /// requested alignment (if the global has one).
370   unsigned getPreferredAlignmentLog(const GlobalVariable *GV) const;
371 
372   /// RoundUpAlignment - Round the specified value up to the next alignment
373   /// boundary specified by Alignment.  For example, 7 rounded up to an
374   /// alignment boundary of 4 is 8.  8 rounded up to the alignment boundary of 4
375   /// is 8 because it is already aligned.
376   template <typename UIntTy>
RoundUpAlignment(UIntTy Val,unsigned Alignment)377   static UIntTy RoundUpAlignment(UIntTy Val, unsigned Alignment) {
378     assert((Alignment & (Alignment-1)) == 0 && "Alignment must be power of 2!");
379     return (Val + (Alignment-1)) & ~UIntTy(Alignment-1);
380   }
381 
382   static char ID; // Pass identification, replacement for typeid
383 };
384 
385 /// StructLayout - used to lazily calculate structure layout information for a
386 /// target machine, based on the DataLayout structure.
387 ///
388 class StructLayout {
389   uint64_t StructSize;
390   unsigned StructAlignment;
391   unsigned NumElements;
392   uint64_t MemberOffsets[1];  // variable sized array!
393 public:
394 
getSizeInBytes()395   uint64_t getSizeInBytes() const {
396     return StructSize;
397   }
398 
getSizeInBits()399   uint64_t getSizeInBits() const {
400     return 8*StructSize;
401   }
402 
getAlignment()403   unsigned getAlignment() const {
404     return StructAlignment;
405   }
406 
407   /// getElementContainingOffset - Given a valid byte offset into the structure,
408   /// return the structure index that contains it.
409   ///
410   unsigned getElementContainingOffset(uint64_t Offset) const;
411 
getElementOffset(unsigned Idx)412   uint64_t getElementOffset(unsigned Idx) const {
413     assert(Idx < NumElements && "Invalid element idx!");
414     return MemberOffsets[Idx];
415   }
416 
getElementOffsetInBits(unsigned Idx)417   uint64_t getElementOffsetInBits(unsigned Idx) const {
418     return getElementOffset(Idx)*8;
419   }
420 
421 private:
422   friend class DataLayout;   // Only DataLayout can create this class
423   StructLayout(StructType *ST, const DataLayout &TD);
424 };
425 
426 } // End llvm namespace
427 
428 #endif
429