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