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