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