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