• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 //===- llvm/DataLayout.h - Data size & alignment info -----------*- C++ -*-===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file defines layout properties related to datatype size/offset/alignment
10 // information.  It uses lazy annotations to cache information about how
11 // structure types are laid out and used.
12 //
13 // This structure should be created once, filled in if the defaults are not
14 // correct and then passed around by const&.  None of the members functions
15 // require modification to the object.
16 //
17 //===----------------------------------------------------------------------===//
18 
19 #ifndef LLVM_IR_DATALAYOUT_H
20 #define LLVM_IR_DATALAYOUT_H
21 
22 #include "llvm/ADT/ArrayRef.h"
23 #include "llvm/ADT/STLExtras.h"
24 #include "llvm/ADT/SmallVector.h"
25 #include "llvm/ADT/StringRef.h"
26 #include "llvm/IR/DerivedTypes.h"
27 #include "llvm/IR/Type.h"
28 #include "llvm/Support/Casting.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/MathExtras.h"
31 #include "llvm/Support/Alignment.h"
32 #include "llvm/Support/TypeSize.h"
33 #include <cassert>
34 #include <cstdint>
35 #include <string>
36 
37 // This needs to be outside of the namespace, to avoid conflict with llvm-c
38 // decl.
39 using LLVMTargetDataRef = struct LLVMOpaqueTargetData *;
40 
41 namespace llvm {
42 
43 class GlobalVariable;
44 class LLVMContext;
45 class Module;
46 class StructLayout;
47 class Triple;
48 class Value;
49 
50 /// Enum used to categorize the alignment types stored by LayoutAlignElem
51 enum AlignTypeEnum {
52   INVALID_ALIGN = 0,
53   INTEGER_ALIGN = 'i',
54   VECTOR_ALIGN = 'v',
55   FLOAT_ALIGN = 'f',
56   AGGREGATE_ALIGN = 'a'
57 };
58 
59 // FIXME: Currently the DataLayout string carries a "preferred alignment"
60 // for types. As the DataLayout is module/global, this should likely be
61 // sunk down to an FTTI element that is queried rather than a global
62 // preference.
63 
64 /// Layout alignment element.
65 ///
66 /// Stores the alignment data associated with a given alignment type (integer,
67 /// vector, float) and type bit width.
68 ///
69 /// \note The unusual order of elements in the structure attempts to reduce
70 /// padding and make the structure slightly more cache friendly.
71 struct LayoutAlignElem {
72   /// Alignment type from \c AlignTypeEnum
73   unsigned AlignType : 8;
74   unsigned TypeBitWidth : 24;
75   Align ABIAlign;
76   Align PrefAlign;
77 
78   static LayoutAlignElem get(AlignTypeEnum align_type, Align abi_align,
79                              Align pref_align, uint32_t bit_width);
80 
81   bool operator==(const LayoutAlignElem &rhs) const;
82 };
83 
84 /// Layout pointer alignment element.
85 ///
86 /// Stores the alignment data associated with a given pointer and address space.
87 ///
88 /// \note The unusual order of elements in the structure attempts to reduce
89 /// padding and make the structure slightly more cache friendly.
90 struct PointerAlignElem {
91   Align ABIAlign;
92   Align PrefAlign;
93   uint32_t TypeByteWidth;
94   uint32_t AddressSpace;
95   uint32_t IndexWidth;
96 
97   /// Initializer
98   static PointerAlignElem get(uint32_t AddressSpace, Align ABIAlign,
99                               Align PrefAlign, uint32_t TypeByteWidth,
100                               uint32_t IndexWidth);
101 
102   bool operator==(const PointerAlignElem &rhs) const;
103 };
104 
105 /// A parsed version of the target data layout string in and methods for
106 /// querying it.
107 ///
108 /// The target data layout string is specified *by the target* - a frontend
109 /// generating LLVM IR is required to generate the right target data for the
110 /// target being codegen'd to.
111 class DataLayout {
112 public:
113   enum class FunctionPtrAlignType {
114     /// The function pointer alignment is independent of the function alignment.
115     Independent,
116     /// The function pointer alignment is a multiple of the function alignment.
117     MultipleOfFunctionAlign,
118   };
119 private:
120   /// Defaults to false.
121   bool BigEndian;
122 
123   unsigned AllocaAddrSpace;
124   MaybeAlign StackNaturalAlign;
125   unsigned ProgramAddrSpace;
126   unsigned DefaultGlobalsAddrSpace;
127 
128   MaybeAlign FunctionPtrAlign;
129   FunctionPtrAlignType TheFunctionPtrAlignType;
130 
131   enum ManglingModeT {
132     MM_None,
133     MM_ELF,
134     MM_MachO,
135     MM_WinCOFF,
136     MM_WinCOFFX86,
137     MM_Mips,
138     MM_XCOFF
139   };
140   ManglingModeT ManglingMode;
141 
142   SmallVector<unsigned char, 8> LegalIntWidths;
143 
144   /// Primitive type alignment data. This is sorted by type and bit
145   /// width during construction.
146   using AlignmentsTy = SmallVector<LayoutAlignElem, 16>;
147   AlignmentsTy Alignments;
148 
149   AlignmentsTy::const_iterator
findAlignmentLowerBound(AlignTypeEnum AlignType,uint32_t BitWidth)150   findAlignmentLowerBound(AlignTypeEnum AlignType, uint32_t BitWidth) const {
151     return const_cast<DataLayout *>(this)->findAlignmentLowerBound(AlignType,
152                                                                    BitWidth);
153   }
154 
155   AlignmentsTy::iterator
156   findAlignmentLowerBound(AlignTypeEnum AlignType, uint32_t BitWidth);
157 
158   /// The string representation used to create this DataLayout
159   std::string StringRepresentation;
160 
161   using PointersTy = SmallVector<PointerAlignElem, 8>;
162   PointersTy Pointers;
163 
164   const PointerAlignElem &getPointerAlignElem(uint32_t AddressSpace) const;
165 
166   // The StructType -> StructLayout map.
167   mutable void *LayoutMap = nullptr;
168 
169   /// Pointers in these address spaces are non-integral, and don't have a
170   /// well-defined bitwise representation.
171   SmallVector<unsigned, 8> NonIntegralAddressSpaces;
172 
173   /// Attempts to set the alignment of the given type. Returns an error
174   /// description on failure.
175   Error setAlignment(AlignTypeEnum align_type, Align abi_align,
176                      Align pref_align, uint32_t bit_width);
177 
178   /// Attempts to set the alignment of a pointer in the given address space.
179   /// Returns an error description on failure.
180   Error setPointerAlignment(uint32_t AddrSpace, Align ABIAlign, Align PrefAlign,
181                             uint32_t TypeByteWidth, uint32_t IndexWidth);
182 
183   /// Internal helper to get alignment for integer of given bitwidth.
184   Align getIntegerAlignment(uint32_t BitWidth, bool abi_or_pref) const;
185 
186   /// Internal helper method that returns requested alignment for type.
187   Align getAlignment(Type *Ty, bool abi_or_pref) const;
188 
189   /// Attempts to parse a target data specification string and reports an error
190   /// if the string is malformed.
191   Error parseSpecifier(StringRef Desc);
192 
193   // Free all internal data structures.
194   void clear();
195 
196 public:
197   /// Constructs a DataLayout from a specification string. See reset().
DataLayout(StringRef LayoutDescription)198   explicit DataLayout(StringRef LayoutDescription) {
199     reset(LayoutDescription);
200   }
201 
202   /// Initialize target data from properties stored in the module.
203   explicit DataLayout(const Module *M);
204 
DataLayout(const DataLayout & DL)205   DataLayout(const DataLayout &DL) { *this = DL; }
206 
207   ~DataLayout(); // Not virtual, do not subclass this class
208 
209   DataLayout &operator=(const DataLayout &DL) {
210     clear();
211     StringRepresentation = DL.StringRepresentation;
212     BigEndian = DL.isBigEndian();
213     AllocaAddrSpace = DL.AllocaAddrSpace;
214     StackNaturalAlign = DL.StackNaturalAlign;
215     FunctionPtrAlign = DL.FunctionPtrAlign;
216     TheFunctionPtrAlignType = DL.TheFunctionPtrAlignType;
217     ProgramAddrSpace = DL.ProgramAddrSpace;
218     DefaultGlobalsAddrSpace = DL.DefaultGlobalsAddrSpace;
219     ManglingMode = DL.ManglingMode;
220     LegalIntWidths = DL.LegalIntWidths;
221     Alignments = DL.Alignments;
222     Pointers = DL.Pointers;
223     NonIntegralAddressSpaces = DL.NonIntegralAddressSpaces;
224     return *this;
225   }
226 
227   bool operator==(const DataLayout &Other) const;
228   bool operator!=(const DataLayout &Other) const { return !(*this == Other); }
229 
230   void init(const Module *M);
231 
232   /// Parse a data layout string (with fallback to default values).
233   void reset(StringRef LayoutDescription);
234 
235   /// Parse a data layout string and return the layout. Return an error
236   /// description on failure.
237   static Expected<DataLayout> parse(StringRef LayoutDescription);
238 
239   /// Layout endianness...
isLittleEndian()240   bool isLittleEndian() const { return !BigEndian; }
isBigEndian()241   bool isBigEndian() const { return BigEndian; }
242 
243   /// Returns the string representation of the DataLayout.
244   ///
245   /// This representation is in the same format accepted by the string
246   /// constructor above. This should not be used to compare two DataLayout as
247   /// different string can represent the same layout.
getStringRepresentation()248   const std::string &getStringRepresentation() const {
249     return StringRepresentation;
250   }
251 
252   /// Test if the DataLayout was constructed from an empty string.
isDefault()253   bool isDefault() const { return StringRepresentation.empty(); }
254 
255   /// Returns true if the specified type is known to be a native integer
256   /// type supported by the CPU.
257   ///
258   /// For example, i64 is not native on most 32-bit CPUs and i37 is not native
259   /// on any known one. This returns false if the integer width is not legal.
260   ///
261   /// The width is specified in bits.
isLegalInteger(uint64_t Width)262   bool isLegalInteger(uint64_t Width) const {
263     for (unsigned LegalIntWidth : LegalIntWidths)
264       if (LegalIntWidth == Width)
265         return true;
266     return false;
267   }
268 
isIllegalInteger(uint64_t Width)269   bool isIllegalInteger(uint64_t Width) const { return !isLegalInteger(Width); }
270 
271   /// Returns true if the given alignment exceeds the natural stack alignment.
exceedsNaturalStackAlignment(Align Alignment)272   bool exceedsNaturalStackAlignment(Align Alignment) const {
273     return StackNaturalAlign && (Alignment > *StackNaturalAlign);
274   }
275 
getStackAlignment()276   Align getStackAlignment() const {
277     assert(StackNaturalAlign && "StackNaturalAlign must be defined");
278     return *StackNaturalAlign;
279   }
280 
getAllocaAddrSpace()281   unsigned getAllocaAddrSpace() const { return AllocaAddrSpace; }
282 
283   /// Returns the alignment of function pointers, which may or may not be
284   /// related to the alignment of functions.
285   /// \see getFunctionPtrAlignType
getFunctionPtrAlign()286   MaybeAlign getFunctionPtrAlign() const { return FunctionPtrAlign; }
287 
288   /// Return the type of function pointer alignment.
289   /// \see getFunctionPtrAlign
getFunctionPtrAlignType()290   FunctionPtrAlignType getFunctionPtrAlignType() const {
291     return TheFunctionPtrAlignType;
292   }
293 
getProgramAddressSpace()294   unsigned getProgramAddressSpace() const { return ProgramAddrSpace; }
getDefaultGlobalsAddressSpace()295   unsigned getDefaultGlobalsAddressSpace() const {
296     return DefaultGlobalsAddrSpace;
297   }
298 
hasMicrosoftFastStdCallMangling()299   bool hasMicrosoftFastStdCallMangling() const {
300     return ManglingMode == MM_WinCOFFX86;
301   }
302 
303   /// Returns true if symbols with leading question marks should not receive IR
304   /// mangling. True for Windows mangling modes.
doNotMangleLeadingQuestionMark()305   bool doNotMangleLeadingQuestionMark() const {
306     return ManglingMode == MM_WinCOFF || ManglingMode == MM_WinCOFFX86;
307   }
308 
hasLinkerPrivateGlobalPrefix()309   bool hasLinkerPrivateGlobalPrefix() const { return ManglingMode == MM_MachO; }
310 
getLinkerPrivateGlobalPrefix()311   StringRef getLinkerPrivateGlobalPrefix() const {
312     if (ManglingMode == MM_MachO)
313       return "l";
314     return "";
315   }
316 
getGlobalPrefix()317   char getGlobalPrefix() const {
318     switch (ManglingMode) {
319     case MM_None:
320     case MM_ELF:
321     case MM_Mips:
322     case MM_WinCOFF:
323     case MM_XCOFF:
324       return '\0';
325     case MM_MachO:
326     case MM_WinCOFFX86:
327       return '_';
328     }
329     llvm_unreachable("invalid mangling mode");
330   }
331 
getPrivateGlobalPrefix()332   StringRef getPrivateGlobalPrefix() const {
333     switch (ManglingMode) {
334     case MM_None:
335       return "";
336     case MM_ELF:
337     case MM_WinCOFF:
338       return ".L";
339     case MM_Mips:
340       return "$";
341     case MM_MachO:
342     case MM_WinCOFFX86:
343       return "L";
344     case MM_XCOFF:
345       return "L..";
346     }
347     llvm_unreachable("invalid mangling mode");
348   }
349 
350   static const char *getManglingComponent(const Triple &T);
351 
352   /// Returns true if the specified type fits in a native integer type
353   /// supported by the CPU.
354   ///
355   /// For example, if the CPU only supports i32 as a native integer type, then
356   /// i27 fits in a legal integer type but i45 does not.
fitsInLegalInteger(unsigned Width)357   bool fitsInLegalInteger(unsigned Width) const {
358     for (unsigned LegalIntWidth : LegalIntWidths)
359       if (Width <= LegalIntWidth)
360         return true;
361     return false;
362   }
363 
364   /// Layout pointer alignment
365   Align getPointerABIAlignment(unsigned AS) const;
366 
367   /// Return target's alignment for stack-based pointers
368   /// FIXME: The defaults need to be removed once all of
369   /// the backends/clients are updated.
370   Align getPointerPrefAlignment(unsigned AS = 0) const;
371 
372   /// Layout pointer size
373   /// FIXME: The defaults need to be removed once all of
374   /// the backends/clients are updated.
375   unsigned getPointerSize(unsigned AS = 0) const;
376 
377   /// Returns the maximum pointer size over all address spaces.
378   unsigned getMaxPointerSize() const;
379 
380   // Index size used for address calculation.
381   unsigned getIndexSize(unsigned AS) const;
382 
383   /// Return the address spaces containing non-integral pointers.  Pointers in
384   /// this address space don't have a well-defined bitwise representation.
getNonIntegralAddressSpaces()385   ArrayRef<unsigned> getNonIntegralAddressSpaces() const {
386     return NonIntegralAddressSpaces;
387   }
388 
isNonIntegralAddressSpace(unsigned AddrSpace)389   bool isNonIntegralAddressSpace(unsigned AddrSpace) const {
390     ArrayRef<unsigned> NonIntegralSpaces = getNonIntegralAddressSpaces();
391     return find(NonIntegralSpaces, AddrSpace) != NonIntegralSpaces.end();
392   }
393 
isNonIntegralPointerType(PointerType * PT)394   bool isNonIntegralPointerType(PointerType *PT) const {
395     return isNonIntegralAddressSpace(PT->getAddressSpace());
396   }
397 
isNonIntegralPointerType(Type * Ty)398   bool isNonIntegralPointerType(Type *Ty) const {
399     auto *PTy = dyn_cast<PointerType>(Ty);
400     return PTy && isNonIntegralPointerType(PTy);
401   }
402 
403   /// Layout pointer size, in bits
404   /// FIXME: The defaults need to be removed once all of
405   /// the backends/clients are updated.
406   unsigned getPointerSizeInBits(unsigned AS = 0) const {
407     return getPointerSize(AS) * 8;
408   }
409 
410   /// Returns the maximum pointer size over all address spaces.
getMaxPointerSizeInBits()411   unsigned getMaxPointerSizeInBits() const {
412     return getMaxPointerSize() * 8;
413   }
414 
415   /// Size in bits of index used for address calculation in getelementptr.
getIndexSizeInBits(unsigned AS)416   unsigned getIndexSizeInBits(unsigned AS) const {
417     return getIndexSize(AS) * 8;
418   }
419 
420   /// Layout pointer size, in bits, based on the type.  If this function is
421   /// called with a pointer type, then the type size of the pointer is returned.
422   /// If this function is called with a vector of pointers, then the type size
423   /// of the pointer is returned.  This should only be called with a pointer or
424   /// vector of pointers.
425   unsigned getPointerTypeSizeInBits(Type *) const;
426 
427   /// Layout size of the index used in GEP calculation.
428   /// The function should be called with pointer or vector of pointers type.
429   unsigned getIndexTypeSizeInBits(Type *Ty) const;
430 
getPointerTypeSize(Type * Ty)431   unsigned getPointerTypeSize(Type *Ty) const {
432     return getPointerTypeSizeInBits(Ty) / 8;
433   }
434 
435   /// Size examples:
436   ///
437   /// Type        SizeInBits  StoreSizeInBits  AllocSizeInBits[*]
438   /// ----        ----------  ---------------  ---------------
439   ///  i1            1           8                8
440   ///  i8            8           8                8
441   ///  i19          19          24               32
442   ///  i32          32          32               32
443   ///  i100        100         104              128
444   ///  i128        128         128              128
445   ///  Float        32          32               32
446   ///  Double       64          64               64
447   ///  X86_FP80     80          80               96
448   ///
449   /// [*] The alloc size depends on the alignment, and thus on the target.
450   ///     These values are for x86-32 linux.
451 
452   /// Returns the number of bits necessary to hold the specified type.
453   ///
454   /// If Ty is a scalable vector type, the scalable property will be set and
455   /// the runtime size will be a positive integer multiple of the base size.
456   ///
457   /// For example, returns 36 for i36 and 80 for x86_fp80. The type passed must
458   /// have a size (Type::isSized() must return true).
459   TypeSize getTypeSizeInBits(Type *Ty) const;
460 
461   /// Returns the maximum number of bytes that may be overwritten by
462   /// storing the specified type.
463   ///
464   /// If Ty is a scalable vector type, the scalable property will be set and
465   /// the runtime size will be a positive integer multiple of the base size.
466   ///
467   /// For example, returns 5 for i36 and 10 for x86_fp80.
getTypeStoreSize(Type * Ty)468   TypeSize getTypeStoreSize(Type *Ty) const {
469     TypeSize BaseSize = getTypeSizeInBits(Ty);
470     return { (BaseSize.getKnownMinSize() + 7) / 8, BaseSize.isScalable() };
471   }
472 
473   /// Returns the maximum number of bits that may be overwritten by
474   /// storing the specified type; always a multiple of 8.
475   ///
476   /// If Ty is a scalable vector type, the scalable property will be set and
477   /// the runtime size will be a positive integer multiple of the base size.
478   ///
479   /// For example, returns 40 for i36 and 80 for x86_fp80.
getTypeStoreSizeInBits(Type * Ty)480   TypeSize getTypeStoreSizeInBits(Type *Ty) const {
481     return 8 * getTypeStoreSize(Ty);
482   }
483 
484   /// Returns true if no extra padding bits are needed when storing the
485   /// specified type.
486   ///
487   /// For example, returns false for i19 that has a 24-bit store size.
typeSizeEqualsStoreSize(Type * Ty)488   bool typeSizeEqualsStoreSize(Type *Ty) const {
489     return getTypeSizeInBits(Ty) == getTypeStoreSizeInBits(Ty);
490   }
491 
492   /// Returns the offset in bytes between successive objects of the
493   /// specified type, including alignment padding.
494   ///
495   /// If Ty is a scalable vector type, the scalable property will be set and
496   /// the runtime size will be a positive integer multiple of the base size.
497   ///
498   /// This is the amount that alloca reserves for this type. For example,
499   /// returns 12 or 16 for x86_fp80, depending on alignment.
getTypeAllocSize(Type * Ty)500   TypeSize getTypeAllocSize(Type *Ty) const {
501     // Round up to the next alignment boundary.
502     return alignTo(getTypeStoreSize(Ty), getABITypeAlignment(Ty));
503   }
504 
505   /// Returns the offset in bits between successive objects of the
506   /// specified type, including alignment padding; always a multiple of 8.
507   ///
508   /// If Ty is a scalable vector type, the scalable property will be set and
509   /// the runtime size will be a positive integer multiple of the base size.
510   ///
511   /// This is the amount that alloca reserves for this type. For example,
512   /// returns 96 or 128 for x86_fp80, depending on alignment.
getTypeAllocSizeInBits(Type * Ty)513   TypeSize getTypeAllocSizeInBits(Type *Ty) const {
514     return 8 * getTypeAllocSize(Ty);
515   }
516 
517   /// Returns the minimum ABI-required alignment for the specified type.
518   /// FIXME: Deprecate this function once migration to Align is over.
519   unsigned getABITypeAlignment(Type *Ty) const;
520 
521   /// Returns the minimum ABI-required alignment for the specified type.
522   Align getABITypeAlign(Type *Ty) const;
523 
524   /// Helper function to return `Alignment` if it's set or the result of
525   /// `getABITypeAlignment(Ty)`, in any case the result is a valid alignment.
getValueOrABITypeAlignment(MaybeAlign Alignment,Type * Ty)526   inline Align getValueOrABITypeAlignment(MaybeAlign Alignment,
527                                           Type *Ty) const {
528     return Alignment ? *Alignment : getABITypeAlign(Ty);
529   }
530 
531   /// Returns the minimum ABI-required alignment for an integer type of
532   /// the specified bitwidth.
getABIIntegerTypeAlignment(unsigned BitWidth)533   Align getABIIntegerTypeAlignment(unsigned BitWidth) const {
534     return getIntegerAlignment(BitWidth, /* abi_or_pref */ true);
535   }
536 
537   /// Returns the preferred stack/global alignment for the specified
538   /// type.
539   ///
540   /// This is always at least as good as the ABI alignment.
541   /// FIXME: Deprecate this function once migration to Align is over.
542   unsigned getPrefTypeAlignment(Type *Ty) const;
543 
544   /// Returns the preferred stack/global alignment for the specified
545   /// type.
546   ///
547   /// This is always at least as good as the ABI alignment.
548   Align getPrefTypeAlign(Type *Ty) const;
549 
550   /// Returns an integer type with size at least as big as that of a
551   /// pointer in the given address space.
552   IntegerType *getIntPtrType(LLVMContext &C, unsigned AddressSpace = 0) const;
553 
554   /// Returns an integer (vector of integer) type with size at least as
555   /// big as that of a pointer of the given pointer (vector of pointer) type.
556   Type *getIntPtrType(Type *) const;
557 
558   /// Returns the smallest integer type with size at least as big as
559   /// Width bits.
560   Type *getSmallestLegalIntType(LLVMContext &C, unsigned Width = 0) const;
561 
562   /// Returns the largest legal integer type, or null if none are set.
getLargestLegalIntType(LLVMContext & C)563   Type *getLargestLegalIntType(LLVMContext &C) const {
564     unsigned LargestSize = getLargestLegalIntTypeSizeInBits();
565     return (LargestSize == 0) ? nullptr : Type::getIntNTy(C, LargestSize);
566   }
567 
568   /// Returns the size of largest legal integer type size, or 0 if none
569   /// are set.
570   unsigned getLargestLegalIntTypeSizeInBits() const;
571 
572   /// Returns the type of a GEP index.
573   /// If it was not specified explicitly, it will be the integer type of the
574   /// pointer width - IntPtrType.
575   Type *getIndexType(Type *PtrTy) const;
576 
577   /// Returns the offset from the beginning of the type for the specified
578   /// indices.
579   ///
580   /// Note that this takes the element type, not the pointer type.
581   /// This is used to implement getelementptr.
582   int64_t getIndexedOffsetInType(Type *ElemTy, ArrayRef<Value *> Indices) const;
583 
584   /// Returns a StructLayout object, indicating the alignment of the
585   /// struct, its size, and the offsets of its fields.
586   ///
587   /// Note that this information is lazily cached.
588   const StructLayout *getStructLayout(StructType *Ty) const;
589 
590   /// Returns the preferred alignment of the specified global.
591   ///
592   /// This includes an explicitly requested alignment (if the global has one).
593   Align getPreferredAlign(const GlobalVariable *GV) const;
594 
595   /// Returns the preferred alignment of the specified global.
596   ///
597   /// This includes an explicitly requested alignment (if the global has one).
598   LLVM_ATTRIBUTE_DEPRECATED(
getPreferredAlignment(const GlobalVariable * GV)599       inline unsigned getPreferredAlignment(const GlobalVariable *GV) const,
600       "Use getPreferredAlign instead") {
601     return getPreferredAlign(GV).value();
602   }
603 
604   /// Returns the preferred alignment of the specified global, returned
605   /// in log form.
606   ///
607   /// This includes an explicitly requested alignment (if the global has one).
608   LLVM_ATTRIBUTE_DEPRECATED(
getPreferredAlignmentLog(const GlobalVariable * GV)609       inline unsigned getPreferredAlignmentLog(const GlobalVariable *GV) const,
610       "Inline where needed") {
611     return Log2(getPreferredAlign(GV));
612   }
613 };
614 
unwrap(LLVMTargetDataRef P)615 inline DataLayout *unwrap(LLVMTargetDataRef P) {
616   return reinterpret_cast<DataLayout *>(P);
617 }
618 
wrap(const DataLayout * P)619 inline LLVMTargetDataRef wrap(const DataLayout *P) {
620   return reinterpret_cast<LLVMTargetDataRef>(const_cast<DataLayout *>(P));
621 }
622 
623 /// Used to lazily calculate structure layout information for a target machine,
624 /// based on the DataLayout structure.
625 class StructLayout {
626   uint64_t StructSize;
627   Align StructAlignment;
628   unsigned IsPadded : 1;
629   unsigned NumElements : 31;
630   uint64_t MemberOffsets[1]; // variable sized array!
631 
632 public:
getSizeInBytes()633   uint64_t getSizeInBytes() const { return StructSize; }
634 
getSizeInBits()635   uint64_t getSizeInBits() const { return 8 * StructSize; }
636 
getAlignment()637   Align getAlignment() const { return StructAlignment; }
638 
639   /// Returns whether the struct has padding or not between its fields.
640   /// NB: Padding in nested element is not taken into account.
hasPadding()641   bool hasPadding() const { return IsPadded; }
642 
643   /// Given a valid byte offset into the structure, returns the structure
644   /// index that contains it.
645   unsigned getElementContainingOffset(uint64_t Offset) const;
646 
getElementOffset(unsigned Idx)647   uint64_t getElementOffset(unsigned Idx) const {
648     assert(Idx < NumElements && "Invalid element idx!");
649     return MemberOffsets[Idx];
650   }
651 
getElementOffsetInBits(unsigned Idx)652   uint64_t getElementOffsetInBits(unsigned Idx) const {
653     return getElementOffset(Idx) * 8;
654   }
655 
656 private:
657   friend class DataLayout; // Only DataLayout can create this class
658 
659   StructLayout(StructType *ST, const DataLayout &DL);
660 };
661 
662 // The implementation of this method is provided inline as it is particularly
663 // well suited to constant folding when called on a specific Type subclass.
getTypeSizeInBits(Type * Ty)664 inline TypeSize DataLayout::getTypeSizeInBits(Type *Ty) const {
665   assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
666   switch (Ty->getTypeID()) {
667   case Type::LabelTyID:
668     return TypeSize::Fixed(getPointerSizeInBits(0));
669   case Type::PointerTyID:
670     return TypeSize::Fixed(getPointerSizeInBits(Ty->getPointerAddressSpace()));
671   case Type::ArrayTyID: {
672     ArrayType *ATy = cast<ArrayType>(Ty);
673     return ATy->getNumElements() *
674            getTypeAllocSizeInBits(ATy->getElementType());
675   }
676   case Type::StructTyID:
677     // Get the layout annotation... which is lazily created on demand.
678     return TypeSize::Fixed(
679                         getStructLayout(cast<StructType>(Ty))->getSizeInBits());
680   case Type::IntegerTyID:
681     return TypeSize::Fixed(Ty->getIntegerBitWidth());
682   case Type::HalfTyID:
683   case Type::BFloatTyID:
684     return TypeSize::Fixed(16);
685   case Type::FloatTyID:
686     return TypeSize::Fixed(32);
687   case Type::DoubleTyID:
688   case Type::X86_MMXTyID:
689     return TypeSize::Fixed(64);
690   case Type::PPC_FP128TyID:
691   case Type::FP128TyID:
692     return TypeSize::Fixed(128);
693   // In memory objects this is always aligned to a higher boundary, but
694   // only 80 bits contain information.
695   case Type::X86_FP80TyID:
696     return TypeSize::Fixed(80);
697   case Type::FixedVectorTyID:
698   case Type::ScalableVectorTyID: {
699     VectorType *VTy = cast<VectorType>(Ty);
700     auto EltCnt = VTy->getElementCount();
701     uint64_t MinBits = EltCnt.getKnownMinValue() *
702                        getTypeSizeInBits(VTy->getElementType()).getFixedSize();
703     return TypeSize(MinBits, EltCnt.isScalable());
704   }
705   default:
706     llvm_unreachable("DataLayout::getTypeSizeInBits(): Unsupported type");
707   }
708 }
709 
710 } // end namespace llvm
711 
712 #endif // LLVM_IR_DATALAYOUT_H
713