Fix resetting the DataLayout in a Module.
[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/IR/DerivedTypes.h"
26 #include "llvm/IR/Type.h"
27 #include "llvm/Pass.h"
28 #include "llvm/Support/DataTypes.h"
29
30 namespace llvm {
31
32 class Value;
33 class Type;
34 class IntegerType;
35 class StructType;
36 class StructLayout;
37 class Triple;
38 class GlobalVariable;
39 class LLVMContext;
40 template<typename T>
41 class ArrayRef;
42
43 /// Enum used to categorize the alignment types stored by LayoutAlignElem
44 enum AlignTypeEnum {
45   INVALID_ALIGN = 0,                 ///< An invalid alignment
46   INTEGER_ALIGN = 'i',               ///< Integer type alignment
47   VECTOR_ALIGN = 'v',                ///< Vector type alignment
48   FLOAT_ALIGN = 'f',                 ///< Floating point type alignment
49   AGGREGATE_ALIGN = 'a'              ///< Aggregate alignment
50 };
51
52 /// Layout alignment element.
53 ///
54 /// Stores the alignment data associated with a given alignment type (integer,
55 /// vector, float) and type bit width.
56 ///
57 /// @note The unusual order of elements in the structure attempts to reduce
58 /// padding and make the structure slightly more cache friendly.
59 struct LayoutAlignElem {
60   unsigned AlignType    : 8;  ///< Alignment type (AlignTypeEnum)
61   unsigned TypeBitWidth : 24; ///< Type bit width
62   unsigned ABIAlign     : 16; ///< ABI alignment for this type/bitw
63   unsigned PrefAlign    : 16; ///< Pref. alignment for this type/bitw
64
65   /// Initializer
66   static LayoutAlignElem get(AlignTypeEnum align_type, unsigned abi_align,
67                              unsigned pref_align, uint32_t bit_width);
68   /// Equality predicate
69   bool operator==(const LayoutAlignElem &rhs) const;
70 };
71
72 /// Layout pointer alignment element.
73 ///
74 /// Stores the alignment data associated with a given pointer and address space.
75 ///
76 /// @note The unusual order of elements in the structure attempts to reduce
77 /// padding and make the structure slightly more cache friendly.
78 struct PointerAlignElem {
79   unsigned            ABIAlign;       ///< ABI alignment for this type/bitw
80   unsigned            PrefAlign;      ///< Pref. alignment for this type/bitw
81   uint32_t            TypeByteWidth;  ///< Type byte width
82   uint32_t            AddressSpace;   ///< Address space for the pointer type
83
84   /// Initializer
85   static PointerAlignElem get(uint32_t AddressSpace, unsigned ABIAlign,
86                              unsigned PrefAlign, uint32_t TypeByteWidth);
87   /// Equality predicate
88   bool operator==(const PointerAlignElem &rhs) const;
89 };
90
91 /// This class holds a parsed version of the target data layout string in a
92 /// module and provides methods for querying it. The target data layout string
93 /// is specified *by the target* - a frontend generating LLVM IR is required to
94 /// generate the right target data for the target being codegen'd to.
95 class DataLayout {
96 private:
97   bool          LittleEndian;          ///< Defaults to false
98   unsigned      StackNaturalAlign;     ///< Stack natural alignment
99
100   enum ManglingModeT {
101     MM_None,
102     MM_ELF,
103     MM_MachO,
104     MM_WINCOFF,
105     MM_Mips
106   };
107   ManglingModeT ManglingMode;
108
109   SmallVector<unsigned char, 8> LegalIntWidths; ///< Legal Integers.
110
111   /// Alignments - Where the primitive type alignment data is stored.
112   ///
113   /// @sa reset().
114   /// @note Could support multiple size pointer alignments, e.g., 32-bit
115   /// pointers vs. 64-bit pointers by extending LayoutAlignment, but for now,
116   /// we don't.
117   SmallVector<LayoutAlignElem, 16> Alignments;
118   DenseMap<unsigned, PointerAlignElem> Pointers;
119
120   /// InvalidAlignmentElem - This member is a signal that a requested alignment
121   /// type and bit width were not found in the SmallVector.
122   static const LayoutAlignElem InvalidAlignmentElem;
123
124   /// InvalidPointerElem - This member is a signal that a requested pointer
125   /// type and bit width were not found in the DenseSet.
126   static const PointerAlignElem InvalidPointerElem;
127
128   // The StructType -> StructLayout map.
129   mutable void *LayoutMap;
130
131   //! Set/initialize target alignments
132   void setAlignment(AlignTypeEnum align_type, unsigned abi_align,
133                     unsigned pref_align, uint32_t bit_width);
134   unsigned getAlignmentInfo(AlignTypeEnum align_type, uint32_t bit_width,
135                             bool ABIAlign, Type *Ty) const;
136
137   //! Set/initialize pointer alignments
138   void setPointerAlignment(uint32_t AddrSpace, unsigned ABIAlign,
139                            unsigned PrefAlign, uint32_t TypeByteWidth);
140
141   //! Internal helper method that returns requested alignment for type.
142   unsigned getAlignment(Type *Ty, bool abi_or_pref) const;
143
144   /// Valid alignment predicate.
145   ///
146   /// Predicate that tests a LayoutAlignElem reference returned by get() against
147   /// InvalidAlignmentElem.
148   bool validAlignment(const LayoutAlignElem &align) const {
149     return &align != &InvalidAlignmentElem;
150   }
151
152   /// Valid pointer predicate.
153   ///
154   /// Predicate that tests a PointerAlignElem reference returned by get() against
155   /// InvalidPointerElem.
156   bool validPointer(const PointerAlignElem &align) const {
157     return &align != &InvalidPointerElem;
158   }
159
160   /// Parses a target data specification string. Assert if the string is
161   /// malformed.
162   void parseSpecifier(StringRef LayoutDescription);
163
164   // Free all internal data structures.
165   void clear();
166
167 public:
168   /// Constructs a DataLayout from a specification string. See reset().
169   explicit DataLayout(StringRef LayoutDescription) : LayoutMap(0) {
170     reset(LayoutDescription);
171   }
172
173   /// Initialize target data from properties stored in the module.
174   explicit DataLayout(const Module *M);
175
176   DataLayout(const DataLayout &DL) : LayoutMap(0) { *this = DL; }
177
178   DataLayout &operator=(const DataLayout &DL) {
179     clear();
180     LittleEndian = DL.isLittleEndian();
181     StackNaturalAlign = DL.StackNaturalAlign;
182     ManglingMode = DL.ManglingMode;
183     LegalIntWidths = DL.LegalIntWidths;
184     Alignments = DL.Alignments;
185     Pointers = DL.Pointers;
186     return *this;
187   }
188
189   ~DataLayout();  // Not virtual, do not subclass this class
190
191   /// Parse a data layout string (with fallback to default values).
192   void reset(StringRef LayoutDescription);
193
194   /// Layout endianness...
195   bool isLittleEndian() const { return LittleEndian; }
196   bool isBigEndian() const { return !LittleEndian; }
197
198   /// getStringRepresentation - Return the string representation of the
199   /// DataLayout.  This representation is in the same format accepted by the
200   /// string constructor above.
201   std::string getStringRepresentation() const;
202
203   /// isLegalInteger - This function returns true if the specified type is
204   /// known to be a native integer type supported by the CPU.  For example,
205   /// i64 is not native on most 32-bit CPUs and i37 is not native on any known
206   /// one.  This returns false if the integer width is not legal.
207   ///
208   /// The width is specified in bits.
209   ///
210   bool isLegalInteger(unsigned Width) const {
211     for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
212       if (LegalIntWidths[i] == Width)
213         return true;
214     return false;
215   }
216
217   bool isIllegalInteger(unsigned Width) const {
218     return !isLegalInteger(Width);
219   }
220
221   /// Returns true if the given alignment exceeds the natural stack alignment.
222   bool exceedsNaturalStackAlignment(unsigned Align) const {
223     return (StackNaturalAlign != 0) && (Align > StackNaturalAlign);
224   }
225
226   bool hasMicrosoftFastStdCallMangling() const {
227     return ManglingMode == MM_WINCOFF;
228   }
229
230   bool hasLinkerPrivateGlobalPrefix() const {
231     return ManglingMode == MM_MachO;
232   }
233
234   const char *getLinkerPrivateGlobalPrefix() const {
235     if (ManglingMode == MM_MachO)
236       return "l";
237     return getPrivateGlobalPrefix();
238   }
239
240   char getGlobalPrefix() const {
241     switch (ManglingMode) {
242     case MM_None:
243     case MM_ELF:
244     case MM_Mips:
245       return '\0';
246     case MM_MachO:
247     case MM_WINCOFF:
248       return '_';
249     }
250     llvm_unreachable("invalid mangling mode");
251   }
252
253   const char *getPrivateGlobalPrefix() const {
254     switch (ManglingMode) {
255     case MM_None:
256       return "";
257     case MM_ELF:
258       return ".L";
259     case MM_Mips:
260       return "$";
261     case MM_MachO:
262     case MM_WINCOFF:
263       return "L";
264     }
265     llvm_unreachable("invalid mangling mode");
266   }
267
268   static const char *getManglingComponent(const Triple &T);
269
270   /// fitsInLegalInteger - This function returns true if the specified type fits
271   /// in a native integer type supported by the CPU.  For example, if the CPU
272   /// only supports i32 as a native integer type, then i27 fits in a legal
273   // integer type but i45 does not.
274   bool fitsInLegalInteger(unsigned Width) const {
275     for (unsigned i = 0, e = (unsigned)LegalIntWidths.size(); i != e; ++i)
276       if (Width <= LegalIntWidths[i])
277         return true;
278     return false;
279   }
280
281   /// Layout pointer alignment
282   /// FIXME: The defaults need to be removed once all of
283   /// the backends/clients are updated.
284   unsigned getPointerABIAlignment(unsigned AS = 0) const {
285     DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
286     if (val == Pointers.end()) {
287       val = Pointers.find(0);
288     }
289     return val->second.ABIAlign;
290   }
291
292   /// Return target's alignment for stack-based pointers
293   /// FIXME: The defaults need to be removed once all of
294   /// the backends/clients are updated.
295   unsigned getPointerPrefAlignment(unsigned AS = 0) const {
296     DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
297     if (val == Pointers.end()) {
298       val = Pointers.find(0);
299     }
300     return val->second.PrefAlign;
301   }
302   /// Layout pointer size
303   /// FIXME: The defaults need to be removed once all of
304   /// the backends/clients are updated.
305   unsigned getPointerSize(unsigned AS = 0) const {
306     DenseMap<unsigned, PointerAlignElem>::const_iterator val = Pointers.find(AS);
307     if (val == Pointers.end()) {
308       val = Pointers.find(0);
309     }
310     return val->second.TypeByteWidth;
311   }
312   /// Layout pointer size, in bits
313   /// FIXME: The defaults need to be removed once all of
314   /// the backends/clients are updated.
315   unsigned getPointerSizeInBits(unsigned AS = 0) const {
316     return getPointerSize(AS) * 8;
317   }
318
319   /// Layout pointer size, in bits, based on the type.  If this function is
320   /// called with a pointer type, then the type size of the pointer is returned.
321   /// If this function is called with a vector of pointers, then the type size
322   /// of the pointer is returned.  This should only be called with a pointer or
323   /// vector of pointers.
324   unsigned getPointerTypeSizeInBits(Type *) const;
325
326   unsigned getPointerTypeSize(Type *Ty) const {
327     return getPointerTypeSizeInBits(Ty) / 8;
328   }
329
330   /// Size examples:
331   ///
332   /// Type        SizeInBits  StoreSizeInBits  AllocSizeInBits[*]
333   /// ----        ----------  ---------------  ---------------
334   ///  i1            1           8                8
335   ///  i8            8           8                8
336   ///  i19          19          24               32
337   ///  i32          32          32               32
338   ///  i100        100         104              128
339   ///  i128        128         128              128
340   ///  Float        32          32               32
341   ///  Double       64          64               64
342   ///  X86_FP80     80          80               96
343   ///
344   /// [*] The alloc size depends on the alignment, and thus on the target.
345   ///     These values are for x86-32 linux.
346
347   /// getTypeSizeInBits - Return the number of bits necessary to hold the
348   /// specified type.  For example, returns 36 for i36 and 80 for x86_fp80.
349   /// The type passed must have a size (Type::isSized() must return true).
350   uint64_t getTypeSizeInBits(Type *Ty) const;
351
352   /// getTypeStoreSize - Return the maximum number of bytes that may be
353   /// overwritten by storing the specified type.  For example, returns 5
354   /// for i36 and 10 for x86_fp80.
355   uint64_t getTypeStoreSize(Type *Ty) const {
356     return (getTypeSizeInBits(Ty)+7)/8;
357   }
358
359   /// getTypeStoreSizeInBits - Return the maximum number of bits that may be
360   /// overwritten by storing the specified type; always a multiple of 8.  For
361   /// example, returns 40 for i36 and 80 for x86_fp80.
362   uint64_t getTypeStoreSizeInBits(Type *Ty) const {
363     return 8*getTypeStoreSize(Ty);
364   }
365
366   /// getTypeAllocSize - Return the offset in bytes between successive objects
367   /// of the specified type, including alignment padding.  This is the amount
368   /// that alloca reserves for this type.  For example, returns 12 or 16 for
369   /// x86_fp80, depending on alignment.
370   uint64_t getTypeAllocSize(Type *Ty) const {
371     // Round up to the next alignment boundary.
372     return RoundUpAlignment(getTypeStoreSize(Ty), getABITypeAlignment(Ty));
373   }
374
375   /// getTypeAllocSizeInBits - Return the offset in bits between successive
376   /// objects of the specified type, including alignment padding; always a
377   /// multiple of 8.  This is the amount that alloca reserves for this type.
378   /// For example, returns 96 or 128 for x86_fp80, depending on alignment.
379   uint64_t getTypeAllocSizeInBits(Type *Ty) const {
380     return 8*getTypeAllocSize(Ty);
381   }
382
383   /// getABITypeAlignment - Return the minimum ABI-required alignment for the
384   /// specified type.
385   unsigned getABITypeAlignment(Type *Ty) const;
386
387   /// getABIIntegerTypeAlignment - Return the minimum ABI-required alignment for
388   /// an integer type of the specified bitwidth.
389   unsigned getABIIntegerTypeAlignment(unsigned BitWidth) const;
390
391   /// getPrefTypeAlignment - Return the preferred stack/global alignment for
392   /// the specified type.  This is always at least as good as the ABI alignment.
393   unsigned getPrefTypeAlignment(Type *Ty) const;
394
395   /// getPreferredTypeAlignmentShift - Return the preferred alignment for the
396   /// specified type, returned as log2 of the value (a shift amount).
397   unsigned getPreferredTypeAlignmentShift(Type *Ty) const;
398
399   /// getIntPtrType - Return an integer type with size at least as big as that
400   /// of a pointer in the given address space.
401   IntegerType *getIntPtrType(LLVMContext &C, unsigned AddressSpace = 0) const;
402
403   /// getIntPtrType - Return an integer (vector of integer) type with size at
404   /// least as big as that of a pointer of the given pointer (vector of pointer)
405   /// type.
406   Type *getIntPtrType(Type *) const;
407
408   /// getSmallestLegalIntType - Return the smallest integer type with size at
409   /// least as big as Width bits.
410   Type *getSmallestLegalIntType(LLVMContext &C, unsigned Width = 0) const;
411
412   /// getLargestLegalIntType - Return the largest legal integer type, or null if
413   /// none are set.
414   Type *getLargestLegalIntType(LLVMContext &C) const {
415     unsigned LargestSize = getLargestLegalIntTypeSize();
416     return (LargestSize == 0) ? 0 : Type::getIntNTy(C, LargestSize);
417   }
418
419   /// getLargestLegalIntType - Return the size of largest legal integer type
420   /// size, or 0 if none are set.
421   unsigned getLargestLegalIntTypeSize() const;
422
423   /// getIndexedOffset - return the offset from the beginning of the type for
424   /// the specified indices.  This is used to implement getelementptr.
425   uint64_t getIndexedOffset(Type *Ty, ArrayRef<Value *> Indices) const;
426
427   /// getStructLayout - Return a StructLayout object, indicating the alignment
428   /// of the struct, its size, and the offsets of its fields.  Note that this
429   /// information is lazily cached.
430   const StructLayout *getStructLayout(StructType *Ty) const;
431
432   /// getPreferredAlignment - Return the preferred alignment of the specified
433   /// global.  This includes an explicitly requested alignment (if the global
434   /// has one).
435   unsigned getPreferredAlignment(const GlobalVariable *GV) const;
436
437   /// getPreferredAlignmentLog - Return the preferred alignment of the
438   /// specified global, returned in log form.  This includes an explicitly
439   /// requested alignment (if the global has one).
440   unsigned getPreferredAlignmentLog(const GlobalVariable *GV) const;
441
442   /// RoundUpAlignment - Round the specified value up to the next alignment
443   /// boundary specified by Alignment.  For example, 7 rounded up to an
444   /// alignment boundary of 4 is 8.  8 rounded up to the alignment boundary of 4
445   /// is 8 because it is already aligned.
446   template <typename UIntTy>
447   static UIntTy RoundUpAlignment(UIntTy Val, unsigned Alignment) {
448     assert((Alignment & (Alignment-1)) == 0 && "Alignment must be power of 2!");
449     return (Val + (Alignment-1)) & ~UIntTy(Alignment-1);
450   }
451 };
452
453 class DataLayoutPass : public ImmutablePass {
454   DataLayout DL;
455
456 public:
457   /// This has to exist, because this is a pass, but it should never be used.
458   DataLayoutPass();
459   ~DataLayoutPass();
460
461   const DataLayout &getDataLayout() const { return DL; }
462
463   explicit DataLayoutPass(const DataLayout &DL);
464
465   explicit DataLayoutPass(StringRef LayoutDescription);
466
467   explicit DataLayoutPass(const Module *M);
468
469   static char ID; // Pass identification, replacement for typeid
470 };
471
472 /// StructLayout - used to lazily calculate structure layout information for a
473 /// target machine, based on the DataLayout structure.
474 ///
475 class StructLayout {
476   uint64_t StructSize;
477   unsigned StructAlignment;
478   unsigned NumElements;
479   uint64_t MemberOffsets[1];  // variable sized array!
480 public:
481
482   uint64_t getSizeInBytes() const {
483     return StructSize;
484   }
485
486   uint64_t getSizeInBits() const {
487     return 8*StructSize;
488   }
489
490   unsigned getAlignment() const {
491     return StructAlignment;
492   }
493
494   /// getElementContainingOffset - Given a valid byte offset into the structure,
495   /// return the structure index that contains it.
496   ///
497   unsigned getElementContainingOffset(uint64_t Offset) const;
498
499   uint64_t getElementOffset(unsigned Idx) const {
500     assert(Idx < NumElements && "Invalid element idx!");
501     return MemberOffsets[Idx];
502   }
503
504   uint64_t getElementOffsetInBits(unsigned Idx) const {
505     return getElementOffset(Idx)*8;
506   }
507
508 private:
509   friend class DataLayout;   // Only DataLayout can create this class
510   StructLayout(StructType *ST, const DataLayout &DL);
511 };
512
513
514 // The implementation of this method is provided inline as it is particularly
515 // well suited to constant folding when called on a specific Type subclass.
516 inline uint64_t DataLayout::getTypeSizeInBits(Type *Ty) const {
517   assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
518   switch (Ty->getTypeID()) {
519   case Type::LabelTyID:
520     return getPointerSizeInBits(0);
521   case Type::PointerTyID:
522     return getPointerSizeInBits(Ty->getPointerAddressSpace());
523   case Type::ArrayTyID: {
524     ArrayType *ATy = cast<ArrayType>(Ty);
525     return ATy->getNumElements() *
526            getTypeAllocSizeInBits(ATy->getElementType());
527   }
528   case Type::StructTyID:
529     // Get the layout annotation... which is lazily created on demand.
530     return getStructLayout(cast<StructType>(Ty))->getSizeInBits();
531   case Type::IntegerTyID:
532     return Ty->getIntegerBitWidth();
533   case Type::HalfTyID:
534     return 16;
535   case Type::FloatTyID:
536     return 32;
537   case Type::DoubleTyID:
538   case Type::X86_MMXTyID:
539     return 64;
540   case Type::PPC_FP128TyID:
541   case Type::FP128TyID:
542     return 128;
543     // In memory objects this is always aligned to a higher boundary, but
544   // only 80 bits contain information.
545   case Type::X86_FP80TyID:
546     return 80;
547   case Type::VectorTyID: {
548     VectorType *VTy = cast<VectorType>(Ty);
549     return VTy->getNumElements() * getTypeSizeInBits(VTy->getElementType());
550   }
551   default:
552     llvm_unreachable("DataLayout::getTypeSizeInBits(): Unsupported type");
553   }
554 }
555
556 } // End llvm namespace
557
558 #endif