Add some examples to show the difference between
[oota-llvm.git] / include / llvm / Target / TargetData.h
1 //===-- llvm/Target/TargetData.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 target 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_TARGET_TARGETDATA_H
21 #define LLVM_TARGET_TARGETDATA_H
22
23 #include "llvm/Pass.h"
24 #include "llvm/Support/DataTypes.h"
25 #include "llvm/ADT/SmallVector.h"
26 #include <string>
27
28 namespace llvm {
29
30 class Value;
31 class Type;
32 class StructType;
33 class StructLayout;
34 class GlobalVariable;
35
36 /// Enum used to categorize the alignment types stored by TargetAlignElem
37 enum AlignTypeEnum {
38   INTEGER_ALIGN = 'i',               ///< Integer type alignment
39   VECTOR_ALIGN = 'v',                ///< Vector type alignment
40   FLOAT_ALIGN = 'f',                 ///< Floating point type alignment
41   AGGREGATE_ALIGN = 'a',             ///< Aggregate alignment
42   STACK_ALIGN = 's'                  ///< Stack objects alignment
43 };
44 /// Target alignment element.
45 ///
46 /// Stores the alignment data associated with a given alignment type (pointer,
47 /// integer, vector, float) and type bit width.
48 ///
49 /// @note The unusual order of elements in the structure attempts to reduce
50 /// padding and make the structure slightly more cache friendly.
51 struct TargetAlignElem {
52   AlignTypeEnum       AlignType : 8;  //< Alignment type (AlignTypeEnum)
53   unsigned char       ABIAlign;       //< ABI alignment for this type/bitw
54   unsigned char       PrefAlign;      //< Pref. alignment for this type/bitw
55   uint32_t            TypeBitWidth;   //< Type bit width
56
57   /// Initializer
58   static TargetAlignElem get(AlignTypeEnum align_type, unsigned char abi_align,
59                              unsigned char pref_align, uint32_t bit_width);
60   /// Equality predicate
61   bool operator==(const TargetAlignElem &rhs) const;
62   /// output stream operator
63   std::ostream &dump(std::ostream &os) const;
64 };
65
66 class TargetData : public ImmutablePass {
67 private:
68   bool          LittleEndian;          ///< Defaults to false
69   unsigned char PointerMemSize;        ///< Pointer size in bytes
70   unsigned char PointerABIAlign;       ///< Pointer ABI alignment
71   unsigned char PointerPrefAlign;      ///< Pointer preferred alignment
72
73   //! Where the primitive type alignment data is stored.
74   /*!
75    @sa init().
76    @note Could support multiple size pointer alignments, e.g., 32-bit pointers
77    vs. 64-bit pointers by extending TargetAlignment, but for now, we don't.
78    */
79   SmallVector<TargetAlignElem, 16> Alignments;
80   //! Alignment iterator shorthand
81   typedef SmallVector<TargetAlignElem, 16>::iterator align_iterator;
82   //! Constant alignment iterator shorthand
83   typedef SmallVector<TargetAlignElem, 16>::const_iterator align_const_iterator;
84   //! Invalid alignment.
85   /*!
86     This member is a signal that a requested alignment type and bit width were
87     not found in the SmallVector.
88    */
89   static const TargetAlignElem InvalidAlignmentElem;
90
91   //! Set/initialize target alignments
92   void setAlignment(AlignTypeEnum align_type, unsigned char abi_align,
93                     unsigned char pref_align, uint32_t bit_width);
94   unsigned getAlignmentInfo(AlignTypeEnum align_type, uint32_t bit_width,
95                             bool ABIAlign, const Type *Ty) const;
96   //! Internal helper method that returns requested alignment for type.
97   unsigned char getAlignment(const Type *Ty, bool abi_or_pref) const;
98
99   /// Valid alignment predicate.
100   ///
101   /// Predicate that tests a TargetAlignElem reference returned by get() against
102   /// InvalidAlignmentElem.
103   inline bool validAlignment(const TargetAlignElem &align) const {
104     return (&align != &InvalidAlignmentElem);
105   }
106
107 public:
108   /// Default ctor.
109   ///
110   /// @note This has to exist, because this is a pass, but it should never be
111   /// used.
112   TargetData() : ImmutablePass(&ID) {
113     assert(0 && "ERROR: Bad TargetData ctor used.  "
114            "Tool did not specify a TargetData to use?");
115     abort();
116   }
117
118   /// Constructs a TargetData from a specification string. See init().
119   explicit TargetData(const std::string &TargetDescription)
120     : ImmutablePass(&ID) {
121     init(TargetDescription);
122   }
123
124   /// Initialize target data from properties stored in the module.
125   explicit TargetData(const Module *M);
126
127   TargetData(const TargetData &TD) :
128     ImmutablePass(&ID),
129     LittleEndian(TD.isLittleEndian()),
130     PointerMemSize(TD.PointerMemSize),
131     PointerABIAlign(TD.PointerABIAlign),
132     PointerPrefAlign(TD.PointerPrefAlign),
133     Alignments(TD.Alignments)
134   { }
135
136   ~TargetData();  // Not virtual, do not subclass this class
137
138   //! Parse a target data layout string and initialize TargetData alignments.
139   void init(const std::string &TargetDescription);
140
141   /// Target endianness...
142   bool          isLittleEndian()       const { return     LittleEndian; }
143   bool          isBigEndian()          const { return    !LittleEndian; }
144
145   /// getStringRepresentation - Return the string representation of the
146   /// TargetData.  This representation is in the same format accepted by the
147   /// string constructor above.
148   std::string getStringRepresentation() const;
149   /// Target pointer alignment
150   unsigned char getPointerABIAlignment() const { return PointerABIAlign; }
151   /// Return target's alignment for stack-based pointers
152   unsigned char getPointerPrefAlignment() const { return PointerPrefAlign; }
153   /// Target pointer size
154   unsigned char getPointerSize()         const { return PointerMemSize; }
155   /// Target pointer size, in bits
156   unsigned char getPointerSizeInBits()   const { return 8*PointerMemSize; }
157
158   /// Size examples:
159   ///
160   /// Type        SizeInBits  StoreSizeInBits  PaddedSizeInBits[*]
161   /// ----        ----------  ---------------  ----------------
162   ///  i1            1           8                8
163   ///  i8            8           8                8
164   ///  i19          19          24               32
165   ///  i32          32          32               32
166   ///  i100        100         104              128
167   ///  i128        128         128              128
168   ///  Float        32          32               32
169   ///  Double       64          64               64
170   ///  X86_FP80     80          80               96
171   ///
172   /// [*] The padded size depends on the alignment, and thus on the target.
173   ///     These values are for x86-32 linux.
174
175   /// getTypeSizeInBits - Return the number of bits necessary to hold the
176   /// specified type.  For example, returns 36 for i36 and 80 for x86_fp80.
177   uint64_t getTypeSizeInBits(const Type* Ty) const;
178
179   /// getTypeStoreSize - Return the maximum number of bytes that may be
180   /// overwritten by storing the specified type.  For example, returns 5
181   /// for i36 and 10 for x86_fp80.
182   uint64_t getTypeStoreSize(const Type *Ty) const {
183     return (getTypeSizeInBits(Ty)+7)/8;
184   }
185
186   /// getTypeStoreSizeInBits - Return the maximum number of bits that may be
187   /// overwritten by storing the specified type; always a multiple of 8.  For
188   /// example, returns 40 for i36 and 80 for x86_fp80.
189   uint64_t getTypeStoreSizeInBits(const Type *Ty) const {
190     return 8*getTypeStoreSize(Ty);
191   }
192
193   /// getTypePaddedSize - Return the offset in bytes between successive objects
194   /// of the specified type, including alignment padding.  This is the amount
195   /// that alloca reserves for this type.  For example, returns 12 or 16 for
196   /// x86_fp80, depending on alignment.
197   uint64_t getTypePaddedSize(const Type* Ty) const {
198     // Round up to the next alignment boundary.
199     return RoundUpAlignment(getTypeStoreSize(Ty), getABITypeAlignment(Ty));
200   }
201
202   /// getTypePaddedSizeInBits - Return the offset in bits between successive
203   /// objects of the specified type, including alignment padding; always a
204   /// multiple of 8.  This is the amount that alloca reserves for this type.
205   /// For example, returns 96 or 128 for x86_fp80, depending on alignment.
206   uint64_t getTypePaddedSizeInBits(const Type* Ty) const {
207     return 8*getTypePaddedSize(Ty);
208   }
209
210   /// getABITypeAlignment - Return the minimum ABI-required alignment for the
211   /// specified type.
212   unsigned char getABITypeAlignment(const Type *Ty) const;
213
214   /// getCallFrameTypeAlignment - Return the minimum ABI-required alignment
215   /// for the specified type when it is part of a call frame.
216   unsigned char getCallFrameTypeAlignment(const Type *Ty) const;
217
218
219   /// getPrefTypeAlignment - Return the preferred stack/global alignment for
220   /// the specified type.  This is always at least as good as the ABI alignment.
221   unsigned char getPrefTypeAlignment(const Type *Ty) const;
222
223   /// getPreferredTypeAlignmentShift - Return the preferred alignment for the
224   /// specified type, returned as log2 of the value (a shift amount).
225   ///
226   unsigned char getPreferredTypeAlignmentShift(const Type *Ty) const;
227
228   /// getIntPtrType - Return an unsigned integer type that is the same size or
229   /// greater to the host pointer size.
230   ///
231   const Type *getIntPtrType() const;
232
233   /// getIndexedOffset - return the offset from the beginning of the type for
234   /// the specified indices.  This is used to implement getelementptr.
235   ///
236   uint64_t getIndexedOffset(const Type *Ty,
237                             Value* const* Indices, unsigned NumIndices) const;
238
239   /// getStructLayout - Return a StructLayout object, indicating the alignment
240   /// of the struct, its size, and the offsets of its fields.  Note that this
241   /// information is lazily cached.
242   const StructLayout *getStructLayout(const StructType *Ty) const;
243
244   /// InvalidateStructLayoutInfo - TargetData speculatively caches StructLayout
245   /// objects.  If a TargetData object is alive when types are being refined and
246   /// removed, this method must be called whenever a StructType is removed to
247   /// avoid a dangling pointer in this cache.
248   void InvalidateStructLayoutInfo(const StructType *Ty) const;
249
250   /// getPreferredAlignment - Return the preferred alignment of the specified
251   /// global.  This includes an explicitly requested alignment (if the global
252   /// has one).
253   unsigned getPreferredAlignment(const GlobalVariable *GV) const;
254
255   /// getPreferredAlignmentLog - Return the preferred alignment of the
256   /// specified global, returned in log form.  This includes an explicitly
257   /// requested alignment (if the global has one).
258   unsigned getPreferredAlignmentLog(const GlobalVariable *GV) const;
259
260   /// RoundUpAlignment - Round the specified value up to the next alignment
261   /// boundary specified by Alignment.  For example, 7 rounded up to an
262   /// alignment boundary of 4 is 8.  8 rounded up to the alignment boundary of 4
263   /// is 8 because it is already aligned.
264   template <typename UIntTy>
265   static UIntTy RoundUpAlignment(UIntTy Val, unsigned Alignment) {
266     assert((Alignment & (Alignment-1)) == 0 && "Alignment must be power of 2!");
267     return (Val + (Alignment-1)) & ~UIntTy(Alignment-1);
268   }
269   
270   static char ID; // Pass identification, replacement for typeid
271 };
272
273 /// StructLayout - used to lazily calculate structure layout information for a
274 /// target machine, based on the TargetData structure.
275 ///
276 class StructLayout {
277   uint64_t StructSize;
278   unsigned StructAlignment;
279   unsigned NumElements;
280   uint64_t MemberOffsets[1];  // variable sized array!
281 public:
282
283   uint64_t getSizeInBytes() const {
284     return StructSize;
285   }
286
287   uint64_t getSizeInBits() const {
288     return 8*StructSize;
289   }
290
291   unsigned getAlignment() const {
292     return StructAlignment;
293   }
294
295   /// getElementContainingOffset - Given a valid offset into the structure,
296   /// return the structure index that contains it.
297   ///
298   unsigned getElementContainingOffset(uint64_t Offset) const;
299
300   uint64_t getElementOffset(unsigned Idx) const {
301     assert(Idx < NumElements && "Invalid element idx!");
302     return MemberOffsets[Idx];
303   }
304
305   uint64_t getElementOffsetInBits(unsigned Idx) const {
306     return getElementOffset(Idx)*8;
307   }
308
309 private:
310   friend class TargetData;   // Only TargetData can create this class
311   StructLayout(const StructType *ST, const TargetData &TD);
312 };
313
314 } // End llvm namespace
315
316 #endif