LLVM 24.0.0git
DataLayout.h
Go to the documentation of this file.
1//===- llvm/DataLayout.h - Data size & alignment info -----------*- C++ -*-===//
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. It uses lazy annotations to cache information about how
11// structure types are laid out and used.
12//
13// This structure should be created once, filled in if the defaults are not
14// correct and then passed around by const&. None of the members functions
15// require modification to the object.
16//
17//===----------------------------------------------------------------------===//
18
19#ifndef LLVM_IR_DATALAYOUT_H
20#define LLVM_IR_DATALAYOUT_H
21
22#include "llvm/ADT/APInt.h"
23#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/DenseSet.h"
25#include "llvm/ADT/STLExtras.h"
27#include "llvm/ADT/StringRef.h"
29#include "llvm/IR/Type.h"
37#include <cassert>
38#include <cstdint>
39#include <string>
40
41// This needs to be outside of the namespace, to avoid conflict with llvm-c
42// decl.
43using LLVMTargetDataRef = struct LLVMOpaqueTargetData *;
44
45namespace llvm {
46
47class GlobalVariable;
48class LLVMContext;
49class StructLayout;
50class Value;
51
52// FIXME: Currently the DataLayout string carries a "preferred alignment"
53// for types. As the DataLayout is module/global, this should likely be
54// sunk down to an FTTI element that is queried rather than a global
55// preference.
56
57/// A parsed version of the target data layout string in and methods for
58/// querying it.
59///
60/// The target data layout string is specified *by the target* - a frontend
61/// generating LLVM IR is required to generate the right target data for the
62/// target being codegen'd to.
64public:
65 /// Primitive type specification.
73
74 /// Pointer type specification.
75 struct PointerSpec {
80 /// The index bit width also defines the address size in this address space.
81 /// If the index width is less than the representation bit width, the
82 /// pointer is non-integral and bits beyond the index width could be used
83 /// for additional metadata (e.g. AMDGPU buffer fat pointers with bounds
84 /// and other flags or CHERI capabilities that contain bounds+permissions).
86 /// Pointers in this address space don't have a well-defined bitwise
87 /// representation (e.g. they may be relocated by a copying garbage
88 /// collector and thus have different addresses at different times).
90 /// Pointers in this address space have additional state bits that are
91 /// located at a target-defined location when stored in memory. An example
92 /// of this would be CHERI capabilities where the validity bit is stored
93 /// separately from the pointer address+bounds information.
95 // Symbolic name of the address space.
96 std::string AddrSpaceName;
97 /// The null pointer bit representation for this address space.
99
100 LLVM_ABI bool operator==(const PointerSpec &Other) const;
101 };
102
104 /// The function pointer alignment is independent of the function alignment.
106 /// The function pointer alignment is a multiple of the function alignment.
108 };
109
110private:
111 bool BigEndian = false;
112 bool VectorsAreElementAligned = false;
113
114 unsigned AllocaAddrSpace = 0;
115 unsigned ProgramAddrSpace = 0;
116 unsigned DefaultGlobalsAddrSpace = 0;
117
118 MaybeAlign StackNaturalAlign;
119 MaybeAlign FunctionPtrAlign;
120 FunctionPtrAlignType TheFunctionPtrAlignType =
122
123 enum ManglingModeT {
124 MM_None,
125 MM_ELF,
126 MM_MachO,
127 MM_WinCOFF,
128 MM_WinCOFFX86,
129 MM_GOFF,
130 MM_Mips,
131 MM_XCOFF
132 };
133 ManglingModeT ManglingMode = MM_None;
134
135 // FIXME: `unsigned char` truncates the value parsed by `parseSpecifier`.
136 SmallVector<unsigned char, 8> LegalIntWidths;
137
138 /// Primitive type specifications. Sorted and uniqued by type bit width.
142
143 /// Pointer type specifications. Sorted and uniqued by address space number.
144 SmallVector<PointerSpec, 8> PointerSpecs;
145
146 /// The string representation used to create this DataLayout
147 std::string StringRepresentation;
148
149 /// Struct type ABI and preferred alignments. The default spec is "a:8:64".
150 Align StructABIAlignment = Align::Constant<1>();
151 Align StructPrefAlignment = Align::Constant<8>();
152
153 // The StructType -> StructLayout map.
154 mutable void *LayoutMap = nullptr;
155
156 /// Sets or updates the specification for the given primitive type.
157 void setPrimitiveSpec(char Specifier, uint32_t BitWidth, Align ABIAlign,
158 Align PrefAlign);
159
160 /// Searches for a pointer specification that matches the given address space.
161 /// Returns the default address space specification if not found.
162 LLVM_ABI const PointerSpec &getPointerSpec(uint32_t AddrSpace) const;
163
164 /// Sets or updates the specification for pointer in the given address space.
165 void setPointerSpec(uint32_t AddrSpace, uint32_t BitWidth, Align ABIAlign,
166 Align PrefAlign, uint32_t IndexBitWidth,
167 bool HasUnstableRepr, bool HasExternalState,
168 StringRef AddrSpaceName, APInt NullPtrValue);
169
170 /// Internal helper to get alignment for integer of given bitwidth.
171 LLVM_ABI Align getIntegerAlignment(uint32_t BitWidth, bool abi_or_pref) const;
172
173 /// Internal helper method that returns requested alignment for type.
174 Align getAlignment(Type *Ty, bool abi_or_pref) const;
175
176 /// getTypeAllocSize for types other than integers and pointers.
177 TypeSize getAggregateOrOtherTypeAllocSize(Type *Ty) const;
178
179 /// Attempts to parse primitive specification ('i', 'f', or 'v').
180 Error parsePrimitiveSpec(StringRef Spec);
181
182 /// Attempts to parse aggregate specification ('a').
183 Error parseAggregateSpec(StringRef Spec);
184
185 /// Attempts to parse pointer specification ('p').
186 Error parsePointerSpec(StringRef Spec,
187 SmallDenseSet<StringRef, 8> &AddrSpaceNames);
188
189 /// Attempts to parse a single specification.
190 Error parseSpecification(StringRef Spec,
191 SmallVectorImpl<unsigned> &NonIntegralAddressSpaces,
192 SmallDenseSet<StringRef, 8> &AddrSpaceNames);
193
194 /// Attempts to parse a data layout string.
195 Error parseLayoutString(StringRef LayoutString);
196
197public:
198 /// Constructs a DataLayout with default values.
200
201 /// Constructs a DataLayout from a specification string.
202 /// WARNING: Aborts execution if the string is malformed. Use parse() instead.
203 LLVM_ABI explicit DataLayout(StringRef LayoutString);
204
205 DataLayout(const DataLayout &DL) { *this = DL; }
206
207 LLVM_ABI ~DataLayout(); // Not virtual, do not subclass this class
208
210
211 LLVM_ABI bool operator==(const DataLayout &Other) const;
212 bool operator!=(const DataLayout &Other) const { return !(*this == Other); }
213
214 /// Parse a data layout string and return the layout. Return an error
215 /// description on failure.
216 LLVM_ABI static Expected<DataLayout> parse(StringRef LayoutString);
217
218 /// Layout endianness...
219 bool isLittleEndian() const { return !BigEndian; }
220 bool isBigEndian() const { return BigEndian; }
221
222 /// Whether vectors are element aligned, rather than naturally aligned.
223 bool vectorsAreElementAligned() const { return VectorsAreElementAligned; }
224
225 /// Returns the string representation of the DataLayout.
226 ///
227 /// This representation is in the same format accepted by the string
228 /// constructor above. This should not be used to compare two DataLayout as
229 /// different string can represent the same layout.
230 const std::string &getStringRepresentation() const {
231 return StringRepresentation;
232 }
233
234 /// Test if the DataLayout was constructed from an empty string.
235 bool isDefault() const { return StringRepresentation.empty(); }
236
237 /// Returns true if the specified type is known to be a native integer
238 /// type supported by the CPU.
239 ///
240 /// For example, i64 is not native on most 32-bit CPUs and i37 is not native
241 /// on any known one. This returns false if the integer width is not legal.
242 ///
243 /// The width is specified in bits.
244 bool isLegalInteger(uint64_t Width) const {
245 return llvm::is_contained(LegalIntWidths, Width);
246 }
247
248 bool isIllegalInteger(uint64_t Width) const { return !isLegalInteger(Width); }
249
250 /// Returns the natural stack alignment, or MaybeAlign() if one wasn't
251 /// specified.
252 MaybeAlign getStackAlignment() const { return StackNaturalAlign; }
253
254 unsigned getAllocaAddrSpace() const { return AllocaAddrSpace; }
255
257 return PointerType::get(Ctx, AllocaAddrSpace);
258 }
259
260 /// Returns the alignment of function pointers, which may or may not be
261 /// related to the alignment of functions.
262 /// \see getFunctionPtrAlignType
263 MaybeAlign getFunctionPtrAlign() const { return FunctionPtrAlign; }
264
265 /// Return the type of function pointer alignment.
266 /// \see getFunctionPtrAlign
268 return TheFunctionPtrAlignType;
269 }
270
271 unsigned getProgramAddressSpace() const { return ProgramAddrSpace; }
273 return DefaultGlobalsAddrSpace;
274 }
275
277 return ManglingMode == MM_WinCOFFX86;
278 }
279
280 /// Returns true if symbols with leading question marks should not receive IR
281 /// mangling. True for Windows mangling modes.
283 return ManglingMode == MM_WinCOFF || ManglingMode == MM_WinCOFFX86;
284 }
285
286 bool hasLinkerPrivateGlobalPrefix() const { return ManglingMode == MM_MachO; }
287
289 if (ManglingMode == MM_MachO)
290 return "l";
291 return "";
292 }
293
294 char getGlobalPrefix() const {
295 switch (ManglingMode) {
296 case MM_None:
297 case MM_ELF:
298 case MM_GOFF:
299 case MM_Mips:
300 case MM_WinCOFF:
301 case MM_XCOFF:
302 return '\0';
303 case MM_MachO:
304 case MM_WinCOFFX86:
305 return '_';
306 }
307 llvm_unreachable("invalid mangling mode");
308 }
309
311 switch (ManglingMode) {
312 case MM_None:
313 return "";
314 case MM_ELF:
315 case MM_WinCOFF:
316 return ".L";
317 case MM_GOFF:
318 return "L#";
319 case MM_Mips:
320 return "$";
321 case MM_MachO:
322 case MM_WinCOFFX86:
323 return "L";
324 case MM_XCOFF:
325 return "L..";
326 }
327 llvm_unreachable("invalid mangling mode");
328 }
329
330 /// Returns true if the specified type fits in a native integer type
331 /// supported by the CPU.
332 ///
333 /// For example, if the CPU only supports i32 as a native integer type, then
334 /// i27 fits in a legal integer type but i45 does not.
335 bool fitsInLegalInteger(unsigned Width) const {
336 for (unsigned LegalIntWidth : LegalIntWidths)
337 if (Width <= LegalIntWidth)
338 return true;
339 return false;
340 }
341
342 /// Layout pointer alignment.
343 LLVM_ABI Align getPointerABIAlignment(unsigned AS) const;
344
345 LLVM_ABI StringRef getAddressSpaceName(unsigned AS) const;
346
347 LLVM_ABI std::optional<unsigned> getNamedAddressSpace(StringRef Name) const;
348
349 /// Return target's alignment for stack-based pointers
350 /// FIXME: The defaults need to be removed once all of
351 /// the backends/clients are updated.
352 LLVM_ABI Align getPointerPrefAlignment(unsigned AS = 0) const;
353
354 /// The pointer representation size in bytes, rounded up to a whole number of
355 /// bytes. The difference between this function and getAddressSize() is that
356 /// this one returns the size of the entire pointer representation (including
357 /// metadata bits for fat pointers) and the latter only returns the number of
358 /// address bits.
359 /// \sa DataLayout::getAddressSizeInBits
360 /// FIXME: The defaults need to be removed once all of
361 /// the backends/clients are updated.
362 LLVM_ABI unsigned getPointerSize(unsigned AS = 0) const;
363
364 /// The index size in bytes used for address calculation, rounded up to a
365 /// whole number of bytes. This not only defines the size used in
366 /// getelementptr operations, but also the size of addresses in this \p AS.
367 /// For example, a 64-bit CHERI-enabled target has 128-bit pointers of which
368 /// only 64 are used to represent the address and the remaining ones are used
369 /// for metadata such as bounds and access permissions. In this case
370 /// getPointerSize() returns 16, but getIndexSize() returns 8.
371 /// To help with code understanding, the alias getAddressSize() can be used
372 /// instead of getIndexSize() to clarify that an address width is needed.
373 LLVM_ABI unsigned getIndexSize(unsigned AS) const;
374
375 /// The integral size of a pointer in a given address space in bytes, which
376 /// is defined to be the same as getIndexSize(). This exists as a separate
377 /// function to make it clearer when reading code that the size of an address
378 /// is being requested. While targets exist where index size and the
379 /// underlying address width are not identical (e.g. AMDGPU fat pointers with
380 /// 48-bit addresses and 32-bit offsets indexing), there is currently no need
381 /// to differentiate these properties in LLVM.
382 /// \sa DataLayout::getIndexSize
383 /// \sa DataLayout::getAddressSizeInBits
384 unsigned getAddressSize(unsigned AS) const { return getIndexSize(AS); }
385
386 /// Return the address spaces with special pointer semantics (such as being
387 /// unstable or non-integral).
389 SmallVector<unsigned, 8> AddrSpaces;
390 for (const PointerSpec &PS : PointerSpecs) {
391 if (PS.HasUnstableRepresentation || PS.HasExternalState ||
392 PS.BitWidth != PS.IndexBitWidth)
393 AddrSpaces.push_back(PS.AddrSpace);
394 }
395 return AddrSpaces;
396 }
397
398 /// Returns whether this address space has a non-integral pointer
399 /// representation, i.e. the pointer is not just an integer address but some
400 /// other bitwise representation. When true, passes cannot assume that all
401 /// bits of the representation map directly to the allocation address.
402 /// NOTE: This also returns true for "unstable" pointers where the
403 /// representation may be just an address, but this value can change at any
404 /// given time (e.g. due to copying garbage collection).
405 /// Examples include AMDGPU buffer descriptors with a 128-bit fat pointer
406 /// and a 32-bit offset or CHERI capabilities that contain bounds, permissions
407 /// and an out-of-band validity bit.
408 ///
409 /// In general, more specialized functions such as mustNotIntroduceIntToPtr(),
410 /// mustNotIntroducePtrToInt(), or hasExternalState() should be
411 /// preferred over this one when reasoning about the behavior of IR
412 /// analysis/transforms.
413 /// TODO: should remove/deprecate this once all uses have migrated.
414 bool isNonIntegralAddressSpace(unsigned AddrSpace) const {
415 const auto &PS = getPointerSpec(AddrSpace);
416 return PS.BitWidth != PS.IndexBitWidth || PS.HasUnstableRepresentation ||
417 PS.HasExternalState;
418 }
419
420 /// Returns whether this address space has an "unstable" pointer
421 /// representation. The bitwise pattern of such pointers is allowed to change
422 /// in a target-specific way. For example, this could be used for copying
423 /// garbage collection where the garbage collector could update the pointer
424 /// value as part of the collection sweep.
425 bool hasUnstableRepresentation(unsigned AddrSpace) const {
426 return getPointerSpec(AddrSpace).HasUnstableRepresentation;
427 }
429 auto *PTy = dyn_cast<PointerType>(Ty->getScalarType());
430 return PTy && hasUnstableRepresentation(PTy->getPointerAddressSpace());
431 }
432
433 /// Returns whether this address space has external state (implies having
434 /// a non-integral pointer representation).
435 /// These pointer types must be loaded and stored using appropriate
436 /// instructions and cannot use integer loads/stores as this would not
437 /// propagate the out-of-band state. An example of such a pointer type is a
438 /// CHERI capability that contain bounds, permissions and an out-of-band
439 /// validity bit that is invalidated whenever an integer/FP store is performed
440 /// to the associated memory location.
441 bool hasExternalState(unsigned AddrSpace) const {
442 return getPointerSpec(AddrSpace).HasExternalState;
443 }
444 bool hasExternalState(Type *Ty) const {
445 auto *PTy = dyn_cast<PointerType>(Ty->getScalarType());
446 return PTy && hasExternalState(PTy->getPointerAddressSpace());
447 }
448
449 /// Returns the null pointer bit pattern for the given address space.
450 APInt getNullPtrValue(unsigned AS) const {
451 return getPointerSpec(AS).NullPtrValue;
452 }
453
454 /// Returns whether passes must avoid introducing `inttoptr` instructions
455 /// for this address space (unless they have target-specific knowledge).
456 ///
457 /// This is currently the case for non-integral pointer representations with
458 /// external state (hasExternalState()) since `inttoptr` cannot recreate the
459 /// external state bits.
460 /// New `inttoptr` instructions should also be avoided for "unstable" bitwise
461 /// representations (hasUnstableRepresentation()) unless the pass knows it is
462 /// within a critical section that retains the current representation.
463 bool mustNotIntroduceIntToPtr(unsigned AddrSpace) const {
464 return hasUnstableRepresentation(AddrSpace) || hasExternalState(AddrSpace);
465 }
466
467 /// Returns whether passes must avoid introducing `ptrtoint` instructions
468 /// for this address space (unless they have target-specific knowledge).
469 ///
470 /// This is currently the case for pointer address spaces that have an
471 /// "unstable" representation (hasUnstableRepresentation()) since the
472 /// bitwise pattern of such pointers could change unless the pass knows it is
473 /// within a critical section that retains the current representation.
474 bool mustNotIntroducePtrToInt(unsigned AddrSpace) const {
475 return hasUnstableRepresentation(AddrSpace);
476 }
477
481
483 auto *PTy = dyn_cast<PointerType>(Ty->getScalarType());
484 return PTy && isNonIntegralPointerType(PTy);
485 }
486
488 auto *PTy = dyn_cast<PointerType>(Ty->getScalarType());
489 return PTy && mustNotIntroducePtrToInt(PTy->getPointerAddressSpace());
490 }
491
493 auto *PTy = dyn_cast<PointerType>(Ty->getScalarType());
494 return PTy && mustNotIntroduceIntToPtr(PTy->getPointerAddressSpace());
495 }
496
497 /// The size in bits of the pointer representation in a given address space.
498 /// This is not necessarily the same as the integer address of a pointer (e.g.
499 /// for fat pointers).
500 /// \sa DataLayout::getAddressSizeInBits()
501 /// FIXME: The defaults need to be removed once all of
502 /// the backends/clients are updated.
503 unsigned getPointerSizeInBits(unsigned AS = 0) const {
504 return getPointerSpec(AS).BitWidth;
505 }
506
507 /// The size in bits of indices used for address calculation in getelementptr
508 /// and for addresses in the given AS. See getIndexSize() for more
509 /// information.
510 /// \sa DataLayout::getAddressSizeInBits()
511 unsigned getIndexSizeInBits(unsigned AS) const {
512 return getPointerSpec(AS).IndexBitWidth;
513 }
514
515 /// The size in bits of an address in for the given AS. This is defined to
516 /// return the same value as getIndexSizeInBits() since there is currently no
517 /// target that requires these two properties to have different values. See
518 /// getIndexSize() for more information.
519 /// \sa DataLayout::getIndexSizeInBits()
520 unsigned getAddressSizeInBits(unsigned AS) const {
521 return getIndexSizeInBits(AS);
522 }
523
524 /// The pointer representation size in bits for this type. If this function is
525 /// called with a pointer type, then the type size of the pointer is returned.
526 /// If this function is called with a vector of pointers, then the type size
527 /// of the pointer is returned. This should only be called with a pointer or
528 /// vector of pointers.
529 LLVM_ABI unsigned getPointerTypeSizeInBits(Type *) const;
530
531 /// The size in bits of the index used in GEP calculation for this type.
532 /// The function should be called with pointer or vector of pointers type.
533 /// This is defined to return the same value as getAddressSizeInBits(),
534 /// but separate functions exist for code clarity.
535 LLVM_ABI unsigned getIndexTypeSizeInBits(Type *Ty) const;
536
537 /// The size in bits of an address for this type.
538 /// This is defined to return the same value as getIndexTypeSizeInBits(),
539 /// but separate functions exist for code clarity.
540 unsigned getAddressSizeInBits(Type *Ty) const {
541 return getIndexTypeSizeInBits(Ty);
542 }
543
544 unsigned getPointerTypeSize(Type *Ty) const {
545 return getPointerTypeSizeInBits(Ty) / 8;
546 }
547
548 /// Size examples:
549 ///
550 /// Type SizeInBits StoreSizeInBits AllocSizeInBits[*]
551 /// ---- ---------- --------------- ---------------
552 /// i1 1 8 8
553 /// i8 8 8 8
554 /// i19 19 24 32
555 /// i32 32 32 32
556 /// i100 100 104 128
557 /// i128 128 128 128
558 /// Float 32 32 32
559 /// Double 64 64 64
560 /// X86_FP80 80 80 96
561 ///
562 /// [*] The alloc size depends on the alignment, and thus on the target.
563 /// These values are for x86-32 linux.
564
565 /// Returns the number of bits necessary to hold the specified type.
566 ///
567 /// If Ty is a scalable vector type, the scalable property will be set and
568 /// the runtime size will be a positive integer multiple of the base size.
569 ///
570 /// For example, returns 36 for i36 and 80 for x86_fp80. The type passed must
571 /// have a size (Type::isSized() must return true).
573
574 /// Returns the maximum number of bytes that may be overwritten by
575 /// storing the specified type.
576 ///
577 /// If Ty is a scalable vector type, the scalable property will be set and
578 /// the runtime size will be a positive integer multiple of the base size.
579 ///
580 /// For example, returns 5 for i36 and 10 for x86_fp80.
582 TypeSize StoreSizeInBits = getTypeStoreSizeInBits(Ty);
583 return {StoreSizeInBits.getKnownMinValue() / 8,
584 StoreSizeInBits.isScalable()};
585 }
586
587 /// Returns the maximum number of bits that may be overwritten by
588 /// storing the specified type; always a multiple of 8.
589 ///
590 /// If Ty is a scalable vector type, the scalable property will be set and
591 /// the runtime size will be a positive integer multiple of the base size.
592 ///
593 /// For example, returns 40 for i36 and 80 for x86_fp80.
595 TypeSize BaseSize = getTypeSizeInBits(Ty);
596 uint64_t AlignedSizeInBits =
597 alignToPowerOf2(BaseSize.getKnownMinValue(), 8);
598 return {AlignedSizeInBits, BaseSize.isScalable()};
599 }
600
601 /// Returns true if no extra padding bits are needed when storing the
602 /// specified type.
603 ///
604 /// For example, returns false for i19 that has a 24-bit store size.
607 }
608
609 /// Returns the offset in bytes between successive objects of the
610 /// specified type, including alignment padding.
611 ///
612 /// If Ty is a scalable vector type, the scalable property will be set and
613 /// the runtime size will be a positive integer multiple of the base size.
614 ///
615 /// This is the amount that alloca reserves for this type. For example,
616 /// returns 12 or 16 for x86_fp80, depending on alignment.
618
619 /// Returns the offset in bits between successive objects of the
620 /// specified type, including alignment padding; always a multiple of 8.
621 ///
622 /// If Ty is a scalable vector type, the scalable property will be set and
623 /// the runtime size will be a positive integer multiple of the base size.
624 ///
625 /// This is the amount that alloca reserves for this type. For example,
626 /// returns 96 or 128 for x86_fp80, depending on alignment.
628 return 8 * getTypeAllocSize(Ty);
629 }
630
631 /// Returns the minimum ABI-required alignment for the specified type.
633
634 /// Helper function to return `Alignment` if it's set or the result of
635 /// `getABITypeAlign(Ty)`, in any case the result is a valid alignment.
637 Type *Ty) const {
638 return Alignment ? *Alignment : getABITypeAlign(Ty);
639 }
640
641 /// Returns the minimum ABI-required alignment for an integer type of
642 /// the specified bitwidth.
644 return getIntegerAlignment(BitWidth, /* abi_or_pref */ true);
645 }
646
647 /// Returns the preferred stack/global alignment for the specified
648 /// type.
649 ///
650 /// This is always at least as good as the ABI alignment.
652
653 /// Returns a byte type with the same size of a pointer in the given address
654 /// space.
656 unsigned AddressSpace = 0) const;
657
658 /// Returns an integer type with size at least as big as that of a
659 /// pointer in the given address space.
661 unsigned AddressSpace = 0) const;
662
663 /// Returns an integer (vector of integer) type with size at least as
664 /// big as that of a pointer of the given pointer (vector of pointer) type.
666
667 /// Returns a byte (vector of byte) type with the same size of a pointer of
668 /// the given pointer (vector of pointer) type.
670
671 /// Returns the smallest integer type with size at least as big as
672 /// Width bits.
674 unsigned Width = 0) const;
675
676 /// Returns the largest legal integer type, or null if none are set.
678 unsigned LargestSize = getLargestLegalIntTypeSizeInBits();
679 return (LargestSize == 0) ? nullptr : Type::getIntNTy(C, LargestSize);
680 }
681
682 /// Returns the size of largest legal integer type size, or 0 if none
683 /// are set.
685
686 /// Returns the type of a GEP index in \p AddressSpace.
687 /// If it was not specified explicitly, it will be the integer type of the
688 /// pointer width - IntPtrType.
690 unsigned AddressSpace) const;
691 /// Returns the type of an address in \p AddressSpace
695
696 /// Returns the type of a GEP index.
697 /// If it was not specified explicitly, it will be the integer type of the
698 /// pointer width - IntPtrType.
699 LLVM_ABI Type *getIndexType(Type *PtrTy) const;
700 /// Returns the type of an address in \p AddressSpace
701 Type *getAddressType(Type *PtrTy) const { return getIndexType(PtrTy); }
702
703 /// Returns the offset from the beginning of the type for the specified
704 /// indices.
705 ///
706 /// Note that this takes the element type, not the pointer type.
707 /// This is used to implement getelementptr.
709 ArrayRef<Value *> Indices) const;
710
711 /// Get GEP indices to access Offset inside ElemTy. ElemTy is updated to be
712 /// the result element type and Offset to be the residual offset.
714 APInt &Offset) const;
715
716 /// Get single GEP index to access Offset inside ElemTy. Returns std::nullopt
717 /// if index cannot be computed, e.g. because the type is not an aggregate.
718 /// ElemTy is updated to be the result element type and Offset to be the
719 /// residual offset.
720 LLVM_ABI std::optional<APInt> getGEPIndexForOffset(Type *&ElemTy,
721 APInt &Offset) const;
722
723 /// Returns a StructLayout object, indicating the alignment of the
724 /// struct, its size, and the offsets of its fields.
725 ///
726 /// Note that this information is lazily cached.
728
729 /// Returns the preferred alignment of the specified global.
730 ///
731 /// This includes an explicitly requested alignment (if the global has one).
733};
734
736 return reinterpret_cast<DataLayout *>(P);
737}
738
740 return reinterpret_cast<LLVMTargetDataRef>(const_cast<DataLayout *>(P));
741}
742
743/// Used to lazily calculate structure layout information for a target machine,
744/// based on the DataLayout structure.
745class StructLayout final : private TrailingObjects<StructLayout, TypeSize> {
746 friend TrailingObjects;
747
748 TypeSize StructSize;
749 Align StructAlignment;
750 unsigned IsPadded : 1;
751 unsigned NumElements : 31;
752
753public:
754 TypeSize getSizeInBytes() const { return StructSize; }
755
756 TypeSize getSizeInBits() const { return 8 * StructSize; }
757
758 Align getAlignment() const { return StructAlignment; }
759
760 /// Returns whether the struct has padding or not between its fields.
761 /// NB: Padding in nested element is not taken into account.
762 bool hasPadding() const { return IsPadded; }
763
764 /// Given a valid byte offset into the structure, returns the structure
765 /// index that contains it.
766 LLVM_ABI unsigned getElementContainingOffset(uint64_t FixedOffset) const;
767
771
773 return getTrailingObjects(NumElements);
774 }
775
776 TypeSize getElementOffset(unsigned Idx) const {
777 assert(Idx < NumElements && "Invalid element idx!");
778 return getMemberOffsets()[Idx];
779 }
780
781 TypeSize getElementOffsetInBits(unsigned Idx) const {
782 return getElementOffset(Idx) * 8;
783 }
784
785private:
786 friend class DataLayout; // Only DataLayout can create this class
787
788 StructLayout(StructType *ST, const DataLayout &DL);
789};
790
791// The implementation of this method is provided inline as it is particularly
792// well suited to constant folding when called on a specific Type subclass.
794 assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
795 switch (Ty->getTypeID()) {
796 case Type::LabelTyID:
799 return TypeSize::getFixed(
800 getPointerSizeInBits(Ty->getPointerAddressSpace()));
801 case Type::ArrayTyID: {
802 ArrayType *ATy = cast<ArrayType>(Ty);
803 return ATy->getNumElements() *
805 }
806 case Type::StructTyID:
807 // Get the layout annotation... which is lazily created on demand.
809 case Type::ByteTyID:
810 return TypeSize::getFixed(Ty->getByteBitWidth());
812 return TypeSize::getFixed(Ty->getIntegerBitWidth());
813 case Type::HalfTyID:
814 case Type::BFloatTyID:
815 return TypeSize::getFixed(16);
816 case Type::FloatTyID:
817 return TypeSize::getFixed(32);
818 case Type::DoubleTyID:
819 return TypeSize::getFixed(64);
821 case Type::FP128TyID:
822 return TypeSize::getFixed(128);
824 return TypeSize::getFixed(8192);
825 // In memory objects this is always aligned to a higher boundary, but
826 // only 80 bits contain information.
828 return TypeSize::getFixed(80);
831 VectorType *VTy = cast<VectorType>(Ty);
832 auto EltCnt = VTy->getElementCount();
833 uint64_t MinBits = EltCnt.getKnownMinValue() *
835 return TypeSize(MinBits, EltCnt.isScalable());
836 }
837 case Type::TargetExtTyID: {
838 Type *LayoutTy = cast<TargetExtType>(Ty)->getLayoutType();
839 return getTypeSizeInBits(LayoutTy);
840 }
841 default:
842 llvm_unreachable("DataLayout::getTypeSizeInBits(): Unsupported type");
843 }
844}
845
846} // end namespace llvm
847
848#endif // LLVM_IR_DATALAYOUT_H
assert(UImm &&(UImm !=~static_cast< T >(0)) &&"Invalid immediate!")
uint64_t uint64_t
This file implements a class to represent arbitrary precision integral constant values and operations...
MachineBasicBlock MachineBasicBlock::iterator DebugLoc DL
static GCRegistry::Add< ShadowStackGC > C("shadow-stack", "Very portable GC for uncooperative code generators")
#define LLVM_ABI
Definition Compiler.h:211
This file defines the DenseSet and SmallDenseSet classes.
const uint64_t BitWidth
#define P(N)
This file contains some templates that are useful if you are working with the STL at all.
This file defines the SmallVector class.
This header defines support for implementing classes that have some trailing object (or arrays of obj...
static uint32_t getAlignment(const MCSectionCOFF &Sec)
Class for arbitrary precision integers.
Definition APInt.h:78
Represent a constant reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:40
Class to represent array types.
uint64_t getNumElements() const
Type * getElementType() const
Class to represent byte types.
A parsed version of the target data layout string in and methods for querying it.
Definition DataLayout.h:63
unsigned getProgramAddressSpace() const
Definition DataLayout.h:271
bool typeSizeEqualsStoreSize(Type *Ty) const
Returns true if no extra padding bits are needed when storing the specified type.
Definition DataLayout.h:605
LLVM_ABI std::optional< unsigned > getNamedAddressSpace(StringRef Name) const
bool hasLinkerPrivateGlobalPrefix() const
Definition DataLayout.h:286
bool hasExternalState(unsigned AddrSpace) const
Returns whether this address space has external state (implies having a non-integral pointer represen...
Definition DataLayout.h:441
StringRef getLinkerPrivateGlobalPrefix() const
Definition DataLayout.h:288
LLVM_ABI StringRef getAddressSpaceName(unsigned AS) const
unsigned getPointerSizeInBits(unsigned AS=0) const
The size in bits of the pointer representation in a given address space.
Definition DataLayout.h:503
bool isNonIntegralPointerType(Type *Ty) const
Definition DataLayout.h:482
@ MultipleOfFunctionAlign
The function pointer alignment is a multiple of the function alignment.
Definition DataLayout.h:107
@ Independent
The function pointer alignment is independent of the function alignment.
Definition DataLayout.h:105
LLVM_ABI SmallVector< APInt > getGEPIndicesForOffset(Type *&ElemTy, APInt &Offset) const
Get GEP indices to access Offset inside ElemTy.
bool isLittleEndian() const
Layout endianness...
Definition DataLayout.h:219
bool isDefault() const
Test if the DataLayout was constructed from an empty string.
Definition DataLayout.h:235
Type * getAddressType(Type *PtrTy) const
Returns the type of an address in AddressSpace.
Definition DataLayout.h:701
TypeSize getTypeStoreSizeInBits(Type *Ty) const
Returns the maximum number of bits that may be overwritten by storing the specified type; always a mu...
Definition DataLayout.h:594
LLVM_ABI unsigned getLargestLegalIntTypeSizeInBits() const
Returns the size of largest legal integer type size, or 0 if none are set.
unsigned getAddressSizeInBits(unsigned AS) const
The size in bits of an address in for the given AS.
Definition DataLayout.h:520
bool isLegalInteger(uint64_t Width) const
Returns true if the specified type is known to be a native integer type supported by the CPU.
Definition DataLayout.h:244
unsigned getDefaultGlobalsAddressSpace() const
Definition DataLayout.h:272
FunctionPtrAlignType getFunctionPtrAlignType() const
Return the type of function pointer alignment.
Definition DataLayout.h:267
Align getABIIntegerTypeAlignment(unsigned BitWidth) const
Returns the minimum ABI-required alignment for an integer type of the specified bitwidth.
Definition DataLayout.h:643
IntegerType * getAddressType(LLVMContext &C, unsigned AddressSpace) const
Returns the type of an address in AddressSpace.
Definition DataLayout.h:692
bool vectorsAreElementAligned() const
Whether vectors are element aligned, rather than naturally aligned.
Definition DataLayout.h:223
bool doNotMangleLeadingQuestionMark() const
Returns true if symbols with leading question marks should not receive IR mangling.
Definition DataLayout.h:282
LLVM_ABI unsigned getIndexSize(unsigned AS) const
The index size in bytes used for address calculation, rounded up to a whole number of bytes.
bool mustNotIntroduceIntToPtr(unsigned AddrSpace) const
Returns whether passes must avoid introducing inttoptr instructions for this address space (unless th...
Definition DataLayout.h:463
LLVM_ABI const StructLayout * getStructLayout(StructType *Ty) const
Returns a StructLayout object, indicating the alignment of the struct, its size, and the offsets of i...
LLVM_ABI DataLayout()
Constructs a DataLayout with default values.
bool hasUnstableRepresentation(unsigned AddrSpace) const
Returns whether this address space has an "unstable" pointer representation.
Definition DataLayout.h:425
bool mustNotIntroduceIntToPtr(Type *Ty) const
Definition DataLayout.h:492
unsigned getAddressSizeInBits(Type *Ty) const
The size in bits of an address for this type.
Definition DataLayout.h:540
bool mustNotIntroducePtrToInt(Type *Ty) const
Definition DataLayout.h:487
LLVM_ABI IntegerType * getIntPtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns an integer type with size at least as big as that of a pointer in the given address space.
unsigned getPointerTypeSize(Type *Ty) const
Definition DataLayout.h:544
LLVM_ABI Align getABITypeAlign(Type *Ty) const
Returns the minimum ABI-required alignment for the specified type.
bool isNonIntegralAddressSpace(unsigned AddrSpace) const
Returns whether this address space has a non-integral pointer representation, i.e.
Definition DataLayout.h:414
bool isIllegalInteger(uint64_t Width) const
Definition DataLayout.h:248
LLVM_ABI unsigned getIndexTypeSizeInBits(Type *Ty) const
The size in bits of the index used in GEP calculation for this type.
PointerType * getAllocaPtrType(LLVMContext &Ctx) const
Definition DataLayout.h:256
LLVM_ABI unsigned getPointerTypeSizeInBits(Type *) const
The pointer representation size in bits for this type.
bool isBigEndian() const
Definition DataLayout.h:220
SmallVector< unsigned, 8 > getNonStandardAddressSpaces() const
Return the address spaces with special pointer semantics (such as being unstable or non-integral).
Definition DataLayout.h:388
LLVM_ABI ByteType * getBytePtrType(LLVMContext &C, unsigned AddressSpace=0) const
Returns a byte type with the same size of a pointer in the given address space.
MaybeAlign getStackAlignment() const
Returns the natural stack alignment, or MaybeAlign() if one wasn't specified.
Definition DataLayout.h:252
unsigned getAllocaAddrSpace() const
Definition DataLayout.h:254
LLVM_ABI DataLayout & operator=(const DataLayout &Other)
LLVM_ABI IntegerType * getIndexType(LLVMContext &C, unsigned AddressSpace) const
Returns the type of a GEP index in AddressSpace.
LLVM_ABI TypeSize getTypeAllocSize(Type *Ty) const
Returns the offset in bytes between successive objects of the specified type, including alignment pad...
APInt getNullPtrValue(unsigned AS) const
Returns the null pointer bit pattern for the given address space.
Definition DataLayout.h:450
StringRef getInternalSymbolPrefix() const
Definition DataLayout.h:310
bool mustNotIntroducePtrToInt(unsigned AddrSpace) const
Returns whether passes must avoid introducing ptrtoint instructions for this address space (unless th...
Definition DataLayout.h:474
LLVM_ABI std::optional< APInt > getGEPIndexForOffset(Type *&ElemTy, APInt &Offset) const
Get single GEP index to access Offset inside ElemTy.
LLVM_ABI Type * getSmallestLegalIntType(LLVMContext &C, unsigned Width=0) const
Returns the smallest integer type with size at least as big as Width bits.
bool hasExternalState(Type *Ty) const
Definition DataLayout.h:444
LLVM_ABI Align getPreferredAlign(const GlobalVariable *GV) const
Returns the preferred alignment of the specified global.
bool fitsInLegalInteger(unsigned Width) const
Returns true if the specified type fits in a native integer type supported by the CPU.
Definition DataLayout.h:335
bool hasMicrosoftFastStdCallMangling() const
Definition DataLayout.h:276
bool hasUnstableRepresentation(Type *Ty) const
Definition DataLayout.h:428
LLVM_ABI ~DataLayout()
LLVM_ABI unsigned getPointerSize(unsigned AS=0) const
The pointer representation size in bytes, rounded up to a whole number of bytes.
bool isNonIntegralPointerType(PointerType *PT) const
Definition DataLayout.h:478
LLVM_ABI Align getPointerPrefAlignment(unsigned AS=0) const
Return target's alignment for stack-based pointers FIXME: The defaults need to be removed once all of...
unsigned getIndexSizeInBits(unsigned AS) const
The size in bits of indices used for address calculation in getelementptr and for addresses in the gi...
Definition DataLayout.h:511
Type * getLargestLegalIntType(LLVMContext &C) const
Returns the largest legal integer type, or null if none are set.
Definition DataLayout.h:677
MaybeAlign getFunctionPtrAlign() const
Returns the alignment of function pointers, which may or may not be related to the alignment of funct...
Definition DataLayout.h:263
TypeSize getTypeSizeInBits(Type *Ty) const
Size examples:
Definition DataLayout.h:793
TypeSize getTypeStoreSize(Type *Ty) const
Returns the maximum number of bytes that may be overwritten by storing the specified type.
Definition DataLayout.h:581
bool operator!=(const DataLayout &Other) const
Definition DataLayout.h:212
DataLayout(const DataLayout &DL)
Definition DataLayout.h:205
TypeSize getTypeAllocSizeInBits(Type *Ty) const
Returns the offset in bits between successive objects of the specified type, including alignment padd...
Definition DataLayout.h:627
char getGlobalPrefix() const
Definition DataLayout.h:294
LLVM_ABI bool operator==(const DataLayout &Other) const
LLVM_ABI int64_t getIndexedOffsetInType(Type *ElemTy, ArrayRef< Value * > Indices) const
Returns the offset from the beginning of the type for the specified indices.
const std::string & getStringRepresentation() const
Returns the string representation of the DataLayout.
Definition DataLayout.h:230
unsigned getAddressSize(unsigned AS) const
The integral size of a pointer in a given address space in bytes, which is defined to be the same as ...
Definition DataLayout.h:384
Align getValueOrABITypeAlignment(MaybeAlign Alignment, Type *Ty) const
Helper function to return Alignment if it's set or the result of getABITypeAlign(Ty),...
Definition DataLayout.h:636
LLVM_ABI Align getPointerABIAlignment(unsigned AS) const
Layout pointer alignment.
LLVM_ABI Align getPrefTypeAlign(Type *Ty) const
Returns the preferred stack/global alignment for the specified type.
static LLVM_ABI Expected< DataLayout > parse(StringRef LayoutString)
Parse a data layout string and return the layout.
Tagged union holding either a T or a Error.
Definition Error.h:485
Class to represent integer types.
This is an important class for using LLVM in a threaded context.
Definition LLVMContext.h:76
Represent a mutable reference to an array (0 or more elements consecutively in memory),...
Definition ArrayRef.h:294
Class to represent pointers.
static LLVM_ABI PointerType * get(LLVMContext &C, unsigned AddressSpace)
This constructs an opaque pointer to an object in a numbered address space.
Definition Type.cpp:882
unsigned getAddressSpace() const
Return the address space of the Pointer type.
void push_back(const T &Elt)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small.
Represent a constant reference to a string, i.e.
Definition StringRef.h:56
Used to lazily calculate structure layout information for a target machine, based on the DataLayout s...
Definition DataLayout.h:745
TypeSize getSizeInBytes() const
Definition DataLayout.h:754
bool hasPadding() const
Returns whether the struct has padding or not between its fields.
Definition DataLayout.h:762
MutableArrayRef< TypeSize > getMemberOffsets()
Definition DataLayout.h:768
LLVM_ABI unsigned getElementContainingOffset(uint64_t FixedOffset) const
Given a valid byte offset into the structure, returns the structure index that contains it.
TypeSize getElementOffset(unsigned Idx) const
Definition DataLayout.h:776
friend class DataLayout
Definition DataLayout.h:786
ArrayRef< TypeSize > getMemberOffsets() const
Definition DataLayout.h:772
TypeSize getSizeInBits() const
Definition DataLayout.h:756
TypeSize getElementOffsetInBits(unsigned Idx) const
Definition DataLayout.h:781
Align getAlignment() const
Definition DataLayout.h:758
Class to represent struct types.
static constexpr TypeSize getFixed(ScalarTy ExactSize)
Definition TypeSize.h:352
The instances of the Type class are immutable: once they are created, they are never changed.
Definition Type.h:46
@ X86_AMXTyID
AMX vectors (8192 bits, X86 specific)
Definition Type.h:67
@ ArrayTyID
Arrays.
Definition Type.h:76
@ HalfTyID
16-bit floating point type
Definition Type.h:57
@ TargetExtTyID
Target extension type.
Definition Type.h:80
@ ScalableVectorTyID
Scalable SIMD vector type.
Definition Type.h:78
@ LabelTyID
Labels.
Definition Type.h:65
@ FloatTyID
32-bit floating point type
Definition Type.h:59
@ StructTyID
Structures.
Definition Type.h:75
@ IntegerTyID
Arbitrary bit width integers.
Definition Type.h:71
@ FixedVectorTyID
Fixed width SIMD vector type.
Definition Type.h:77
@ BFloatTyID
16-bit floating point type (7-bit significand)
Definition Type.h:58
@ DoubleTyID
64-bit floating point type
Definition Type.h:60
@ X86_FP80TyID
80-bit floating point type (X87)
Definition Type.h:61
@ PPC_FP128TyID
128-bit floating point type (two 64-bits, PowerPC)
Definition Type.h:63
@ ByteTyID
Arbitrary bit width bytes.
Definition Type.h:72
@ PointerTyID
Pointers.
Definition Type.h:74
@ FP128TyID
128-bit floating point type (112-bit significand)
Definition Type.h:62
static LLVM_ABI IntegerType * getIntNTy(LLVMContext &C, unsigned N)
Definition Type.cpp:298
LLVM Value Representation.
Definition Value.h:75
Base class of all SIMD vector types.
ElementCount getElementCount() const
Return an ElementCount instance to represent the (possibly scalable) number of elements in the vector...
Type * getElementType() const
constexpr ScalarTy getFixedValue() const
Definition TypeSize.h:201
constexpr bool isScalable() const
Returns whether the quantity is scaled by a runtime quantity (vscale).
Definition TypeSize.h:169
constexpr ScalarTy getKnownMinValue() const
Returns the minimum value this quantity can represent.
Definition TypeSize.h:166
struct LLVMOpaqueTargetData * LLVMTargetDataRef
Definition Core.h:34
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
This is an optimization pass for GlobalISel generic memory operations.
@ Offset
Definition DWP.cpp:577
decltype(auto) dyn_cast(const From &Val)
dyn_cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:643
constexpr T alignToPowerOf2(U Value, V Align)
Will overflow only if result is not representable in T.
Definition MathExtras.h:493
class LLVM_GSL_OWNER SmallVector
Forward declaration of SmallVector so that calculateSmallVectorDefaultInlinedElements can reference s...
@ Other
Any other memory.
Definition ModRef.h:68
Attribute unwrap(LLVMAttributeRef Attr)
Definition Attributes.h:394
constexpr unsigned BitWidth
decltype(auto) cast(const From &Val)
cast<X> - Return the argument parameter cast to the specified type.
Definition Casting.h:559
LLVMAttributeRef wrap(Attribute Attr)
Definition Attributes.h:389
bool is_contained(R &&Range, const E &Element)
Returns true if Element is found in Range.
Definition STLExtras.h:1963
This struct is a compact representation of a valid (non-zero power of two) alignment.
Definition Alignment.h:39
static constexpr Align Constant()
Allow constructions of constexpr Align.
Definition Alignment.h:93
Pointer type specification.
Definition DataLayout.h:75
APInt NullPtrValue
The null pointer bit representation for this address space.
Definition DataLayout.h:98
bool HasUnstableRepresentation
Pointers in this address space don't have a well-defined bitwise representation (e....
Definition DataLayout.h:89
LLVM_ABI bool operator==(const PointerSpec &Other) const
bool HasExternalState
Pointers in this address space have additional state bits that are located at a target-defined locati...
Definition DataLayout.h:94
uint32_t IndexBitWidth
The index bit width also defines the address size in this address space.
Definition DataLayout.h:85
Primitive type specification.
Definition DataLayout.h:66
LLVM_ABI bool operator==(const PrimitiveSpec &Other) const
This struct is a compact representation of a valid (power of two) or undefined (0) alignment.
Definition Alignment.h:111