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