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