| 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(ExactSize: 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(N: i); |
| 57 | if (i == 0 && Ty->isScalableTy()) |
| 58 | StructSize = TypeSize::getScalable(MinimumSize: 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(Lhs: TyAlign, SizeInBytes: StructSize)) { |
| 70 | IsPadded = true; |
| 71 | StructSize = TypeSize::getFixed(ExactSize: alignTo(Size: StructSize, A: TyAlign)); |
| 72 | } |
| 73 | |
| 74 | // Keep track of maximum alignment constraint. |
| 75 | StructAlignment = std::max(a: TyAlign, b: 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(Lhs: StructAlignment, SizeInBytes: StructSize)) { |
| 85 | IsPadded = true; |
| 86 | StructSize = TypeSize::getFixed(ExactSize: alignTo(Size: StructSize, A: 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(ExactSize: FixedOffset); |
| 97 | ArrayRef<TypeSize> MemberOffsets = getMemberOffsets(); |
| 98 | |
| 99 | const auto *SI = llvm::upper_bound(Range&: MemberOffsets, Value&: Offset, |
| 100 | C: [](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(ptr: 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 | HasUnstableRepresentation == Other.HasUnstableRepresentation && |
| 155 | HasExternalState == Other.HasExternalState && |
| 156 | AddrSpaceName == Other.AddrSpaceName; |
| 157 | } |
| 158 | |
| 159 | namespace { |
| 160 | /// Predicate to sort primitive specs by bit width. |
| 161 | struct LessPrimitiveBitWidth { |
| 162 | bool operator()(const DataLayout::PrimitiveSpec &LHS, |
| 163 | unsigned RHSBitWidth) const { |
| 164 | return LHS.BitWidth < RHSBitWidth; |
| 165 | } |
| 166 | }; |
| 167 | |
| 168 | /// Predicate to sort pointer specs by address space number. |
| 169 | struct LessPointerAddrSpace { |
| 170 | bool operator()(const DataLayout::PointerSpec &LHS, |
| 171 | unsigned RHSAddrSpace) const { |
| 172 | return LHS.AddrSpace < RHSAddrSpace; |
| 173 | } |
| 174 | }; |
| 175 | } // namespace |
| 176 | |
| 177 | // Default primitive type specifications. |
| 178 | // NOTE: These arrays must be sorted by type bit width. |
| 179 | constexpr DataLayout::PrimitiveSpec DefaultIntSpecs[] = { |
| 180 | {.BitWidth: 8, .ABIAlign: Align::Constant<1>(), .PrefAlign: Align::Constant<1>()}, // i8:8:8 |
| 181 | {.BitWidth: 16, .ABIAlign: Align::Constant<2>(), .PrefAlign: Align::Constant<2>()}, // i16:16:16 |
| 182 | {.BitWidth: 32, .ABIAlign: Align::Constant<4>(), .PrefAlign: Align::Constant<4>()}, // i32:32:32 |
| 183 | {.BitWidth: 64, .ABIAlign: Align::Constant<4>(), .PrefAlign: Align::Constant<8>()}, // i64:32:64 |
| 184 | }; |
| 185 | constexpr DataLayout::PrimitiveSpec DefaultFloatSpecs[] = { |
| 186 | {.BitWidth: 16, .ABIAlign: Align::Constant<2>(), .PrefAlign: Align::Constant<2>()}, // f16:16:16 |
| 187 | {.BitWidth: 32, .ABIAlign: Align::Constant<4>(), .PrefAlign: Align::Constant<4>()}, // f32:32:32 |
| 188 | {.BitWidth: 64, .ABIAlign: Align::Constant<8>(), .PrefAlign: Align::Constant<8>()}, // f64:64:64 |
| 189 | {.BitWidth: 128, .ABIAlign: Align::Constant<16>(), .PrefAlign: Align::Constant<16>()}, // f128:128:128 |
| 190 | }; |
| 191 | constexpr DataLayout::PrimitiveSpec DefaultVectorSpecs[] = { |
| 192 | {.BitWidth: 64, .ABIAlign: Align::Constant<8>(), .PrefAlign: Align::Constant<8>()}, // v64:64:64 |
| 193 | {.BitWidth: 128, .ABIAlign: Align::Constant<16>(), .PrefAlign: Align::Constant<16>()}, // v128:128:128 |
| 194 | }; |
| 195 | |
| 196 | DataLayout::DataLayout() |
| 197 | : IntSpecs(ArrayRef(DefaultIntSpecs)), |
| 198 | FloatSpecs(ArrayRef(DefaultFloatSpecs)), |
| 199 | VectorSpecs(ArrayRef(DefaultVectorSpecs)) { |
| 200 | // Default pointer type specifications. |
| 201 | setPointerSpec(AddrSpace: 0, BitWidth: 64, ABIAlign: Align::Constant<8>(), PrefAlign: Align::Constant<8>(), IndexBitWidth: 64, HasUnstableRepr: false, |
| 202 | HasExternalState: false, AddrSpaceName: "" ); |
| 203 | } |
| 204 | |
| 205 | DataLayout::DataLayout(StringRef LayoutString) : DataLayout() { |
| 206 | if (Error Err = parseLayoutString(LayoutString)) |
| 207 | report_fatal_error(Err: std::move(Err)); |
| 208 | } |
| 209 | |
| 210 | DataLayout &DataLayout::operator=(const DataLayout &Other) { |
| 211 | delete static_cast<StructLayoutMap *>(LayoutMap); |
| 212 | LayoutMap = nullptr; |
| 213 | StringRepresentation = Other.StringRepresentation; |
| 214 | BigEndian = Other.BigEndian; |
| 215 | AllocaAddrSpace = Other.AllocaAddrSpace; |
| 216 | ProgramAddrSpace = Other.ProgramAddrSpace; |
| 217 | DefaultGlobalsAddrSpace = Other.DefaultGlobalsAddrSpace; |
| 218 | StackNaturalAlign = Other.StackNaturalAlign; |
| 219 | FunctionPtrAlign = Other.FunctionPtrAlign; |
| 220 | TheFunctionPtrAlignType = Other.TheFunctionPtrAlignType; |
| 221 | ManglingMode = Other.ManglingMode; |
| 222 | LegalIntWidths = Other.LegalIntWidths; |
| 223 | IntSpecs = Other.IntSpecs; |
| 224 | FloatSpecs = Other.FloatSpecs; |
| 225 | VectorSpecs = Other.VectorSpecs; |
| 226 | PointerSpecs = Other.PointerSpecs; |
| 227 | StructABIAlignment = Other.StructABIAlignment; |
| 228 | StructPrefAlignment = Other.StructPrefAlignment; |
| 229 | return *this; |
| 230 | } |
| 231 | |
| 232 | bool DataLayout::operator==(const DataLayout &Other) const { |
| 233 | // NOTE: StringRepresentation might differ, it is not canonicalized. |
| 234 | return BigEndian == Other.BigEndian && |
| 235 | AllocaAddrSpace == Other.AllocaAddrSpace && |
| 236 | ProgramAddrSpace == Other.ProgramAddrSpace && |
| 237 | DefaultGlobalsAddrSpace == Other.DefaultGlobalsAddrSpace && |
| 238 | StackNaturalAlign == Other.StackNaturalAlign && |
| 239 | FunctionPtrAlign == Other.FunctionPtrAlign && |
| 240 | TheFunctionPtrAlignType == Other.TheFunctionPtrAlignType && |
| 241 | ManglingMode == Other.ManglingMode && |
| 242 | LegalIntWidths == Other.LegalIntWidths && IntSpecs == Other.IntSpecs && |
| 243 | FloatSpecs == Other.FloatSpecs && VectorSpecs == Other.VectorSpecs && |
| 244 | PointerSpecs == Other.PointerSpecs && |
| 245 | StructABIAlignment == Other.StructABIAlignment && |
| 246 | StructPrefAlignment == Other.StructPrefAlignment; |
| 247 | } |
| 248 | |
| 249 | Expected<DataLayout> DataLayout::parse(StringRef LayoutString) { |
| 250 | DataLayout Layout; |
| 251 | if (Error Err = Layout.parseLayoutString(LayoutString)) |
| 252 | return std::move(Err); |
| 253 | return Layout; |
| 254 | } |
| 255 | |
| 256 | static Error createSpecFormatError(Twine Format) { |
| 257 | return createStringError(S: "malformed specification, must be of the form \"" + |
| 258 | Format + "\"" ); |
| 259 | } |
| 260 | |
| 261 | /// Attempts to parse an address space component of a specification. |
| 262 | static Error parseAddrSpace(StringRef Str, unsigned &AddrSpace) { |
| 263 | if (Str.empty()) |
| 264 | return createStringError(Fmt: "address space component cannot be empty" ); |
| 265 | |
| 266 | if (!to_integer(S: Str, Num&: AddrSpace, Base: 10) || !isUInt<24>(x: AddrSpace)) |
| 267 | return createStringError(Fmt: "address space must be a 24-bit integer" ); |
| 268 | |
| 269 | return Error::success(); |
| 270 | } |
| 271 | |
| 272 | /// Attempts to parse an address space component of a specification allowing |
| 273 | /// name to be specified as well. The input is expected to be of the form |
| 274 | /// <number> '(' name ' )', with the name otional and the number is optional as |
| 275 | /// well. |
| 276 | static Error parseAddrSpaceAndName(StringRef Str, unsigned &AddrSpace, |
| 277 | StringRef &AddrSpaceName) { |
| 278 | if (Str.empty()) |
| 279 | return createStringError(Fmt: "address space component cannot be empty" ); |
| 280 | |
| 281 | if (isDigit(C: Str.front())) { |
| 282 | if (Str.consumeInteger(Radix: 10, Result&: AddrSpace) || !isUInt<24>(x: AddrSpace)) |
| 283 | return createStringError(Fmt: "address space must be a 24-bit integer" ); |
| 284 | } |
| 285 | |
| 286 | if (Str.empty()) |
| 287 | return Error::success(); |
| 288 | |
| 289 | if (Str.front() != '(') |
| 290 | return createStringError(Fmt: "address space must be a 24-bit integer" ); |
| 291 | |
| 292 | // Expect atleast one character in between the ( and ). |
| 293 | if (Str.back() != ')' || Str.size() == 2) |
| 294 | return createStringError(Fmt: "Expected `( address space name )`" ); |
| 295 | |
| 296 | AddrSpaceName = Str.drop_front().drop_back(); |
| 297 | // TODO: Do we need any additional verification for address space name? Like |
| 298 | // should be a valid identifier of some sort? Its not strictly needed. |
| 299 | |
| 300 | // LLVM's assembly parser used names "P", "G" and "A" to represent the |
| 301 | // program, default global, and alloca address space. This mapping is not 1:1 |
| 302 | // in the sense that all of them can map to the same numberic address space. |
| 303 | // Diallow using these predefined symbolic address space names as address |
| 304 | // space names specified in the data layout. |
| 305 | if (AddrSpaceName.size() == 1) { |
| 306 | char C = AddrSpaceName.front(); |
| 307 | if (C == 'P' || C == 'G' || C == 'A') |
| 308 | return createStringError( |
| 309 | Fmt: "Cannot use predefined address space names P/G/A in data layout" ); |
| 310 | } |
| 311 | return Error::success(); |
| 312 | } |
| 313 | |
| 314 | /// Attempts to parse a size component of a specification. |
| 315 | static Error parseSize(StringRef Str, unsigned &BitWidth, |
| 316 | StringRef Name = "size" ) { |
| 317 | if (Str.empty()) |
| 318 | return createStringError(S: Name + " component cannot be empty" ); |
| 319 | |
| 320 | if (!to_integer(S: Str, Num&: BitWidth, Base: 10) || BitWidth == 0 || !isUInt<24>(x: BitWidth)) |
| 321 | return createStringError(S: Name + " must be a non-zero 24-bit integer" ); |
| 322 | |
| 323 | return Error::success(); |
| 324 | } |
| 325 | |
| 326 | /// Attempts to parse an alignment component of a specification. |
| 327 | /// |
| 328 | /// On success, returns the value converted to byte amount in \p Alignment. |
| 329 | /// If the value is zero and \p AllowZero is true, \p Alignment is set to one. |
| 330 | /// |
| 331 | /// Return an error in a number of cases: |
| 332 | /// - \p Str is empty or contains characters other than decimal digits; |
| 333 | /// - the value is zero and \p AllowZero is false; |
| 334 | /// - the value is too large; |
| 335 | /// - the value is not a multiple of the byte width; |
| 336 | /// - the value converted to byte amount is not not a power of two. |
| 337 | static Error parseAlignment(StringRef Str, Align &Alignment, StringRef Name, |
| 338 | bool AllowZero = false) { |
| 339 | if (Str.empty()) |
| 340 | return createStringError(S: Name + " alignment component cannot be empty" ); |
| 341 | |
| 342 | unsigned Value; |
| 343 | if (!to_integer(S: Str, Num&: Value, Base: 10) || !isUInt<16>(x: Value)) |
| 344 | return createStringError(S: Name + " alignment must be a 16-bit integer" ); |
| 345 | |
| 346 | if (Value == 0) { |
| 347 | if (!AllowZero) |
| 348 | return createStringError(S: Name + " alignment must be non-zero" ); |
| 349 | Alignment = Align(1); |
| 350 | return Error::success(); |
| 351 | } |
| 352 | |
| 353 | constexpr unsigned ByteWidth = 8; |
| 354 | if (Value % ByteWidth || !isPowerOf2_32(Value: Value / ByteWidth)) |
| 355 | return createStringError( |
| 356 | S: Name + " alignment must be a power of two times the byte width" ); |
| 357 | |
| 358 | Alignment = Align(Value / ByteWidth); |
| 359 | return Error::success(); |
| 360 | } |
| 361 | |
| 362 | Error DataLayout::parsePrimitiveSpec(StringRef Spec) { |
| 363 | // [ifv]<size>:<abi>[:<pref>] |
| 364 | SmallVector<StringRef, 3> Components; |
| 365 | char Specifier = Spec.front(); |
| 366 | assert(Specifier == 'i' || Specifier == 'f' || Specifier == 'v'); |
| 367 | Spec.drop_front().split(A&: Components, Separator: ':'); |
| 368 | |
| 369 | if (Components.size() < 2 || Components.size() > 3) |
| 370 | return createSpecFormatError(Format: Twine(Specifier) + "<size>:<abi>[:<pref>]" ); |
| 371 | |
| 372 | // Size. Required, cannot be zero. |
| 373 | unsigned BitWidth; |
| 374 | if (Error Err = parseSize(Str: Components[0], BitWidth)) |
| 375 | return Err; |
| 376 | |
| 377 | // ABI alignment. |
| 378 | Align ABIAlign; |
| 379 | if (Error Err = parseAlignment(Str: Components[1], Alignment&: ABIAlign, Name: "ABI" )) |
| 380 | return Err; |
| 381 | |
| 382 | if (Specifier == 'i' && BitWidth == 8 && ABIAlign != 1) |
| 383 | return createStringError(Fmt: "i8 must be 8-bit aligned" ); |
| 384 | |
| 385 | // Preferred alignment. Optional, defaults to the ABI alignment. |
| 386 | Align PrefAlign = ABIAlign; |
| 387 | if (Components.size() > 2) |
| 388 | if (Error Err = parseAlignment(Str: Components[2], Alignment&: PrefAlign, Name: "preferred" )) |
| 389 | return Err; |
| 390 | |
| 391 | if (PrefAlign < ABIAlign) |
| 392 | return createStringError( |
| 393 | Fmt: "preferred alignment cannot be less than the ABI alignment" ); |
| 394 | |
| 395 | setPrimitiveSpec(Specifier, BitWidth, ABIAlign, PrefAlign); |
| 396 | return Error::success(); |
| 397 | } |
| 398 | |
| 399 | Error DataLayout::parseAggregateSpec(StringRef Spec) { |
| 400 | // a<size>:<abi>[:<pref>] |
| 401 | SmallVector<StringRef, 3> Components; |
| 402 | assert(Spec.front() == 'a'); |
| 403 | Spec.drop_front().split(A&: Components, Separator: ':'); |
| 404 | |
| 405 | if (Components.size() < 2 || Components.size() > 3) |
| 406 | return createSpecFormatError(Format: "a:<abi>[:<pref>]" ); |
| 407 | |
| 408 | // According to LangRef, <size> component must be absent altogether. |
| 409 | // For backward compatibility, allow it to be specified, but require |
| 410 | // it to be zero. |
| 411 | if (!Components[0].empty()) { |
| 412 | unsigned BitWidth; |
| 413 | if (!to_integer(S: Components[0], Num&: BitWidth, Base: 10) || BitWidth != 0) |
| 414 | return createStringError(Fmt: "size must be zero" ); |
| 415 | } |
| 416 | |
| 417 | // ABI alignment. Required. Can be zero, meaning use one byte alignment. |
| 418 | Align ABIAlign; |
| 419 | if (Error Err = |
| 420 | parseAlignment(Str: Components[1], Alignment&: ABIAlign, Name: "ABI" , /*AllowZero=*/true)) |
| 421 | return Err; |
| 422 | |
| 423 | // Preferred alignment. Optional, defaults to the ABI alignment. |
| 424 | Align PrefAlign = ABIAlign; |
| 425 | if (Components.size() > 2) |
| 426 | if (Error Err = parseAlignment(Str: Components[2], Alignment&: PrefAlign, Name: "preferred" )) |
| 427 | return Err; |
| 428 | |
| 429 | if (PrefAlign < ABIAlign) |
| 430 | return createStringError( |
| 431 | Fmt: "preferred alignment cannot be less than the ABI alignment" ); |
| 432 | |
| 433 | StructABIAlignment = ABIAlign; |
| 434 | StructPrefAlignment = PrefAlign; |
| 435 | return Error::success(); |
| 436 | } |
| 437 | |
| 438 | Error DataLayout::parsePointerSpec( |
| 439 | StringRef Spec, SmallDenseSet<StringRef, 8> &AddrSpaceNames) { |
| 440 | // p[<n>]:<size>:<abi>[:<pref>[:<idx>]] |
| 441 | SmallVector<StringRef, 5> Components; |
| 442 | assert(Spec.front() == 'p'); |
| 443 | Spec.drop_front().split(A&: Components, Separator: ':'); |
| 444 | |
| 445 | if (Components.size() < 3 || Components.size() > 5) |
| 446 | return createSpecFormatError(Format: "p[<n>]:<size>:<abi>[:<pref>[:<idx>]]" ); |
| 447 | |
| 448 | // Address space. Optional, defaults to 0. |
| 449 | unsigned AddrSpace = 0; |
| 450 | bool ExternalState = false; |
| 451 | bool UnstableRepr = false; |
| 452 | StringRef AddrSpaceName; |
| 453 | StringRef AddrSpaceStr = Components[0]; |
| 454 | while (!AddrSpaceStr.empty()) { |
| 455 | char C = AddrSpaceStr.front(); |
| 456 | if (C == 'e') { |
| 457 | ExternalState = true; |
| 458 | } else if (C == 'u') { |
| 459 | UnstableRepr = true; |
| 460 | } else if (isAlpha(C)) { |
| 461 | return createStringError(Fmt: "'%c' is not a valid pointer specification flag" , |
| 462 | Vals: C); |
| 463 | } else { |
| 464 | break; // not a valid flag, remaining must be the address space number. |
| 465 | } |
| 466 | AddrSpaceStr = AddrSpaceStr.drop_front(N: 1); |
| 467 | } |
| 468 | if (!AddrSpaceStr.empty()) |
| 469 | if (Error Err = |
| 470 | parseAddrSpaceAndName(Str: AddrSpaceStr, AddrSpace, AddrSpaceName)) |
| 471 | return Err; // Failed to parse the remaining characters as a number |
| 472 | if (AddrSpace == 0 && (ExternalState || UnstableRepr)) |
| 473 | return createStringError( |
| 474 | Fmt: "address space 0 cannot be unstable or have external state" ); |
| 475 | |
| 476 | // Check for duplicate address space names. |
| 477 | if (!AddrSpaceName.empty() && !AddrSpaceNames.insert(V: AddrSpaceName).second) |
| 478 | return createStringError(S: "address space name `" + AddrSpaceName + |
| 479 | "` already used" ); |
| 480 | |
| 481 | // Size. Required, cannot be zero. |
| 482 | unsigned BitWidth; |
| 483 | if (Error Err = parseSize(Str: Components[1], BitWidth, Name: "pointer size" )) |
| 484 | return Err; |
| 485 | |
| 486 | // ABI alignment. Required, cannot be zero. |
| 487 | Align ABIAlign; |
| 488 | if (Error Err = parseAlignment(Str: Components[2], Alignment&: ABIAlign, Name: "ABI" )) |
| 489 | return Err; |
| 490 | |
| 491 | // Preferred alignment. Optional, defaults to the ABI alignment. |
| 492 | // Cannot be zero. |
| 493 | Align PrefAlign = ABIAlign; |
| 494 | if (Components.size() > 3) |
| 495 | if (Error Err = parseAlignment(Str: Components[3], Alignment&: PrefAlign, Name: "preferred" )) |
| 496 | return Err; |
| 497 | |
| 498 | if (PrefAlign < ABIAlign) |
| 499 | return createStringError( |
| 500 | Fmt: "preferred alignment cannot be less than the ABI alignment" ); |
| 501 | |
| 502 | // Index size. Optional, defaults to pointer size. Cannot be zero. |
| 503 | unsigned IndexBitWidth = BitWidth; |
| 504 | if (Components.size() > 4) |
| 505 | if (Error Err = parseSize(Str: Components[4], BitWidth&: IndexBitWidth, Name: "index size" )) |
| 506 | return Err; |
| 507 | |
| 508 | if (IndexBitWidth > BitWidth) |
| 509 | return createStringError( |
| 510 | Fmt: "index size cannot be larger than the pointer size" ); |
| 511 | |
| 512 | setPointerSpec(AddrSpace, BitWidth, ABIAlign, PrefAlign, IndexBitWidth, |
| 513 | HasUnstableRepr: UnstableRepr, HasExternalState: ExternalState, AddrSpaceName); |
| 514 | return Error::success(); |
| 515 | } |
| 516 | |
| 517 | Error DataLayout::parseSpecification( |
| 518 | StringRef Spec, SmallVectorImpl<unsigned> &NonIntegralAddressSpaces, |
| 519 | SmallDenseSet<StringRef, 8> &AddrSpaceNames) { |
| 520 | // The "ni" specifier is the only two-character specifier. Handle it first. |
| 521 | if (Spec.starts_with(Prefix: "ni" )) { |
| 522 | // ni:<address space>[:<address space>]... |
| 523 | StringRef Rest = Spec.drop_front(N: 2); |
| 524 | |
| 525 | // Drop the first ':', then split the rest of the string the usual way. |
| 526 | if (!Rest.consume_front(Prefix: ":" )) |
| 527 | return createSpecFormatError(Format: "ni:<address space>[:<address space>]..." ); |
| 528 | |
| 529 | for (StringRef Str : split(Str: Rest, Separator: ':')) { |
| 530 | unsigned AddrSpace; |
| 531 | if (Error Err = parseAddrSpace(Str, AddrSpace)) |
| 532 | return Err; |
| 533 | if (AddrSpace == 0) |
| 534 | return createStringError(Fmt: "address space 0 cannot be non-integral" ); |
| 535 | NonIntegralAddressSpaces.push_back(Elt: AddrSpace); |
| 536 | } |
| 537 | return Error::success(); |
| 538 | } |
| 539 | |
| 540 | // The rest of the specifiers are single-character. |
| 541 | assert(!Spec.empty() && "Empty specification is handled by the caller" ); |
| 542 | char Specifier = Spec.front(); |
| 543 | |
| 544 | if (Specifier == 'i' || Specifier == 'f' || Specifier == 'v') |
| 545 | return parsePrimitiveSpec(Spec); |
| 546 | |
| 547 | if (Specifier == 'a') |
| 548 | return parseAggregateSpec(Spec); |
| 549 | |
| 550 | if (Specifier == 'p') |
| 551 | return parsePointerSpec(Spec, AddrSpaceNames); |
| 552 | |
| 553 | StringRef Rest = Spec.drop_front(); |
| 554 | switch (Specifier) { |
| 555 | case 's': |
| 556 | // Deprecated, but ignoring here to preserve loading older textual llvm |
| 557 | // ASM file |
| 558 | break; |
| 559 | case 'e': |
| 560 | case 'E': |
| 561 | if (!Rest.empty()) |
| 562 | return createStringError( |
| 563 | Fmt: "malformed specification, must be just 'e' or 'E'" ); |
| 564 | BigEndian = Specifier == 'E'; |
| 565 | break; |
| 566 | case 'n': // Native integer types. |
| 567 | // n<size>[:<size>]... |
| 568 | for (StringRef Str : split(Str: Rest, Separator: ':')) { |
| 569 | unsigned BitWidth; |
| 570 | if (Error Err = parseSize(Str, BitWidth)) |
| 571 | return Err; |
| 572 | LegalIntWidths.push_back(Elt: BitWidth); |
| 573 | } |
| 574 | break; |
| 575 | case 'S': { // Stack natural alignment. |
| 576 | // S<size> |
| 577 | if (Rest.empty()) |
| 578 | return createSpecFormatError(Format: "S<size>" ); |
| 579 | Align Alignment; |
| 580 | if (Error Err = parseAlignment(Str: Rest, Alignment, Name: "stack natural" )) |
| 581 | return Err; |
| 582 | StackNaturalAlign = Alignment; |
| 583 | break; |
| 584 | } |
| 585 | case 'F': { |
| 586 | // F<type><abi> |
| 587 | if (Rest.empty()) |
| 588 | return createSpecFormatError(Format: "F<type><abi>" ); |
| 589 | char Type = Rest.front(); |
| 590 | Rest = Rest.drop_front(); |
| 591 | switch (Type) { |
| 592 | case 'i': |
| 593 | TheFunctionPtrAlignType = FunctionPtrAlignType::Independent; |
| 594 | break; |
| 595 | case 'n': |
| 596 | TheFunctionPtrAlignType = FunctionPtrAlignType::MultipleOfFunctionAlign; |
| 597 | break; |
| 598 | default: |
| 599 | return createStringError(S: "unknown function pointer alignment type '" + |
| 600 | Twine(Type) + "'" ); |
| 601 | } |
| 602 | Align Alignment; |
| 603 | if (Error Err = parseAlignment(Str: Rest, Alignment, Name: "ABI" )) |
| 604 | return Err; |
| 605 | FunctionPtrAlign = Alignment; |
| 606 | break; |
| 607 | } |
| 608 | case 'P': { // Function address space. |
| 609 | if (Rest.empty()) |
| 610 | return createSpecFormatError(Format: "P<address space>" ); |
| 611 | if (Error Err = parseAddrSpace(Str: Rest, AddrSpace&: ProgramAddrSpace)) |
| 612 | return Err; |
| 613 | break; |
| 614 | } |
| 615 | case 'A': { // Default stack/alloca address space. |
| 616 | if (Rest.empty()) |
| 617 | return createSpecFormatError(Format: "A<address space>" ); |
| 618 | if (Error Err = parseAddrSpace(Str: Rest, AddrSpace&: AllocaAddrSpace)) |
| 619 | return Err; |
| 620 | break; |
| 621 | } |
| 622 | case 'G': { // Default address space for global variables. |
| 623 | if (Rest.empty()) |
| 624 | return createSpecFormatError(Format: "G<address space>" ); |
| 625 | if (Error Err = parseAddrSpace(Str: Rest, AddrSpace&: DefaultGlobalsAddrSpace)) |
| 626 | return Err; |
| 627 | break; |
| 628 | } |
| 629 | case 'm': |
| 630 | if (!Rest.consume_front(Prefix: ":" ) || Rest.empty()) |
| 631 | return createSpecFormatError(Format: "m:<mangling>" ); |
| 632 | if (Rest.size() > 1) |
| 633 | return createStringError(Fmt: "unknown mangling mode" ); |
| 634 | switch (Rest[0]) { |
| 635 | default: |
| 636 | return createStringError(Fmt: "unknown mangling mode" ); |
| 637 | case 'e': |
| 638 | ManglingMode = MM_ELF; |
| 639 | break; |
| 640 | case 'l': |
| 641 | ManglingMode = MM_GOFF; |
| 642 | break; |
| 643 | case 'o': |
| 644 | ManglingMode = MM_MachO; |
| 645 | break; |
| 646 | case 'm': |
| 647 | ManglingMode = MM_Mips; |
| 648 | break; |
| 649 | case 'w': |
| 650 | ManglingMode = MM_WinCOFF; |
| 651 | break; |
| 652 | case 'x': |
| 653 | ManglingMode = MM_WinCOFFX86; |
| 654 | break; |
| 655 | case 'a': |
| 656 | ManglingMode = MM_XCOFF; |
| 657 | break; |
| 658 | } |
| 659 | break; |
| 660 | default: |
| 661 | return createStringError(S: "unknown specifier '" + Twine(Specifier) + "'" ); |
| 662 | } |
| 663 | |
| 664 | return Error::success(); |
| 665 | } |
| 666 | |
| 667 | Error DataLayout::parseLayoutString(StringRef LayoutString) { |
| 668 | StringRepresentation = LayoutString.str(); |
| 669 | |
| 670 | if (LayoutString.empty()) |
| 671 | return Error::success(); |
| 672 | |
| 673 | // Split the data layout string into specifications separated by '-' and |
| 674 | // parse each specification individually, updating internal data structures. |
| 675 | SmallVector<unsigned, 8> NonIntegralAddressSpaces; |
| 676 | SmallDenseSet<StringRef, 8> AddessSpaceNames; |
| 677 | for (StringRef Spec : split(Str: StringRepresentation, Separator: '-')) { |
| 678 | if (Spec.empty()) |
| 679 | return createStringError(Fmt: "empty specification is not allowed" ); |
| 680 | if (Error Err = parseSpecification(Spec, NonIntegralAddressSpaces, |
| 681 | AddrSpaceNames&: AddessSpaceNames)) |
| 682 | return Err; |
| 683 | } |
| 684 | // Mark all address spaces that were qualified as non-integral now. This has |
| 685 | // to be done later since the non-integral property is not part of the data |
| 686 | // layout pointer specification. |
| 687 | for (unsigned AS : NonIntegralAddressSpaces) { |
| 688 | // If there is no special spec for a given AS, getPointerSpec(AS) returns |
| 689 | // the spec for AS0, and we then update that to mark it non-integral. |
| 690 | const PointerSpec &PS = getPointerSpec(AddrSpace: AS); |
| 691 | setPointerSpec(AddrSpace: AS, BitWidth: PS.BitWidth, ABIAlign: PS.ABIAlign, PrefAlign: PS.PrefAlign, IndexBitWidth: PS.IndexBitWidth, |
| 692 | /*HasUnstableRepr=*/true, /*HasExternalState=*/false, |
| 693 | AddrSpaceName: getAddressSpaceName(AS)); |
| 694 | } |
| 695 | |
| 696 | return Error::success(); |
| 697 | } |
| 698 | |
| 699 | void DataLayout::setPrimitiveSpec(char Specifier, uint32_t BitWidth, |
| 700 | Align ABIAlign, Align PrefAlign) { |
| 701 | SmallVectorImpl<PrimitiveSpec> *Specs; |
| 702 | switch (Specifier) { |
| 703 | default: |
| 704 | llvm_unreachable("Unexpected specifier" ); |
| 705 | case 'i': |
| 706 | Specs = &IntSpecs; |
| 707 | break; |
| 708 | case 'f': |
| 709 | Specs = &FloatSpecs; |
| 710 | break; |
| 711 | case 'v': |
| 712 | Specs = &VectorSpecs; |
| 713 | break; |
| 714 | } |
| 715 | |
| 716 | auto I = lower_bound(Range&: *Specs, Value&: BitWidth, C: LessPrimitiveBitWidth()); |
| 717 | if (I != Specs->end() && I->BitWidth == BitWidth) { |
| 718 | // Update the abi, preferred alignments. |
| 719 | I->ABIAlign = ABIAlign; |
| 720 | I->PrefAlign = PrefAlign; |
| 721 | } else { |
| 722 | // Insert before I to keep the vector sorted. |
| 723 | Specs->insert(I, Elt: PrimitiveSpec{.BitWidth: BitWidth, .ABIAlign: ABIAlign, .PrefAlign: PrefAlign}); |
| 724 | } |
| 725 | } |
| 726 | |
| 727 | const DataLayout::PointerSpec & |
| 728 | DataLayout::getPointerSpec(uint32_t AddrSpace) const { |
| 729 | if (AddrSpace != 0) { |
| 730 | auto I = lower_bound(Range: PointerSpecs, Value&: AddrSpace, C: LessPointerAddrSpace()); |
| 731 | if (I != PointerSpecs.end() && I->AddrSpace == AddrSpace) |
| 732 | return *I; |
| 733 | } |
| 734 | |
| 735 | assert(PointerSpecs[0].AddrSpace == 0); |
| 736 | return PointerSpecs[0]; |
| 737 | } |
| 738 | |
| 739 | void DataLayout::setPointerSpec(uint32_t AddrSpace, uint32_t BitWidth, |
| 740 | Align ABIAlign, Align PrefAlign, |
| 741 | uint32_t IndexBitWidth, bool HasUnstableRepr, |
| 742 | bool HasExternalState, |
| 743 | StringRef AddrSpaceName) { |
| 744 | auto I = lower_bound(Range&: PointerSpecs, Value&: AddrSpace, C: LessPointerAddrSpace()); |
| 745 | if (I == PointerSpecs.end() || I->AddrSpace != AddrSpace) { |
| 746 | PointerSpecs.insert(I, Elt: PointerSpec{.AddrSpace: AddrSpace, .BitWidth: BitWidth, .ABIAlign: ABIAlign, .PrefAlign: PrefAlign, |
| 747 | .IndexBitWidth: IndexBitWidth, .HasUnstableRepresentation: HasUnstableRepr, |
| 748 | .HasExternalState: HasExternalState, .AddrSpaceName: AddrSpaceName.str()}); |
| 749 | } else { |
| 750 | I->BitWidth = BitWidth; |
| 751 | I->ABIAlign = ABIAlign; |
| 752 | I->PrefAlign = PrefAlign; |
| 753 | I->IndexBitWidth = IndexBitWidth; |
| 754 | I->HasUnstableRepresentation = HasUnstableRepr; |
| 755 | I->HasExternalState = HasExternalState; |
| 756 | I->AddrSpaceName = AddrSpaceName.str(); |
| 757 | } |
| 758 | } |
| 759 | |
| 760 | Align DataLayout::getIntegerAlignment(uint32_t BitWidth, |
| 761 | bool abi_or_pref) const { |
| 762 | auto I = IntSpecs.begin(); |
| 763 | for (; I != IntSpecs.end(); ++I) { |
| 764 | if (I->BitWidth >= BitWidth) |
| 765 | break; |
| 766 | } |
| 767 | |
| 768 | // If we don't have an exact match, use alignment of next larger integer |
| 769 | // type. If there is none, use alignment of largest integer type by going |
| 770 | // back one element. |
| 771 | if (I == IntSpecs.end()) |
| 772 | --I; |
| 773 | return abi_or_pref ? I->ABIAlign : I->PrefAlign; |
| 774 | } |
| 775 | |
| 776 | DataLayout::~DataLayout() { delete static_cast<StructLayoutMap *>(LayoutMap); } |
| 777 | |
| 778 | const StructLayout *DataLayout::getStructLayout(StructType *Ty) const { |
| 779 | if (!LayoutMap) |
| 780 | LayoutMap = new StructLayoutMap(); |
| 781 | |
| 782 | StructLayoutMap *STM = static_cast<StructLayoutMap*>(LayoutMap); |
| 783 | StructLayout *&SL = (*STM)[Ty]; |
| 784 | if (SL) return SL; |
| 785 | |
| 786 | // Otherwise, create the struct layout. Because it is variable length, we |
| 787 | // malloc it, then use placement new. |
| 788 | StructLayout *L = (StructLayout *)safe_malloc( |
| 789 | Sz: StructLayout::totalSizeToAlloc<TypeSize>(Counts: Ty->getNumElements())); |
| 790 | |
| 791 | // Set SL before calling StructLayout's ctor. The ctor could cause other |
| 792 | // entries to be added to TheMap, invalidating our reference. |
| 793 | SL = L; |
| 794 | |
| 795 | new (L) StructLayout(Ty, *this); |
| 796 | |
| 797 | return L; |
| 798 | } |
| 799 | |
| 800 | Align DataLayout::getPointerABIAlignment(unsigned AS) const { |
| 801 | return getPointerSpec(AddrSpace: AS).ABIAlign; |
| 802 | } |
| 803 | |
| 804 | StringRef DataLayout::getAddressSpaceName(unsigned AS) const { |
| 805 | return getPointerSpec(AddrSpace: AS).AddrSpaceName; |
| 806 | } |
| 807 | |
| 808 | std::optional<unsigned> DataLayout::getNamedAddressSpace(StringRef Name) const { |
| 809 | auto II = llvm::find_if(Range: PointerSpecs, P: [Name](const PointerSpec &PS) { |
| 810 | return PS.AddrSpaceName == Name; |
| 811 | }); |
| 812 | if (II != PointerSpecs.end()) |
| 813 | return II->AddrSpace; |
| 814 | return std::nullopt; |
| 815 | } |
| 816 | |
| 817 | Align DataLayout::getPointerPrefAlignment(unsigned AS) const { |
| 818 | return getPointerSpec(AddrSpace: AS).PrefAlign; |
| 819 | } |
| 820 | |
| 821 | unsigned DataLayout::getPointerSize(unsigned AS) const { |
| 822 | return divideCeil(Numerator: getPointerSpec(AddrSpace: AS).BitWidth, Denominator: 8); |
| 823 | } |
| 824 | |
| 825 | unsigned DataLayout::getPointerTypeSizeInBits(Type *Ty) const { |
| 826 | assert(Ty->isPtrOrPtrVectorTy() && |
| 827 | "This should only be called with a pointer or pointer vector type" ); |
| 828 | Ty = Ty->getScalarType(); |
| 829 | return getPointerSizeInBits(AS: cast<PointerType>(Val: Ty)->getAddressSpace()); |
| 830 | } |
| 831 | |
| 832 | unsigned DataLayout::getIndexSize(unsigned AS) const { |
| 833 | return divideCeil(Numerator: getPointerSpec(AddrSpace: AS).IndexBitWidth, Denominator: 8); |
| 834 | } |
| 835 | |
| 836 | unsigned DataLayout::getIndexTypeSizeInBits(Type *Ty) const { |
| 837 | assert(Ty->isPtrOrPtrVectorTy() && |
| 838 | "This should only be called with a pointer or pointer vector type" ); |
| 839 | Ty = Ty->getScalarType(); |
| 840 | return getIndexSizeInBits(AS: cast<PointerType>(Val: Ty)->getAddressSpace()); |
| 841 | } |
| 842 | |
| 843 | /*! |
| 844 | \param abi_or_pref Flag that determines which alignment is returned. true |
| 845 | returns the ABI alignment, false returns the preferred alignment. |
| 846 | \param Ty The underlying type for which alignment is determined. |
| 847 | |
| 848 | Get the ABI (\a abi_or_pref == true) or preferred alignment (\a abi_or_pref |
| 849 | == false) for the requested type \a Ty. |
| 850 | */ |
| 851 | Align DataLayout::getAlignment(Type *Ty, bool abi_or_pref) const { |
| 852 | assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!" ); |
| 853 | switch (Ty->getTypeID()) { |
| 854 | // Early escape for the non-numeric types. |
| 855 | case Type::LabelTyID: |
| 856 | return abi_or_pref ? getPointerABIAlignment(AS: 0) : getPointerPrefAlignment(AS: 0); |
| 857 | case Type::PointerTyID: { |
| 858 | unsigned AS = cast<PointerType>(Val: Ty)->getAddressSpace(); |
| 859 | return abi_or_pref ? getPointerABIAlignment(AS) |
| 860 | : getPointerPrefAlignment(AS); |
| 861 | } |
| 862 | case Type::ArrayTyID: |
| 863 | return getAlignment(Ty: cast<ArrayType>(Val: Ty)->getElementType(), abi_or_pref); |
| 864 | |
| 865 | case Type::StructTyID: { |
| 866 | // Packed structure types always have an ABI alignment of one. |
| 867 | if (cast<StructType>(Val: Ty)->isPacked() && abi_or_pref) |
| 868 | return Align(1); |
| 869 | |
| 870 | // Get the layout annotation... which is lazily created on demand. |
| 871 | const StructLayout *Layout = getStructLayout(Ty: cast<StructType>(Val: Ty)); |
| 872 | const Align Align = abi_or_pref ? StructABIAlignment : StructPrefAlignment; |
| 873 | return std::max(a: Align, b: Layout->getAlignment()); |
| 874 | } |
| 875 | case Type::IntegerTyID: |
| 876 | return getIntegerAlignment(BitWidth: Ty->getIntegerBitWidth(), abi_or_pref); |
| 877 | case Type::HalfTyID: |
| 878 | case Type::BFloatTyID: |
| 879 | case Type::FloatTyID: |
| 880 | case Type::DoubleTyID: |
| 881 | // PPC_FP128TyID and FP128TyID have different data contents, but the |
| 882 | // same size and alignment, so they look the same here. |
| 883 | case Type::PPC_FP128TyID: |
| 884 | case Type::FP128TyID: |
| 885 | case Type::X86_FP80TyID: { |
| 886 | unsigned BitWidth = getTypeSizeInBits(Ty).getFixedValue(); |
| 887 | auto I = lower_bound(Range: FloatSpecs, Value&: BitWidth, C: LessPrimitiveBitWidth()); |
| 888 | if (I != FloatSpecs.end() && I->BitWidth == BitWidth) |
| 889 | return abi_or_pref ? I->ABIAlign : I->PrefAlign; |
| 890 | |
| 891 | // If we still couldn't find a reasonable default alignment, fall back |
| 892 | // to a simple heuristic that the alignment is the first power of two |
| 893 | // greater-or-equal to the store size of the type. This is a reasonable |
| 894 | // approximation of reality, and if the user wanted something less |
| 895 | // less conservative, they should have specified it explicitly in the data |
| 896 | // layout. |
| 897 | return Align(PowerOf2Ceil(A: BitWidth / 8)); |
| 898 | } |
| 899 | case Type::FixedVectorTyID: |
| 900 | case Type::ScalableVectorTyID: { |
| 901 | unsigned BitWidth = getTypeSizeInBits(Ty).getKnownMinValue(); |
| 902 | auto I = lower_bound(Range: VectorSpecs, Value&: BitWidth, C: LessPrimitiveBitWidth()); |
| 903 | if (I != VectorSpecs.end() && I->BitWidth == BitWidth) |
| 904 | return abi_or_pref ? I->ABIAlign : I->PrefAlign; |
| 905 | |
| 906 | // By default, use natural alignment for vector types. This is consistent |
| 907 | // with what clang and llvm-gcc do. |
| 908 | // |
| 909 | // We're only calculating a natural alignment, so it doesn't have to be |
| 910 | // based on the full size for scalable vectors. Using the minimum element |
| 911 | // count should be enough here. |
| 912 | return Align(PowerOf2Ceil(A: getTypeStoreSize(Ty).getKnownMinValue())); |
| 913 | } |
| 914 | case Type::X86_AMXTyID: |
| 915 | return Align(64); |
| 916 | case Type::TargetExtTyID: { |
| 917 | Type *LayoutTy = cast<TargetExtType>(Val: Ty)->getLayoutType(); |
| 918 | return getAlignment(Ty: LayoutTy, abi_or_pref); |
| 919 | } |
| 920 | default: |
| 921 | llvm_unreachable("Bad type for getAlignment!!!" ); |
| 922 | } |
| 923 | } |
| 924 | |
| 925 | TypeSize DataLayout::getTypeAllocSize(Type *Ty) const { |
| 926 | switch (Ty->getTypeID()) { |
| 927 | case Type::ArrayTyID: { |
| 928 | // The alignment of the array is the alignment of the element, so there |
| 929 | // is no need for further adjustment. |
| 930 | auto *ATy = cast<ArrayType>(Val: Ty); |
| 931 | return ATy->getNumElements() * getTypeAllocSize(Ty: ATy->getElementType()); |
| 932 | } |
| 933 | case Type::StructTyID: { |
| 934 | const StructLayout *Layout = getStructLayout(Ty: cast<StructType>(Val: Ty)); |
| 935 | TypeSize Size = Layout->getSizeInBytes(); |
| 936 | |
| 937 | if (cast<StructType>(Val: Ty)->isPacked()) |
| 938 | return Size; |
| 939 | |
| 940 | Align A = std::max(a: StructABIAlignment, b: Layout->getAlignment()); |
| 941 | return alignTo(Size, Align: A.value()); |
| 942 | } |
| 943 | case Type::IntegerTyID: { |
| 944 | unsigned BitWidth = Ty->getIntegerBitWidth(); |
| 945 | TypeSize Size = TypeSize::getFixed(ExactSize: divideCeil(Numerator: BitWidth, Denominator: 8)); |
| 946 | Align A = getIntegerAlignment(BitWidth, /*ABI=*/abi_or_pref: true); |
| 947 | return alignTo(Size, Align: A.value()); |
| 948 | } |
| 949 | case Type::PointerTyID: { |
| 950 | unsigned AS = Ty->getPointerAddressSpace(); |
| 951 | TypeSize Size = TypeSize::getFixed(ExactSize: getPointerSize(AS)); |
| 952 | return alignTo(Size, Align: getPointerABIAlignment(AS).value()); |
| 953 | } |
| 954 | case Type::TargetExtTyID: { |
| 955 | Type *LayoutTy = cast<TargetExtType>(Val: Ty)->getLayoutType(); |
| 956 | return getTypeAllocSize(Ty: LayoutTy); |
| 957 | } |
| 958 | default: |
| 959 | return alignTo(Size: getTypeStoreSize(Ty), Align: getABITypeAlign(Ty).value()); |
| 960 | } |
| 961 | } |
| 962 | |
| 963 | Align DataLayout::getABITypeAlign(Type *Ty) const { |
| 964 | return getAlignment(Ty, abi_or_pref: true); |
| 965 | } |
| 966 | |
| 967 | Align DataLayout::getPrefTypeAlign(Type *Ty) const { |
| 968 | return getAlignment(Ty, abi_or_pref: false); |
| 969 | } |
| 970 | |
| 971 | IntegerType *DataLayout::getIntPtrType(LLVMContext &C, |
| 972 | unsigned AddressSpace) const { |
| 973 | return IntegerType::get(C, NumBits: getPointerSizeInBits(AS: AddressSpace)); |
| 974 | } |
| 975 | |
| 976 | Type *DataLayout::getIntPtrType(Type *Ty) const { |
| 977 | assert(Ty->isPtrOrPtrVectorTy() && |
| 978 | "Expected a pointer or pointer vector type." ); |
| 979 | unsigned NumBits = getPointerTypeSizeInBits(Ty); |
| 980 | IntegerType *IntTy = IntegerType::get(C&: Ty->getContext(), NumBits); |
| 981 | if (VectorType *VecTy = dyn_cast<VectorType>(Val: Ty)) |
| 982 | return VectorType::get(ElementType: IntTy, Other: VecTy); |
| 983 | return IntTy; |
| 984 | } |
| 985 | |
| 986 | Type *DataLayout::getSmallestLegalIntType(LLVMContext &C, unsigned Width) const { |
| 987 | for (unsigned LegalIntWidth : LegalIntWidths) |
| 988 | if (Width <= LegalIntWidth) |
| 989 | return Type::getIntNTy(C, N: LegalIntWidth); |
| 990 | return nullptr; |
| 991 | } |
| 992 | |
| 993 | unsigned DataLayout::getLargestLegalIntTypeSizeInBits() const { |
| 994 | auto Max = llvm::max_element(Range: LegalIntWidths); |
| 995 | return Max != LegalIntWidths.end() ? *Max : 0; |
| 996 | } |
| 997 | |
| 998 | IntegerType *DataLayout::getIndexType(LLVMContext &C, |
| 999 | unsigned AddressSpace) const { |
| 1000 | return IntegerType::get(C, NumBits: getIndexSizeInBits(AS: AddressSpace)); |
| 1001 | } |
| 1002 | |
| 1003 | Type *DataLayout::getIndexType(Type *Ty) const { |
| 1004 | assert(Ty->isPtrOrPtrVectorTy() && |
| 1005 | "Expected a pointer or pointer vector type." ); |
| 1006 | unsigned NumBits = getIndexTypeSizeInBits(Ty); |
| 1007 | IntegerType *IntTy = IntegerType::get(C&: Ty->getContext(), NumBits); |
| 1008 | if (VectorType *VecTy = dyn_cast<VectorType>(Val: Ty)) |
| 1009 | return VectorType::get(ElementType: IntTy, Other: VecTy); |
| 1010 | return IntTy; |
| 1011 | } |
| 1012 | |
| 1013 | int64_t DataLayout::getIndexedOffsetInType(Type *ElemTy, |
| 1014 | ArrayRef<Value *> Indices) const { |
| 1015 | int64_t Result = 0; |
| 1016 | |
| 1017 | generic_gep_type_iterator<Value* const*> |
| 1018 | GTI = gep_type_begin(Op0: ElemTy, A: Indices), |
| 1019 | GTE = gep_type_end(ElemTy, A: Indices); |
| 1020 | for (; GTI != GTE; ++GTI) { |
| 1021 | Value *Idx = GTI.getOperand(); |
| 1022 | if (StructType *STy = GTI.getStructTypeOrNull()) { |
| 1023 | assert(Idx->getType()->isIntegerTy(32) && "Illegal struct idx" ); |
| 1024 | unsigned FieldNo = cast<ConstantInt>(Val: Idx)->getZExtValue(); |
| 1025 | |
| 1026 | // Get structure layout information... |
| 1027 | const StructLayout *Layout = getStructLayout(Ty: STy); |
| 1028 | |
| 1029 | // Add in the offset, as calculated by the structure layout info... |
| 1030 | Result += Layout->getElementOffset(Idx: FieldNo); |
| 1031 | } else { |
| 1032 | if (int64_t ArrayIdx = cast<ConstantInt>(Val: Idx)->getSExtValue()) |
| 1033 | Result += ArrayIdx * GTI.getSequentialElementStride(DL: *this); |
| 1034 | } |
| 1035 | } |
| 1036 | |
| 1037 | return Result; |
| 1038 | } |
| 1039 | |
| 1040 | static APInt getElementIndex(TypeSize ElemSize, APInt &Offset) { |
| 1041 | // Skip over scalable or zero size elements. Also skip element sizes larger |
| 1042 | // than the positive index space, because the arithmetic below may not be |
| 1043 | // correct in that case. |
| 1044 | unsigned BitWidth = Offset.getBitWidth(); |
| 1045 | if (ElemSize.isScalable() || ElemSize == 0 || |
| 1046 | !isUIntN(N: BitWidth - 1, x: ElemSize)) { |
| 1047 | return APInt::getZero(numBits: BitWidth); |
| 1048 | } |
| 1049 | |
| 1050 | uint64_t FixedElemSize = ElemSize.getFixedValue(); |
| 1051 | APInt Index = Offset.sdiv(RHS: FixedElemSize); |
| 1052 | Offset -= Index * FixedElemSize; |
| 1053 | if (Offset.isNegative()) { |
| 1054 | // Prefer a positive remaining offset to allow struct indexing. |
| 1055 | --Index; |
| 1056 | Offset += FixedElemSize; |
| 1057 | assert(Offset.isNonNegative() && "Remaining offset shouldn't be negative" ); |
| 1058 | } |
| 1059 | return Index; |
| 1060 | } |
| 1061 | |
| 1062 | std::optional<APInt> DataLayout::getGEPIndexForOffset(Type *&ElemTy, |
| 1063 | APInt &Offset) const { |
| 1064 | if (auto *ArrTy = dyn_cast<ArrayType>(Val: ElemTy)) { |
| 1065 | ElemTy = ArrTy->getElementType(); |
| 1066 | return getElementIndex(ElemSize: getTypeAllocSize(Ty: ElemTy), Offset); |
| 1067 | } |
| 1068 | |
| 1069 | if (isa<VectorType>(Val: ElemTy)) { |
| 1070 | // Vector GEPs are partially broken (e.g. for overaligned element types), |
| 1071 | // and may be forbidden in the future, so avoid generating GEPs into |
| 1072 | // vectors. See https://discourse.llvm.org/t/67497 |
| 1073 | return std::nullopt; |
| 1074 | } |
| 1075 | |
| 1076 | if (auto *STy = dyn_cast<StructType>(Val: ElemTy)) { |
| 1077 | const StructLayout *SL = getStructLayout(Ty: STy); |
| 1078 | uint64_t IntOffset = Offset.getZExtValue(); |
| 1079 | if (IntOffset >= SL->getSizeInBytes()) |
| 1080 | return std::nullopt; |
| 1081 | |
| 1082 | unsigned Index = SL->getElementContainingOffset(FixedOffset: IntOffset); |
| 1083 | Offset -= SL->getElementOffset(Idx: Index); |
| 1084 | ElemTy = STy->getElementType(N: Index); |
| 1085 | return APInt(32, Index); |
| 1086 | } |
| 1087 | |
| 1088 | // Non-aggregate type. |
| 1089 | return std::nullopt; |
| 1090 | } |
| 1091 | |
| 1092 | SmallVector<APInt> DataLayout::getGEPIndicesForOffset(Type *&ElemTy, |
| 1093 | APInt &Offset) const { |
| 1094 | assert(ElemTy->isSized() && "Element type must be sized" ); |
| 1095 | SmallVector<APInt> Indices; |
| 1096 | Indices.push_back(Elt: getElementIndex(ElemSize: getTypeAllocSize(Ty: ElemTy), Offset)); |
| 1097 | while (Offset != 0) { |
| 1098 | std::optional<APInt> Index = getGEPIndexForOffset(ElemTy, Offset); |
| 1099 | if (!Index) |
| 1100 | break; |
| 1101 | Indices.push_back(Elt: *Index); |
| 1102 | } |
| 1103 | |
| 1104 | return Indices; |
| 1105 | } |
| 1106 | |
| 1107 | /// getPreferredAlign - Return the preferred alignment of the specified global. |
| 1108 | /// This includes an explicitly requested alignment (if the global has one). |
| 1109 | Align DataLayout::getPreferredAlign(const GlobalVariable *GV) const { |
| 1110 | MaybeAlign GVAlignment = GV->getAlign(); |
| 1111 | // If a section is specified, always precisely honor explicit alignment, |
| 1112 | // so we don't insert padding into a section we don't control. |
| 1113 | if (GVAlignment && GV->hasSection()) |
| 1114 | return *GVAlignment; |
| 1115 | |
| 1116 | // If no explicit alignment is specified, compute the alignment based on |
| 1117 | // the IR type. If an alignment is specified, increase it to match the ABI |
| 1118 | // alignment of the IR type. |
| 1119 | // |
| 1120 | // FIXME: Not sure it makes sense to use the alignment of the type if |
| 1121 | // there's already an explicit alignment specification. |
| 1122 | Type *ElemType = GV->getValueType(); |
| 1123 | Align Alignment = getPrefTypeAlign(Ty: ElemType); |
| 1124 | if (GVAlignment) { |
| 1125 | if (*GVAlignment >= Alignment) |
| 1126 | Alignment = *GVAlignment; |
| 1127 | else |
| 1128 | Alignment = std::max(a: *GVAlignment, b: getABITypeAlign(Ty: ElemType)); |
| 1129 | } |
| 1130 | |
| 1131 | // If no explicit alignment is specified, and the global is large, increase |
| 1132 | // the alignment to 16. |
| 1133 | // FIXME: Why 16, specifically? |
| 1134 | if (GV->hasInitializer() && !GVAlignment) { |
| 1135 | if (Alignment < Align(16)) { |
| 1136 | // If the global is not external, see if it is large. If so, give it a |
| 1137 | // larger alignment. |
| 1138 | if (getTypeSizeInBits(Ty: ElemType) > 128) |
| 1139 | Alignment = Align(16); // 16-byte alignment. |
| 1140 | } |
| 1141 | } |
| 1142 | return Alignment; |
| 1143 | } |
| 1144 | |