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