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