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