Copy missing member in DataLayout copy ctor.
[oota-llvm.git] / include / llvm / IR / DataLayout.h
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.
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.
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().
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
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   /// Parse a data layout string (with fallback to default values). Ensure that
185   /// the data layout pass is registered.
186   void init(StringRef LayoutDescription);
187
188   /// Layout endianness...
189   bool isLittleEndian() const { return LittleEndian; }
190   bool isBigEndian() const { return !LittleEndian; }
191
192   /// getStringRepresentation - Return the string representation of the
193   /// DataLayout.  This representation is in the same format accepted by the
194   /// string constructor above.
195   std::string getStringRepresentation() const;
196
197   /// isLegalInteger - This function returns true if the specified type is
198   /// known to be a native integer type supported by the CPU.  For example,
199   /// i64 is not native on most 32-bit CPUs and i37 is not native on any known
200   /// one.  This returns false if the integer width is not legal.
201   ///
202   /// The width is specified in bits.
203   ///
204   bool isLegalInteger(unsigned Width) const {
205     for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
206       if (LegalIntWidths[i] == Width)
207         return true;
208     return false;
209   }
210
211   bool isIllegalInteger(unsigned Width) const {
212     return !isLegalInteger(Width);
213   }
214
215   /// Returns true if the given alignment exceeds the natural stack alignment.
216   bool exceedsNaturalStackAlignment(unsigned Align) const {
217     return (StackNaturalAlign != 0) && (Align > StackNaturalAlign);
218   }
219
220   /// fitsInLegalInteger - This function returns true if the specified type fits
221   /// in a native integer type supported by the CPU.  For example, if the CPU
222   /// only supports i32 as a native integer type, then i27 fits in a legal
223   // integer type but i45 does not.
224   bool fitsInLegalInteger(unsigned Width) const {
225     for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
226       if (Width <= LegalIntWidths[i])
227         return true;
228     return false;
229   }
230
231   /// Layout pointer alignment
232   /// FIXME: The defaults need to be removed once all of
233   /// the backends/clients are updated.
234   unsigned getPointerABIAlignment(unsigned AS = 0)  const {
235     DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
236     if (val == Pointers.end()) {
237       val = Pointers.find(0);
238     }
239     return val->second.ABIAlign;
240   }
241   /// Return target's alignment for stack-based pointers
242   /// FIXME: The defaults need to be removed once all of
243   /// the backends/clients are updated.
244   unsigned getPointerPrefAlignment(unsigned AS = 0) const {
245     DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
246     if (val == Pointers.end()) {
247       val = Pointers.find(0);
248     }
249     return val->second.PrefAlign;
250   }
251   /// Layout pointer size
252   /// FIXME: The defaults need to be removed once all of
253   /// the backends/clients are updated.
254   unsigned getPointerSize(unsigned AS = 0)          const {
255     DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
256     if (val == Pointers.end()) {
257       val = Pointers.find(0);
258     }
259     return val->second.TypeBitWidth;
260   }
261   /// Layout pointer size, in bits
262   /// FIXME: The defaults need to be removed once all of
263   /// the backends/clients are updated.
264   unsigned getPointerSizeInBits(unsigned AS = 0)    const {
265     return getPointerSize(AS) * 8;
266   }
267   /// Size examples:
268   ///
269   /// Type        SizeInBits  StoreSizeInBits  AllocSizeInBits[*]
270   /// ----        ----------  ---------------  ---------------
271   ///  i1            1           8                8
272   ///  i8            8           8                8
273   ///  i19          19          24               32
274   ///  i32          32          32               32
275   ///  i100        100         104              128
276   ///  i128        128         128              128
277   ///  Float        32          32               32
278   ///  Double       64          64               64
279   ///  X86_FP80     80          80               96
280   ///
281   /// [*] The alloc size depends on the alignment, and thus on the target.
282   ///     These values are for x86-32 linux.
283
284   /// getTypeSizeInBits - Return the number of bits necessary to hold the
285   /// specified type.  For example, returns 36 for i36 and 80 for x86_fp80.
286   /// The type passed must have a size (Type::isSized() must return true).
287   uint64_t getTypeSizeInBits(Type* Ty) const;
288
289   /// getTypeStoreSize - Return the maximum number of bytes that may be
290   /// overwritten by storing the specified type.  For example, returns 5
291   /// for i36 and 10 for x86_fp80.
292   uint64_t getTypeStoreSize(Type *Ty) const {
293     return (getTypeSizeInBits(Ty)+7)/8;
294   }
295
296   /// getTypeStoreSizeInBits - Return the maximum number of bits that may be
297   /// overwritten by storing the specified type; always a multiple of 8.  For
298   /// example, returns 40 for i36 and 80 for x86_fp80.
299   uint64_t getTypeStoreSizeInBits(Type *Ty) const {
300     return 8*getTypeStoreSize(Ty);
301   }
302
303   /// getTypeAllocSize - Return the offset in bytes between successive objects
304   /// of the specified type, including alignment padding.  This is the amount
305   /// that alloca reserves for this type.  For example, returns 12 or 16 for
306   /// x86_fp80, depending on alignment.
307   uint64_t getTypeAllocSize(Type* Ty) const {
308     // Round up to the next alignment boundary.
309     return RoundUpAlignment(getTypeStoreSize(Ty), getABITypeAlignment(Ty));
310   }
311
312   /// getTypeAllocSizeInBits - Return the offset in bits between successive
313   /// objects of the specified type, including alignment padding; always a
314   /// multiple of 8.  This is the amount that alloca reserves for this type.
315   /// For example, returns 96 or 128 for x86_fp80, depending on alignment.
316   uint64_t getTypeAllocSizeInBits(Type* Ty) const {
317     return 8*getTypeAllocSize(Ty);
318   }
319
320   /// getABITypeAlignment - Return the minimum ABI-required alignment for the
321   /// specified type.
322   unsigned getABITypeAlignment(Type *Ty) const;
323
324   /// getABIIntegerTypeAlignment - Return the minimum ABI-required alignment for
325   /// an integer type of the specified bitwidth.
326   unsigned getABIIntegerTypeAlignment(unsigned BitWidth) const;
327
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;
331
332   /// getPrefTypeAlignment - Return the preferred stack/global alignment for
333   /// the specified type.  This is always at least as good as the ABI alignment.
334   unsigned getPrefTypeAlignment(Type *Ty) const;
335
336   /// getPreferredTypeAlignmentShift - Return the preferred alignment for the
337   /// specified type, returned as log2 of the value (a shift amount).
338   unsigned getPreferredTypeAlignmentShift(Type *Ty) const;
339
340   /// getIntPtrType - Return an integer type with size at least as big as that
341   /// of a pointer in the given address space.
342   IntegerType *getIntPtrType(LLVMContext &C, unsigned AddressSpace = 0) const;
343
344   /// getIntPtrType - Return an integer (vector of integer) type with size at
345   /// least as big as that of a pointer of the given pointer (vector of pointer)
346   /// type.
347   Type *getIntPtrType(Type *) const;
348
349   /// getIndexedOffset - return the offset from the beginning of the type for
350   /// the specified indices.  This is used to implement getelementptr.
351   uint64_t getIndexedOffset(Type *Ty, ArrayRef<Value *> Indices) const;
352
353   /// getStructLayout - Return a StructLayout object, indicating the alignment
354   /// of the struct, its size, and the offsets of its fields.  Note that this
355   /// information is lazily cached.
356   const StructLayout *getStructLayout(StructType *Ty) const;
357
358   /// getPreferredAlignment - Return the preferred alignment of the specified
359   /// global.  This includes an explicitly requested alignment (if the global
360   /// has one).
361   unsigned getPreferredAlignment(const GlobalVariable *GV) const;
362
363   /// getPreferredAlignmentLog - Return the preferred alignment of the
364   /// specified global, returned in log form.  This includes an explicitly
365   /// requested alignment (if the global has one).
366   unsigned getPreferredAlignmentLog(const GlobalVariable *GV) const;
367
368   /// RoundUpAlignment - Round the specified value up to the next alignment
369   /// boundary specified by Alignment.  For example, 7 rounded up to an
370   /// alignment boundary of 4 is 8.  8 rounded up to the alignment boundary of 4
371   /// is 8 because it is already aligned.
372   template <typename UIntTy>
373   static UIntTy RoundUpAlignment(UIntTy Val, unsigned Alignment) {
374     assert((Alignment & (Alignment-1)) == 0 && "Alignment must be power of 2!");
375     return (Val + (Alignment-1)) & ~UIntTy(Alignment-1);
376   }
377
378   static char ID; // Pass identification, replacement for typeid
379 };
380
381 /// StructLayout - used to lazily calculate structure layout information for a
382 /// target machine, based on the DataLayout structure.
383 ///
384 class StructLayout {
385   uint64_t StructSize;
386   unsigned StructAlignment;
387   unsigned NumElements;
388   uint64_t MemberOffsets[1];  // variable sized array!
389 public:
390
391   uint64_t getSizeInBytes() const {
392     return StructSize;
393   }
394
395   uint64_t getSizeInBits() const {
396     return 8*StructSize;
397   }
398
399   unsigned getAlignment() const {
400     return StructAlignment;
401   }
402
403   /// getElementContainingOffset - Given a valid byte offset into the structure,
404   /// return the structure index that contains it.
405   ///
406   unsigned getElementContainingOffset(uint64_t Offset) const;
407
408   uint64_t getElementOffset(unsigned Idx) const {
409     assert(Idx < NumElements && "Invalid element idx!");
410     return MemberOffsets[Idx];
411   }
412
413   uint64_t getElementOffsetInBits(unsigned Idx) const {
414     return getElementOffset(Idx)*8;
415   }
416
417 private:
418   friend class DataLayout;   // Only DataLayout can create this class
419   StructLayout(StructType *ST, const DataLayout &TD);
420 };
421
422 } // End llvm namespace
423
424 #endif