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