1 //===- DataLayout.cpp - Data size & alignment routines ---------------------==//
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.
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 #include "llvm/IR/DataLayout.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/StringRef.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/GetElementPtrTypeIterator.h"
26 #include "llvm/IR/GlobalVariable.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/Type.h"
29 #include "llvm/IR/Value.h"
30 #include "llvm/Support/Casting.h"
31 #include "llvm/Support/ErrorHandling.h"
32 #include "llvm/Support/MathExtras.h"
33 #include <algorithm>
34 #include <cassert>
35 #include <cstdint>
36 #include <cstdlib>
37 #include <tuple>
38 #include <utility>
39 
40 using namespace llvm;
41 
42 //===----------------------------------------------------------------------===//
43 // Support for StructLayout
44 //===----------------------------------------------------------------------===//
45 
46 StructLayout::StructLayout(StructType *ST, const DataLayout &DL) {
47   assert(!ST->isOpaque() && "Cannot get layout of opaque structs");
48   StructAlignment = 0;
49   StructSize = 0;
50   IsPadded = false;
51   NumElements = ST->getNumElements();
52 
53   // Loop over each of the elements, placing them in memory.
54   for (unsigned i = 0, e = NumElements; i != e; ++i) {
55     Type *Ty = ST->getElementType(i);
56     unsigned TyAlign = ST->isPacked() ? 1 : DL.getABITypeAlignment(Ty);
57 
58     // Add padding if necessary to align the data element properly.
59     if ((StructSize & (TyAlign-1)) != 0) {
60       IsPadded = true;
61       StructSize = alignTo(StructSize, TyAlign);
62     }
63 
64     // Keep track of maximum alignment constraint.
65     StructAlignment = std::max(TyAlign, StructAlignment);
66 
67     MemberOffsets[i] = StructSize;
68     StructSize += DL.getTypeAllocSize(Ty); // Consume space for this data item
69   }
70 
71   // Empty structures have alignment of 1 byte.
72   if (StructAlignment == 0) StructAlignment = 1;
73 
74   // Add padding to the end of the struct so that it could be put in an array
75   // and all array elements would be aligned correctly.
76   if ((StructSize & (StructAlignment-1)) != 0) {
77     IsPadded = true;
78     StructSize = alignTo(StructSize, StructAlignment);
79   }
80 }
81 
82 /// getElementContainingOffset - Given a valid offset into the structure,
83 /// return the structure index that contains it.
84 unsigned StructLayout::getElementContainingOffset(uint64_t Offset) const {
85   const uint64_t *SI =
86     std::upper_bound(&MemberOffsets[0], &MemberOffsets[NumElements], Offset);
87   assert(SI != &MemberOffsets[0] && "Offset not in structure type!");
88   --SI;
89   assert(*SI <= Offset && "upper_bound didn't work");
90   assert((SI == &MemberOffsets[0] || *(SI-1) <= Offset) &&
91          (SI+1 == &MemberOffsets[NumElements] || *(SI+1) > Offset) &&
92          "Upper bound didn't work!");
93 
94   // Multiple fields can have the same offset if any of them are zero sized.
95   // For example, in { i32, [0 x i32], i32 }, searching for offset 4 will stop
96   // at the i32 element, because it is the last element at that offset.  This is
97   // the right one to return, because anything after it will have a higher
98   // offset, implying that this element is non-empty.
99   return SI-&MemberOffsets[0];
100 }
101 
102 //===----------------------------------------------------------------------===//
103 // LayoutAlignElem, LayoutAlign support
104 //===----------------------------------------------------------------------===//
105 
106 LayoutAlignElem
107 LayoutAlignElem::get(AlignTypeEnum align_type, unsigned abi_align,
108                      unsigned pref_align, uint32_t bit_width) {
109   assert(abi_align <= pref_align && "Preferred alignment worse than ABI!");
110   LayoutAlignElem retval;
111   retval.AlignType = align_type;
112   retval.ABIAlign = abi_align;
113   retval.PrefAlign = pref_align;
114   retval.TypeBitWidth = bit_width;
115   return retval;
116 }
117 
118 bool
119 LayoutAlignElem::operator==(const LayoutAlignElem &rhs) const {
120   return (AlignType == rhs.AlignType
121           && ABIAlign == rhs.ABIAlign
122           && PrefAlign == rhs.PrefAlign
123           && TypeBitWidth == rhs.TypeBitWidth);
124 }
125 
126 //===----------------------------------------------------------------------===//
127 // PointerAlignElem, PointerAlign support
128 //===----------------------------------------------------------------------===//
129 
130 PointerAlignElem
131 PointerAlignElem::get(uint32_t AddressSpace, unsigned ABIAlign,
132                       unsigned PrefAlign, uint32_t TypeByteWidth,
133                       uint32_t IndexWidth) {
134   assert(ABIAlign <= PrefAlign && "Preferred alignment worse than ABI!");
135   PointerAlignElem retval;
136   retval.AddressSpace = AddressSpace;
137   retval.ABIAlign = ABIAlign;
138   retval.PrefAlign = PrefAlign;
139   retval.TypeByteWidth = TypeByteWidth;
140   retval.IndexWidth = IndexWidth;
141   return retval;
142 }
143 
144 bool
145 PointerAlignElem::operator==(const PointerAlignElem &rhs) const {
146   return (ABIAlign == rhs.ABIAlign
147           && AddressSpace == rhs.AddressSpace
148           && PrefAlign == rhs.PrefAlign
149           && TypeByteWidth == rhs.TypeByteWidth
150           && IndexWidth == rhs.IndexWidth);
151 }
152 
153 //===----------------------------------------------------------------------===//
154 //                       DataLayout Class Implementation
155 //===----------------------------------------------------------------------===//
156 
157 const char *DataLayout::getManglingComponent(const Triple &T) {
158   if (T.isOSBinFormatMachO())
159     return "-m:o";
160   if (T.isOSWindows() && T.isOSBinFormatCOFF())
161     return T.getArch() == Triple::x86 ? "-m:x" : "-m:w";
162   return "-m:e";
163 }
164 
165 static const LayoutAlignElem DefaultAlignments[] = {
166   { INTEGER_ALIGN, 1, 1, 1 },    // i1
167   { INTEGER_ALIGN, 8, 1, 1 },    // i8
168   { INTEGER_ALIGN, 16, 2, 2 },   // i16
169   { INTEGER_ALIGN, 32, 4, 4 },   // i32
170   { INTEGER_ALIGN, 64, 4, 8 },   // i64
171   { FLOAT_ALIGN, 16, 2, 2 },     // half
172   { FLOAT_ALIGN, 32, 4, 4 },     // float
173   { FLOAT_ALIGN, 64, 8, 8 },     // double
174   { FLOAT_ALIGN, 128, 16, 16 },  // ppcf128, quad, ...
175   { VECTOR_ALIGN, 64, 8, 8 },    // v2i32, v1i64, ...
176   { VECTOR_ALIGN, 128, 16, 16 }, // v16i8, v8i16, v4i32, ...
177   { AGGREGATE_ALIGN, 0, 0, 8 }   // struct
178 };
179 
180 void DataLayout::reset(StringRef Desc) {
181   clear();
182 
183   LayoutMap = nullptr;
184   BigEndian = false;
185   AllocaAddrSpace = 0;
186   StackNaturalAlign = 0;
187   ManglingMode = MM_None;
188   NonIntegralAddressSpaces.clear();
189 
190   // Default alignments
191   for (const LayoutAlignElem &E : DefaultAlignments) {
192     setAlignment((AlignTypeEnum)E.AlignType, E.ABIAlign, E.PrefAlign,
193                  E.TypeBitWidth);
194   }
195   setPointerAlignment(0, 8, 8, 8, 8);
196 
197   parseSpecifier(Desc);
198 }
199 
200 /// Checked version of split, to ensure mandatory subparts.
201 static std::pair<StringRef, StringRef> split(StringRef Str, char Separator) {
202   assert(!Str.empty() && "parse error, string can't be empty here");
203   std::pair<StringRef, StringRef> Split = Str.split(Separator);
204   if (Split.second.empty() && Split.first != Str)
205     report_fatal_error("Trailing separator in datalayout string");
206   if (!Split.second.empty() && Split.first.empty())
207     report_fatal_error("Expected token before separator in datalayout string");
208   return Split;
209 }
210 
211 /// Get an unsigned integer, including error checks.
212 static unsigned getInt(StringRef R) {
213   unsigned Result;
214   bool error = R.getAsInteger(10, Result); (void)error;
215   if (error)
216     report_fatal_error("not a number, or does not fit in an unsigned int");
217   return Result;
218 }
219 
220 /// Convert bits into bytes. Assert if not a byte width multiple.
221 static unsigned inBytes(unsigned Bits) {
222   if (Bits % 8)
223     report_fatal_error("number of bits must be a byte width multiple");
224   return Bits / 8;
225 }
226 
227 void DataLayout::parseSpecifier(StringRef Desc) {
228   StringRepresentation = Desc;
229   while (!Desc.empty()) {
230     // Split at '-'.
231     std::pair<StringRef, StringRef> Split = split(Desc, '-');
232     Desc = Split.second;
233 
234     // Split at ':'.
235     Split = split(Split.first, ':');
236 
237     // Aliases used below.
238     StringRef &Tok  = Split.first;  // Current token.
239     StringRef &Rest = Split.second; // The rest of the string.
240 
241     if (Tok == "ni") {
242       do {
243         Split = split(Rest, ':');
244         Rest = Split.second;
245         unsigned AS = getInt(Split.first);
246         if (AS == 0)
247           report_fatal_error("Address space 0 can never be non-integral");
248         NonIntegralAddressSpaces.push_back(AS);
249       } while (!Rest.empty());
250 
251       continue;
252     }
253 
254     char Specifier = Tok.front();
255     Tok = Tok.substr(1);
256 
257     switch (Specifier) {
258     case 's':
259       // Ignored for backward compatibility.
260       // FIXME: remove this on LLVM 4.0.
261       break;
262     case 'E':
263       BigEndian = true;
264       break;
265     case 'e':
266       BigEndian = false;
267       break;
268     case 'p': {
269       // Address space.
270       unsigned AddrSpace = Tok.empty() ? 0 : getInt(Tok);
271       if (!isUInt<24>(AddrSpace))
272         report_fatal_error("Invalid address space, must be a 24bit integer");
273 
274       // Size.
275       if (Rest.empty())
276         report_fatal_error(
277             "Missing size specification for pointer in datalayout string");
278       Split = split(Rest, ':');
279       unsigned PointerMemSize = inBytes(getInt(Tok));
280       if (!PointerMemSize)
281         report_fatal_error("Invalid pointer size of 0 bytes");
282 
283       // ABI alignment.
284       if (Rest.empty())
285         report_fatal_error(
286             "Missing alignment specification for pointer in datalayout string");
287       Split = split(Rest, ':');
288       unsigned PointerABIAlign = inBytes(getInt(Tok));
289       if (!isPowerOf2_64(PointerABIAlign))
290         report_fatal_error(
291             "Pointer ABI alignment must be a power of 2");
292 
293       // Size of index used in GEP for address calculation.
294       // The parameter is optional. By default it is equal to size of pointer.
295       unsigned IndexSize = PointerMemSize;
296 
297       // Preferred alignment.
298       unsigned PointerPrefAlign = PointerABIAlign;
299       if (!Rest.empty()) {
300         Split = split(Rest, ':');
301         PointerPrefAlign = inBytes(getInt(Tok));
302         if (!isPowerOf2_64(PointerPrefAlign))
303           report_fatal_error(
304             "Pointer preferred alignment must be a power of 2");
305 
306         // Now read the index. It is the second optional parameter here.
307         if (!Rest.empty()) {
308           Split = split(Rest, ':');
309           IndexSize = inBytes(getInt(Tok));
310           if (!IndexSize)
311             report_fatal_error("Invalid index size of 0 bytes");
312         }
313       }
314       setPointerAlignment(AddrSpace, PointerABIAlign, PointerPrefAlign,
315                           PointerMemSize, IndexSize);
316       break;
317     }
318     case 'i':
319     case 'v':
320     case 'f':
321     case 'a': {
322       AlignTypeEnum AlignType;
323       switch (Specifier) {
324       default: llvm_unreachable("Unexpected specifier!");
325       case 'i': AlignType = INTEGER_ALIGN; break;
326       case 'v': AlignType = VECTOR_ALIGN; break;
327       case 'f': AlignType = FLOAT_ALIGN; break;
328       case 'a': AlignType = AGGREGATE_ALIGN; break;
329       }
330 
331       // Bit size.
332       unsigned Size = Tok.empty() ? 0 : getInt(Tok);
333 
334       if (AlignType == AGGREGATE_ALIGN && Size != 0)
335         report_fatal_error(
336             "Sized aggregate specification in datalayout string");
337 
338       // ABI alignment.
339       if (Rest.empty())
340         report_fatal_error(
341             "Missing alignment specification in datalayout string");
342       Split = split(Rest, ':');
343       unsigned ABIAlign = inBytes(getInt(Tok));
344       if (AlignType != AGGREGATE_ALIGN && !ABIAlign)
345         report_fatal_error(
346             "ABI alignment specification must be >0 for non-aggregate types");
347 
348       // Preferred alignment.
349       unsigned PrefAlign = ABIAlign;
350       if (!Rest.empty()) {
351         Split = split(Rest, ':');
352         PrefAlign = inBytes(getInt(Tok));
353       }
354 
355       setAlignment(AlignType, ABIAlign, PrefAlign, Size);
356 
357       break;
358     }
359     case 'n':  // Native integer types.
360       while (true) {
361         unsigned Width = getInt(Tok);
362         if (Width == 0)
363           report_fatal_error(
364               "Zero width native integer type in datalayout string");
365         LegalIntWidths.push_back(Width);
366         if (Rest.empty())
367           break;
368         Split = split(Rest, ':');
369       }
370       break;
371     case 'S': { // Stack natural alignment.
372       StackNaturalAlign = inBytes(getInt(Tok));
373       break;
374     }
375     case 'A': { // Default stack/alloca address space.
376       AllocaAddrSpace = getInt(Tok);
377       if (!isUInt<24>(AllocaAddrSpace))
378         report_fatal_error("Invalid address space, must be a 24bit integer");
379       break;
380     }
381     case 'm':
382       if (!Tok.empty())
383         report_fatal_error("Unexpected trailing characters after mangling specifier in datalayout string");
384       if (Rest.empty())
385         report_fatal_error("Expected mangling specifier in datalayout string");
386       if (Rest.size() > 1)
387         report_fatal_error("Unknown mangling specifier in datalayout string");
388       switch(Rest[0]) {
389       default:
390         report_fatal_error("Unknown mangling in datalayout string");
391       case 'e':
392         ManglingMode = MM_ELF;
393         break;
394       case 'o':
395         ManglingMode = MM_MachO;
396         break;
397       case 'm':
398         ManglingMode = MM_Mips;
399         break;
400       case 'w':
401         ManglingMode = MM_WinCOFF;
402         break;
403       case 'x':
404         ManglingMode = MM_WinCOFFX86;
405         break;
406       }
407       break;
408     default:
409       report_fatal_error("Unknown specifier in datalayout string");
410       break;
411     }
412   }
413 }
414 
415 DataLayout::DataLayout(const Module *M) {
416   init(M);
417 }
418 
419 void DataLayout::init(const Module *M) { *this = M->getDataLayout(); }
420 
421 bool DataLayout::operator==(const DataLayout &Other) const {
422   bool Ret = BigEndian == Other.BigEndian &&
423              AllocaAddrSpace == Other.AllocaAddrSpace &&
424              StackNaturalAlign == Other.StackNaturalAlign &&
425              ManglingMode == Other.ManglingMode &&
426              LegalIntWidths == Other.LegalIntWidths &&
427              Alignments == Other.Alignments && Pointers == Other.Pointers;
428   // Note: getStringRepresentation() might differs, it is not canonicalized
429   return Ret;
430 }
431 
432 DataLayout::AlignmentsTy::iterator
433 DataLayout::findAlignmentLowerBound(AlignTypeEnum AlignType,
434                                     uint32_t BitWidth) {
435   auto Pair = std::make_pair((unsigned)AlignType, BitWidth);
436   return std::lower_bound(Alignments.begin(), Alignments.end(), Pair,
437                           [](const LayoutAlignElem &LHS,
438                              const std::pair<unsigned, uint32_t> &RHS) {
439                             return std::tie(LHS.AlignType, LHS.TypeBitWidth) <
440                                    std::tie(RHS.first, RHS.second);
441                           });
442 }
443 
444 void
445 DataLayout::setAlignment(AlignTypeEnum align_type, unsigned abi_align,
446                          unsigned pref_align, uint32_t bit_width) {
447   if (!isUInt<24>(bit_width))
448     report_fatal_error("Invalid bit width, must be a 24bit integer");
449   if (!isUInt<16>(abi_align))
450     report_fatal_error("Invalid ABI alignment, must be a 16bit integer");
451   if (!isUInt<16>(pref_align))
452     report_fatal_error("Invalid preferred alignment, must be a 16bit integer");
453   if (abi_align != 0 && !isPowerOf2_64(abi_align))
454     report_fatal_error("Invalid ABI alignment, must be a power of 2");
455   if (pref_align != 0 && !isPowerOf2_64(pref_align))
456     report_fatal_error("Invalid preferred alignment, must be a power of 2");
457 
458   if (pref_align < abi_align)
459     report_fatal_error(
460         "Preferred alignment cannot be less than the ABI alignment");
461 
462   AlignmentsTy::iterator I = findAlignmentLowerBound(align_type, bit_width);
463   if (I != Alignments.end() &&
464       I->AlignType == (unsigned)align_type && I->TypeBitWidth == bit_width) {
465     // Update the abi, preferred alignments.
466     I->ABIAlign = abi_align;
467     I->PrefAlign = pref_align;
468   } else {
469     // Insert before I to keep the vector sorted.
470     Alignments.insert(I, LayoutAlignElem::get(align_type, abi_align,
471                                               pref_align, bit_width));
472   }
473 }
474 
475 DataLayout::PointersTy::iterator
476 DataLayout::findPointerLowerBound(uint32_t AddressSpace) {
477   return std::lower_bound(Pointers.begin(), Pointers.end(), AddressSpace,
478                           [](const PointerAlignElem &A, uint32_t AddressSpace) {
479     return A.AddressSpace < AddressSpace;
480   });
481 }
482 
483 void DataLayout::setPointerAlignment(uint32_t AddrSpace, unsigned ABIAlign,
484                                      unsigned PrefAlign, uint32_t TypeByteWidth,
485                                      uint32_t IndexWidth) {
486   if (PrefAlign < ABIAlign)
487     report_fatal_error(
488         "Preferred alignment cannot be less than the ABI alignment");
489 
490   PointersTy::iterator I = findPointerLowerBound(AddrSpace);
491   if (I == Pointers.end() || I->AddressSpace != AddrSpace) {
492     Pointers.insert(I, PointerAlignElem::get(AddrSpace, ABIAlign, PrefAlign,
493                                              TypeByteWidth, IndexWidth));
494   } else {
495     I->ABIAlign = ABIAlign;
496     I->PrefAlign = PrefAlign;
497     I->TypeByteWidth = TypeByteWidth;
498     I->IndexWidth = IndexWidth;
499   }
500 }
501 
502 /// getAlignmentInfo - Return the alignment (either ABI if ABIInfo = true or
503 /// preferred if ABIInfo = false) the layout wants for the specified datatype.
504 unsigned DataLayout::getAlignmentInfo(AlignTypeEnum AlignType,
505                                       uint32_t BitWidth, bool ABIInfo,
506                                       Type *Ty) const {
507   AlignmentsTy::const_iterator I = findAlignmentLowerBound(AlignType, BitWidth);
508   // See if we found an exact match. Of if we are looking for an integer type,
509   // but don't have an exact match take the next largest integer. This is where
510   // the lower_bound will point to when it fails an exact match.
511   if (I != Alignments.end() && I->AlignType == (unsigned)AlignType &&
512       (I->TypeBitWidth == BitWidth || AlignType == INTEGER_ALIGN))
513     return ABIInfo ? I->ABIAlign : I->PrefAlign;
514 
515   if (AlignType == INTEGER_ALIGN) {
516     // If we didn't have a larger value try the largest value we have.
517     if (I != Alignments.begin()) {
518       --I; // Go to the previous entry and see if its an integer.
519       if (I->AlignType == INTEGER_ALIGN)
520         return ABIInfo ? I->ABIAlign : I->PrefAlign;
521     }
522   } else if (AlignType == VECTOR_ALIGN) {
523     // By default, use natural alignment for vector types. This is consistent
524     // with what clang and llvm-gcc do.
525     unsigned Align = getTypeAllocSize(cast<VectorType>(Ty)->getElementType());
526     Align *= cast<VectorType>(Ty)->getNumElements();
527     Align = PowerOf2Ceil(Align);
528     return Align;
529    }
530 
531   // If we still couldn't find a reasonable default alignment, fall back
532   // to a simple heuristic that the alignment is the first power of two
533   // greater-or-equal to the store size of the type.  This is a reasonable
534   // approximation of reality, and if the user wanted something less
535   // less conservative, they should have specified it explicitly in the data
536   // layout.
537   unsigned Align = getTypeStoreSize(Ty);
538   Align = PowerOf2Ceil(Align);
539   return Align;
540 }
541 
542 namespace {
543 
544 class StructLayoutMap {
545   using LayoutInfoTy = DenseMap<StructType*, StructLayout*>;
546   LayoutInfoTy LayoutInfo;
547 
548 public:
549   ~StructLayoutMap() {
550     // Remove any layouts.
551     for (const auto &I : LayoutInfo) {
552       StructLayout *Value = I.second;
553       Value->~StructLayout();
554       free(Value);
555     }
556   }
557 
558   StructLayout *&operator[](StructType *STy) {
559     return LayoutInfo[STy];
560   }
561 };
562 
563 } // end anonymous namespace
564 
565 void DataLayout::clear() {
566   LegalIntWidths.clear();
567   Alignments.clear();
568   Pointers.clear();
569   delete static_cast<StructLayoutMap *>(LayoutMap);
570   LayoutMap = nullptr;
571 }
572 
573 DataLayout::~DataLayout() {
574   clear();
575 }
576 
577 const StructLayout *DataLayout::getStructLayout(StructType *Ty) const {
578   if (!LayoutMap)
579     LayoutMap = new StructLayoutMap();
580 
581   StructLayoutMap *STM = static_cast<StructLayoutMap*>(LayoutMap);
582   StructLayout *&SL = (*STM)[Ty];
583   if (SL) return SL;
584 
585   // Otherwise, create the struct layout.  Because it is variable length, we
586   // malloc it, then use placement new.
587   int NumElts = Ty->getNumElements();
588   StructLayout *L =
589     (StructLayout *)malloc(sizeof(StructLayout)+(NumElts-1) * sizeof(uint64_t));
590   if (L == nullptr)
591     report_bad_alloc_error("Allocation of StructLayout elements failed.");
592 
593   // Set SL before calling StructLayout's ctor.  The ctor could cause other
594   // entries to be added to TheMap, invalidating our reference.
595   SL = L;
596 
597   new (L) StructLayout(Ty, *this);
598 
599   return L;
600 }
601 
602 unsigned DataLayout::getPointerABIAlignment(unsigned AS) const {
603   PointersTy::const_iterator I = findPointerLowerBound(AS);
604   if (I == Pointers.end() || I->AddressSpace != AS) {
605     I = findPointerLowerBound(0);
606     assert(I->AddressSpace == 0);
607   }
608   return I->ABIAlign;
609 }
610 
611 unsigned DataLayout::getPointerPrefAlignment(unsigned AS) const {
612   PointersTy::const_iterator I = findPointerLowerBound(AS);
613   if (I == Pointers.end() || I->AddressSpace != AS) {
614     I = findPointerLowerBound(0);
615     assert(I->AddressSpace == 0);
616   }
617   return I->PrefAlign;
618 }
619 
620 unsigned DataLayout::getPointerSize(unsigned AS) const {
621   PointersTy::const_iterator I = findPointerLowerBound(AS);
622   if (I == Pointers.end() || I->AddressSpace != AS) {
623     I = findPointerLowerBound(0);
624     assert(I->AddressSpace == 0);
625   }
626   return I->TypeByteWidth;
627 }
628 
629 unsigned DataLayout::getPointerTypeSizeInBits(Type *Ty) const {
630   assert(Ty->isPtrOrPtrVectorTy() &&
631          "This should only be called with a pointer or pointer vector type");
632   Ty = Ty->getScalarType();
633   return getPointerSizeInBits(cast<PointerType>(Ty)->getAddressSpace());
634 }
635 
636 unsigned DataLayout::getIndexSize(unsigned AS) const {
637   PointersTy::const_iterator I = findPointerLowerBound(AS);
638   if (I == Pointers.end() || I->AddressSpace != AS) {
639     I = findPointerLowerBound(0);
640     assert(I->AddressSpace == 0);
641   }
642   return I->IndexWidth;
643 }
644 
645 unsigned DataLayout::getIndexTypeSizeInBits(Type *Ty) const {
646   assert(Ty->isPtrOrPtrVectorTy() &&
647          "This should only be called with a pointer or pointer vector type");
648   Ty = Ty->getScalarType();
649   return getIndexSizeInBits(cast<PointerType>(Ty)->getAddressSpace());
650 }
651 
652 /*!
653   \param abi_or_pref Flag that determines which alignment is returned. true
654   returns the ABI alignment, false returns the preferred alignment.
655   \param Ty The underlying type for which alignment is determined.
656 
657   Get the ABI (\a abi_or_pref == true) or preferred alignment (\a abi_or_pref
658   == false) for the requested type \a Ty.
659  */
660 unsigned DataLayout::getAlignment(Type *Ty, bool abi_or_pref) const {
661   AlignTypeEnum AlignType;
662 
663   assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
664   switch (Ty->getTypeID()) {
665   // Early escape for the non-numeric types.
666   case Type::LabelTyID:
667     return (abi_or_pref
668             ? getPointerABIAlignment(0)
669             : getPointerPrefAlignment(0));
670   case Type::PointerTyID: {
671     unsigned AS = cast<PointerType>(Ty)->getAddressSpace();
672     return (abi_or_pref
673             ? getPointerABIAlignment(AS)
674             : getPointerPrefAlignment(AS));
675     }
676   case Type::ArrayTyID:
677     return getAlignment(cast<ArrayType>(Ty)->getElementType(), abi_or_pref);
678 
679   case Type::StructTyID: {
680     // Packed structure types always have an ABI alignment of one.
681     if (cast<StructType>(Ty)->isPacked() && abi_or_pref)
682       return 1;
683 
684     // Get the layout annotation... which is lazily created on demand.
685     const StructLayout *Layout = getStructLayout(cast<StructType>(Ty));
686     unsigned Align = getAlignmentInfo(AGGREGATE_ALIGN, 0, abi_or_pref, Ty);
687     return std::max(Align, Layout->getAlignment());
688   }
689   case Type::IntegerTyID:
690     AlignType = INTEGER_ALIGN;
691     break;
692   case Type::HalfTyID:
693   case Type::FloatTyID:
694   case Type::DoubleTyID:
695   // PPC_FP128TyID and FP128TyID have different data contents, but the
696   // same size and alignment, so they look the same here.
697   case Type::PPC_FP128TyID:
698   case Type::FP128TyID:
699   case Type::X86_FP80TyID:
700     AlignType = FLOAT_ALIGN;
701     break;
702   case Type::X86_MMXTyID:
703   case Type::VectorTyID:
704     AlignType = VECTOR_ALIGN;
705     break;
706   default:
707     llvm_unreachable("Bad type for getAlignment!!!");
708   }
709 
710   return getAlignmentInfo(AlignType, getTypeSizeInBits(Ty), abi_or_pref, Ty);
711 }
712 
713 unsigned DataLayout::getABITypeAlignment(Type *Ty) const {
714   return getAlignment(Ty, true);
715 }
716 
717 /// getABIIntegerTypeAlignment - Return the minimum ABI-required alignment for
718 /// an integer type of the specified bitwidth.
719 unsigned DataLayout::getABIIntegerTypeAlignment(unsigned BitWidth) const {
720   return getAlignmentInfo(INTEGER_ALIGN, BitWidth, true, nullptr);
721 }
722 
723 unsigned DataLayout::getPrefTypeAlignment(Type *Ty) const {
724   return getAlignment(Ty, false);
725 }
726 
727 unsigned DataLayout::getPreferredTypeAlignmentShift(Type *Ty) const {
728   unsigned Align = getPrefTypeAlignment(Ty);
729   assert(!(Align & (Align-1)) && "Alignment is not a power of two!");
730   return Log2_32(Align);
731 }
732 
733 IntegerType *DataLayout::getIntPtrType(LLVMContext &C,
734                                        unsigned AddressSpace) const {
735   return IntegerType::get(C, getIndexSizeInBits(AddressSpace));
736 }
737 
738 Type *DataLayout::getIntPtrType(Type *Ty) const {
739   assert(Ty->isPtrOrPtrVectorTy() &&
740          "Expected a pointer or pointer vector type.");
741   unsigned NumBits = getIndexTypeSizeInBits(Ty);
742   IntegerType *IntTy = IntegerType::get(Ty->getContext(), NumBits);
743   if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
744     return VectorType::get(IntTy, VecTy->getNumElements());
745   return IntTy;
746 }
747 
748 Type *DataLayout::getSmallestLegalIntType(LLVMContext &C, unsigned Width) const {
749   for (unsigned LegalIntWidth : LegalIntWidths)
750     if (Width <= LegalIntWidth)
751       return Type::getIntNTy(C, LegalIntWidth);
752   return nullptr;
753 }
754 
755 unsigned DataLayout::getLargestLegalIntTypeSizeInBits() const {
756   auto Max = std::max_element(LegalIntWidths.begin(), LegalIntWidths.end());
757   return Max != LegalIntWidths.end() ? *Max : 0;
758 }
759 
760 Type *DataLayout::getIndexType(Type *Ty) const {
761   assert(Ty->isPtrOrPtrVectorTy() &&
762          "Expected a pointer or pointer vector type.");
763   unsigned NumBits = getIndexTypeSizeInBits(Ty);
764   IntegerType *IntTy = IntegerType::get(Ty->getContext(), NumBits);
765   if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
766     return VectorType::get(IntTy, VecTy->getNumElements());
767   return IntTy;
768 }
769 
770 int64_t DataLayout::getIndexedOffsetInType(Type *ElemTy,
771                                            ArrayRef<Value *> Indices) const {
772   int64_t Result = 0;
773 
774   generic_gep_type_iterator<Value* const*>
775     GTI = gep_type_begin(ElemTy, Indices),
776     GTE = gep_type_end(ElemTy, Indices);
777   for (; GTI != GTE; ++GTI) {
778     Value *Idx = GTI.getOperand();
779     if (StructType *STy = GTI.getStructTypeOrNull()) {
780       assert(Idx->getType()->isIntegerTy(32) && "Illegal struct idx");
781       unsigned FieldNo = cast<ConstantInt>(Idx)->getZExtValue();
782 
783       // Get structure layout information...
784       const StructLayout *Layout = getStructLayout(STy);
785 
786       // Add in the offset, as calculated by the structure layout info...
787       Result += Layout->getElementOffset(FieldNo);
788     } else {
789       // Get the array index and the size of each array element.
790       if (int64_t arrayIdx = cast<ConstantInt>(Idx)->getSExtValue())
791         Result += arrayIdx * getTypeAllocSize(GTI.getIndexedType());
792     }
793   }
794 
795   return Result;
796 }
797 
798 /// getPreferredAlignment - Return the preferred alignment of the specified
799 /// global.  This includes an explicitly requested alignment (if the global
800 /// has one).
801 unsigned DataLayout::getPreferredAlignment(const GlobalVariable *GV) const {
802   Type *ElemType = GV->getValueType();
803   unsigned Alignment = getPrefTypeAlignment(ElemType);
804   unsigned GVAlignment = GV->getAlignment();
805   if (GVAlignment >= Alignment) {
806     Alignment = GVAlignment;
807   } else if (GVAlignment != 0) {
808     Alignment = std::max(GVAlignment, getABITypeAlignment(ElemType));
809   }
810 
811   if (GV->hasInitializer() && GVAlignment == 0) {
812     if (Alignment < 16) {
813       // If the global is not external, see if it is large.  If so, give it a
814       // larger alignment.
815       if (getTypeSizeInBits(ElemType) > 128)
816         Alignment = 16;    // 16-byte alignment.
817     }
818   }
819   return Alignment;
820 }
821 
822 /// getPreferredAlignmentLog - Return the preferred alignment of the
823 /// specified global, returned in log form.  This includes an explicitly
824 /// requested alignment (if the global has one).
825 unsigned DataLayout::getPreferredAlignmentLog(const GlobalVariable *GV) const {
826   return Log2_32(getPreferredAlignment(GV));
827 }
828