Thanks to visit codestin.com
Credit goes to llvm.org

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