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