1 //===-- DataLayout.cpp - Data size & alignment routines --------------------==//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines layout properties related to datatype size/offset/alignment
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.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/IR/DataLayout.h"
20 #include "llvm/ADT/DenseMap.h"
21 #include "llvm/ADT/STLExtras.h"
22 #include "llvm/ADT/Triple.h"
23 #include "llvm/IR/Constants.h"
24 #include "llvm/IR/DerivedTypes.h"
25 #include "llvm/IR/GetElementPtrTypeIterator.h"
26 #include "llvm/IR/Module.h"
27 #include "llvm/Support/ErrorHandling.h"
28 #include "llvm/Support/ManagedStatic.h"
29 #include "llvm/Support/MathExtras.h"
30 #include "llvm/Support/Mutex.h"
31 #include "llvm/Support/raw_ostream.h"
36 // Handle the Pass registration stuff necessary to use DataLayout's.
38 INITIALIZE_PASS(DataLayoutPass, "datalayout", "Data Layout", false, true)
39 char DataLayoutPass::ID = 0;
41 //===----------------------------------------------------------------------===//
42 // Support for StructLayout
43 //===----------------------------------------------------------------------===//
45 StructLayout::StructLayout(StructType *ST, const DataLayout &DL) {
46 assert(!ST->isOpaque() && "Cannot get layout of opaque structs");
49 NumElements = ST->getNumElements();
51 // Loop over each of the elements, placing them in memory.
52 for (unsigned i = 0, e = NumElements; i != e; ++i) {
53 Type *Ty = ST->getElementType(i);
54 unsigned TyAlign = ST->isPacked() ? 1 : DL.getABITypeAlignment(Ty);
56 // Add padding if necessary to align the data element properly.
57 if ((StructSize & (TyAlign-1)) != 0)
58 StructSize = DataLayout::RoundUpAlignment(StructSize, TyAlign);
60 // Keep track of maximum alignment constraint.
61 StructAlignment = std::max(TyAlign, StructAlignment);
63 MemberOffsets[i] = StructSize;
64 StructSize += DL.getTypeAllocSize(Ty); // Consume space for this data item
67 // Empty structures have alignment of 1 byte.
68 if (StructAlignment == 0) StructAlignment = 1;
70 // Add padding to the end of the struct so that it could be put in an array
71 // and all array elements would be aligned correctly.
72 if ((StructSize & (StructAlignment-1)) != 0)
73 StructSize = DataLayout::RoundUpAlignment(StructSize, StructAlignment);
77 /// getElementContainingOffset - Given a valid offset into the structure,
78 /// return the structure index that contains it.
79 unsigned StructLayout::getElementContainingOffset(uint64_t Offset) const {
81 std::upper_bound(&MemberOffsets[0], &MemberOffsets[NumElements], Offset);
82 assert(SI != &MemberOffsets[0] && "Offset not in structure type!");
84 assert(*SI <= Offset && "upper_bound didn't work");
85 assert((SI == &MemberOffsets[0] || *(SI-1) <= Offset) &&
86 (SI+1 == &MemberOffsets[NumElements] || *(SI+1) > Offset) &&
87 "Upper bound didn't work!");
89 // Multiple fields can have the same offset if any of them are zero sized.
90 // For example, in { i32, [0 x i32], i32 }, searching for offset 4 will stop
91 // at the i32 element, because it is the last element at that offset. This is
92 // the right one to return, because anything after it will have a higher
93 // offset, implying that this element is non-empty.
94 return SI-&MemberOffsets[0];
97 //===----------------------------------------------------------------------===//
98 // LayoutAlignElem, LayoutAlign support
99 //===----------------------------------------------------------------------===//
102 LayoutAlignElem::get(AlignTypeEnum align_type, unsigned abi_align,
103 unsigned pref_align, uint32_t bit_width) {
104 assert(abi_align <= pref_align && "Preferred alignment worse than ABI!");
105 LayoutAlignElem retval;
106 retval.AlignType = align_type;
107 retval.ABIAlign = abi_align;
108 retval.PrefAlign = pref_align;
109 retval.TypeBitWidth = bit_width;
114 LayoutAlignElem::operator==(const LayoutAlignElem &rhs) const {
115 return (AlignType == rhs.AlignType
116 && ABIAlign == rhs.ABIAlign
117 && PrefAlign == rhs.PrefAlign
118 && TypeBitWidth == rhs.TypeBitWidth);
121 const LayoutAlignElem
122 DataLayout::InvalidAlignmentElem = { INVALID_ALIGN, 0, 0, 0 };
124 //===----------------------------------------------------------------------===//
125 // PointerAlignElem, PointerAlign support
126 //===----------------------------------------------------------------------===//
129 PointerAlignElem::get(uint32_t AddressSpace, unsigned ABIAlign,
130 unsigned PrefAlign, uint32_t TypeByteWidth) {
131 assert(ABIAlign <= PrefAlign && "Preferred alignment worse than ABI!");
132 PointerAlignElem retval;
133 retval.AddressSpace = AddressSpace;
134 retval.ABIAlign = ABIAlign;
135 retval.PrefAlign = PrefAlign;
136 retval.TypeByteWidth = TypeByteWidth;
141 PointerAlignElem::operator==(const PointerAlignElem &rhs) const {
142 return (ABIAlign == rhs.ABIAlign
143 && AddressSpace == rhs.AddressSpace
144 && PrefAlign == rhs.PrefAlign
145 && TypeByteWidth == rhs.TypeByteWidth);
148 const PointerAlignElem
149 DataLayout::InvalidPointerElem = { 0U, 0U, 0U, ~0U };
151 //===----------------------------------------------------------------------===//
152 // DataLayout Class Implementation
153 //===----------------------------------------------------------------------===//
155 const char *DataLayout::getManglingComponent(const Triple &T) {
156 if (T.isOSBinFormatMachO())
158 if (T.isOSBinFormatELF() || T.isArch64Bit())
160 assert(T.isOSBinFormatCOFF());
164 static const LayoutAlignElem DefaultAlignments[] = {
165 { INTEGER_ALIGN, 1, 1, 1 }, // i1
166 { INTEGER_ALIGN, 8, 1, 1 }, // i8
167 { INTEGER_ALIGN, 16, 2, 2 }, // i16
168 { INTEGER_ALIGN, 32, 4, 4 }, // i32
169 { INTEGER_ALIGN, 64, 4, 8 }, // i64
170 { FLOAT_ALIGN, 16, 2, 2 }, // half
171 { FLOAT_ALIGN, 32, 4, 4 }, // float
172 { FLOAT_ALIGN, 64, 8, 8 }, // double
173 { FLOAT_ALIGN, 128, 16, 16 }, // ppcf128, quad, ...
174 { VECTOR_ALIGN, 64, 8, 8 }, // v2i32, v1i64, ...
175 { VECTOR_ALIGN, 128, 16, 16 }, // v16i8, v8i16, v4i32, ...
176 { AGGREGATE_ALIGN, 0, 0, 8 } // struct
179 void DataLayout::reset(StringRef Desc) {
183 LittleEndian = false;
184 StackNaturalAlign = 0;
185 ManglingMode = MM_None;
187 // Default alignments
188 for (const LayoutAlignElem &E : DefaultAlignments) {
189 setAlignment((AlignTypeEnum)E.AlignType, E.ABIAlign, E.PrefAlign,
192 setPointerAlignment(0, 8, 8, 8);
194 parseSpecifier(Desc);
197 /// Checked version of split, to ensure mandatory subparts.
198 static std::pair<StringRef, StringRef> split(StringRef Str, char Separator) {
199 assert(!Str.empty() && "parse error, string can't be empty here");
200 std::pair<StringRef, StringRef> Split = Str.split(Separator);
201 assert((!Split.second.empty() || Split.first == Str) &&
202 "a trailing separator is not allowed");
206 /// Get an unsigned integer, including error checks.
207 static unsigned getInt(StringRef R) {
209 bool error = R.getAsInteger(10, Result); (void)error;
211 report_fatal_error("not a number, or does not fit in an unsigned int");
215 /// Convert bits into bytes. Assert if not a byte width multiple.
216 static unsigned inBytes(unsigned Bits) {
217 assert(Bits % 8 == 0 && "number of bits must be a byte width multiple");
221 void DataLayout::parseSpecifier(StringRef Desc) {
222 while (!Desc.empty()) {
224 std::pair<StringRef, StringRef> Split = split(Desc, '-');
228 Split = split(Split.first, ':');
230 // Aliases used below.
231 StringRef &Tok = Split.first; // Current token.
232 StringRef &Rest = Split.second; // The rest of the string.
234 char Specifier = Tok.front();
239 // Ignored for backward compatibility.
240 // FIXME: remove this on LLVM 4.0.
243 LittleEndian = false;
250 unsigned AddrSpace = Tok.empty() ? 0 : getInt(Tok);
251 assert(AddrSpace < 1 << 24 &&
252 "Invalid address space, must be a 24bit integer");
255 Split = split(Rest, ':');
256 unsigned PointerMemSize = inBytes(getInt(Tok));
259 Split = split(Rest, ':');
260 unsigned PointerABIAlign = inBytes(getInt(Tok));
262 // Preferred alignment.
263 unsigned PointerPrefAlign = PointerABIAlign;
265 Split = split(Rest, ':');
266 PointerPrefAlign = inBytes(getInt(Tok));
269 setPointerAlignment(AddrSpace, PointerABIAlign, PointerPrefAlign,
277 AlignTypeEnum AlignType;
280 case 'i': AlignType = INTEGER_ALIGN; break;
281 case 'v': AlignType = VECTOR_ALIGN; break;
282 case 'f': AlignType = FLOAT_ALIGN; break;
283 case 'a': AlignType = AGGREGATE_ALIGN; break;
287 unsigned Size = Tok.empty() ? 0 : getInt(Tok);
289 assert((AlignType != AGGREGATE_ALIGN || Size == 0) &&
290 "These specifications don't have a size");
293 Split = split(Rest, ':');
294 unsigned ABIAlign = inBytes(getInt(Tok));
296 // Preferred alignment.
297 unsigned PrefAlign = ABIAlign;
299 Split = split(Rest, ':');
300 PrefAlign = inBytes(getInt(Tok));
303 setAlignment(AlignType, ABIAlign, PrefAlign, Size);
307 case 'n': // Native integer types.
309 unsigned Width = getInt(Tok);
310 assert(Width != 0 && "width must be non-zero");
311 LegalIntWidths.push_back(Width);
314 Split = split(Rest, ':');
317 case 'S': { // Stack natural alignment.
318 StackNaturalAlign = inBytes(getInt(Tok));
323 assert(Rest.size() == 1);
326 llvm_unreachable("Unknown mangling in datalayout string");
328 ManglingMode = MM_ELF;
331 ManglingMode = MM_MachO;
334 ManglingMode = MM_Mips;
337 ManglingMode = MM_WINCOFF;
342 llvm_unreachable("Unknown specifier in datalayout string");
348 DataLayout::DataLayout(const Module *M) : LayoutMap(0) {
349 const DataLayout *Other = M->getDataLayout();
356 bool DataLayout::operator==(const DataLayout &Other) const {
357 bool Ret = LittleEndian == Other.LittleEndian &&
358 StackNaturalAlign == Other.StackNaturalAlign &&
359 ManglingMode == Other.ManglingMode &&
360 LegalIntWidths == Other.LegalIntWidths &&
361 Alignments == Other.Alignments && Pointers == Pointers;
362 assert(Ret == (getStringRepresentation() == Other.getStringRepresentation()));
367 DataLayout::setAlignment(AlignTypeEnum align_type, unsigned abi_align,
368 unsigned pref_align, uint32_t bit_width) {
369 assert(abi_align <= pref_align && "Preferred alignment worse than ABI!");
370 assert(pref_align < (1 << 16) && "Alignment doesn't fit in bitfield");
371 assert(bit_width < (1 << 24) && "Bit width doesn't fit in bitfield");
372 for (LayoutAlignElem &Elem : Alignments) {
373 if (Elem.AlignType == (unsigned)align_type &&
374 Elem.TypeBitWidth == bit_width) {
375 // Update the abi, preferred alignments.
376 Elem.ABIAlign = abi_align;
377 Elem.PrefAlign = pref_align;
382 Alignments.push_back(LayoutAlignElem::get(align_type, abi_align,
383 pref_align, bit_width));
386 DataLayout::PointersTy::iterator
387 DataLayout::findPointerLowerBound(uint32_t AddressSpace) {
388 return std::lower_bound(Pointers.begin(), Pointers.end(), AddressSpace,
389 [](const PointerAlignElem &A, uint32_t AddressSpace) {
390 return A.AddressSpace < AddressSpace;
394 void DataLayout::setPointerAlignment(uint32_t AddrSpace, unsigned ABIAlign,
396 uint32_t TypeByteWidth) {
397 assert(ABIAlign <= PrefAlign && "Preferred alignment worse than ABI!");
398 PointersTy::iterator I = findPointerLowerBound(AddrSpace);
399 if (I == Pointers.end() || I->AddressSpace != AddrSpace) {
400 Pointers.insert(I, PointerAlignElem::get(AddrSpace, ABIAlign, PrefAlign,
403 I->ABIAlign = ABIAlign;
404 I->PrefAlign = PrefAlign;
405 I->TypeByteWidth = TypeByteWidth;
409 /// getAlignmentInfo - Return the alignment (either ABI if ABIInfo = true or
410 /// preferred if ABIInfo = false) the layout wants for the specified datatype.
411 unsigned DataLayout::getAlignmentInfo(AlignTypeEnum AlignType,
412 uint32_t BitWidth, bool ABIInfo,
414 // Check to see if we have an exact match and remember the best match we see.
415 int BestMatchIdx = -1;
417 for (unsigned i = 0, e = Alignments.size(); i != e; ++i) {
418 if (Alignments[i].AlignType == (unsigned)AlignType &&
419 Alignments[i].TypeBitWidth == BitWidth)
420 return ABIInfo ? Alignments[i].ABIAlign : Alignments[i].PrefAlign;
422 // The best match so far depends on what we're looking for.
423 if (AlignType == INTEGER_ALIGN &&
424 Alignments[i].AlignType == INTEGER_ALIGN) {
425 // The "best match" for integers is the smallest size that is larger than
426 // the BitWidth requested.
427 if (Alignments[i].TypeBitWidth > BitWidth && (BestMatchIdx == -1 ||
428 Alignments[i].TypeBitWidth < Alignments[BestMatchIdx].TypeBitWidth))
430 // However, if there isn't one that's larger, then we must use the
431 // largest one we have (see below)
432 if (LargestInt == -1 ||
433 Alignments[i].TypeBitWidth > Alignments[LargestInt].TypeBitWidth)
438 // Okay, we didn't find an exact solution. Fall back here depending on what
439 // is being looked for.
440 if (BestMatchIdx == -1) {
441 // If we didn't find an integer alignment, fall back on most conservative.
442 if (AlignType == INTEGER_ALIGN) {
443 BestMatchIdx = LargestInt;
445 assert(AlignType == VECTOR_ALIGN && "Unknown alignment type!");
447 // By default, use natural alignment for vector types. This is consistent
448 // with what clang and llvm-gcc do.
449 unsigned Align = getTypeAllocSize(cast<VectorType>(Ty)->getElementType());
450 Align *= cast<VectorType>(Ty)->getNumElements();
451 // If the alignment is not a power of 2, round up to the next power of 2.
452 // This happens for non-power-of-2 length vectors.
453 if (Align & (Align-1))
454 Align = NextPowerOf2(Align);
459 // Since we got a "best match" index, just return it.
460 return ABIInfo ? Alignments[BestMatchIdx].ABIAlign
461 : Alignments[BestMatchIdx].PrefAlign;
466 class StructLayoutMap {
467 typedef DenseMap<StructType*, StructLayout*> LayoutInfoTy;
468 LayoutInfoTy LayoutInfo;
472 // Remove any layouts.
473 for (const auto &I : LayoutInfo) {
474 StructLayout *Value = I.second;
475 Value->~StructLayout();
480 StructLayout *&operator[](StructType *STy) {
481 return LayoutInfo[STy];
485 } // end anonymous namespace
487 void DataLayout::clear() {
488 LegalIntWidths.clear();
491 delete static_cast<StructLayoutMap *>(LayoutMap);
495 DataLayout::~DataLayout() {
499 const StructLayout *DataLayout::getStructLayout(StructType *Ty) const {
501 LayoutMap = new StructLayoutMap();
503 StructLayoutMap *STM = static_cast<StructLayoutMap*>(LayoutMap);
504 StructLayout *&SL = (*STM)[Ty];
507 // Otherwise, create the struct layout. Because it is variable length, we
508 // malloc it, then use placement new.
509 int NumElts = Ty->getNumElements();
511 (StructLayout *)malloc(sizeof(StructLayout)+(NumElts-1) * sizeof(uint64_t));
513 // Set SL before calling StructLayout's ctor. The ctor could cause other
514 // entries to be added to TheMap, invalidating our reference.
517 new (L) StructLayout(Ty, *this);
522 std::string DataLayout::getStringRepresentation() const {
524 raw_string_ostream OS(Result);
526 OS << (LittleEndian ? "e" : "E");
528 switch (ManglingMode) {
545 for (const PointerAlignElem &PI : Pointers) {
547 if (PI.AddressSpace == 0 && PI.ABIAlign == 8 && PI.PrefAlign == 8 &&
548 PI.TypeByteWidth == 8)
552 if (PI.AddressSpace) {
553 OS << PI.AddressSpace;
555 OS << ":" << PI.TypeByteWidth*8 << ':' << PI.ABIAlign*8;
556 if (PI.PrefAlign != PI.ABIAlign)
557 OS << ':' << PI.PrefAlign*8;
560 for (const LayoutAlignElem &AI : Alignments) {
561 if (std::find(std::begin(DefaultAlignments), std::end(DefaultAlignments),
562 AI) != std::end(DefaultAlignments))
564 OS << '-' << (char)AI.AlignType;
566 OS << AI.TypeBitWidth;
567 OS << ':' << AI.ABIAlign*8;
568 if (AI.ABIAlign != AI.PrefAlign)
569 OS << ':' << AI.PrefAlign*8;
572 if (!LegalIntWidths.empty()) {
573 OS << "-n" << (unsigned)LegalIntWidths[0];
575 for (unsigned i = 1, e = LegalIntWidths.size(); i != e; ++i)
576 OS << ':' << (unsigned)LegalIntWidths[i];
579 if (StackNaturalAlign)
580 OS << "-S" << StackNaturalAlign*8;
585 unsigned DataLayout::getPointerABIAlignment(unsigned AS) const {
586 PointersTy::const_iterator I = findPointerLowerBound(AS);
587 if (I == Pointers.end() || I->AddressSpace != AS) {
588 I = findPointerLowerBound(0);
589 assert(I->AddressSpace == 0);
594 unsigned DataLayout::getPointerPrefAlignment(unsigned AS) const {
595 PointersTy::const_iterator I = findPointerLowerBound(AS);
596 if (I == Pointers.end() || I->AddressSpace != AS) {
597 I = findPointerLowerBound(0);
598 assert(I->AddressSpace == 0);
603 unsigned DataLayout::getPointerSize(unsigned AS) const {
604 PointersTy::const_iterator I = findPointerLowerBound(AS);
605 if (I == Pointers.end() || I->AddressSpace != AS) {
606 I = findPointerLowerBound(0);
607 assert(I->AddressSpace == 0);
609 return I->TypeByteWidth;
612 unsigned DataLayout::getPointerTypeSizeInBits(Type *Ty) const {
613 assert(Ty->isPtrOrPtrVectorTy() &&
614 "This should only be called with a pointer or pointer vector type");
616 if (Ty->isPointerTy())
617 return getTypeSizeInBits(Ty);
619 return getTypeSizeInBits(Ty->getScalarType());
623 \param abi_or_pref Flag that determines which alignment is returned. true
624 returns the ABI alignment, false returns the preferred alignment.
625 \param Ty The underlying type for which alignment is determined.
627 Get the ABI (\a abi_or_pref == true) or preferred alignment (\a abi_or_pref
628 == false) for the requested type \a Ty.
630 unsigned DataLayout::getAlignment(Type *Ty, bool abi_or_pref) const {
633 assert(Ty->isSized() && "Cannot getTypeInfo() on a type that is unsized!");
634 switch (Ty->getTypeID()) {
635 // Early escape for the non-numeric types.
636 case Type::LabelTyID:
638 ? getPointerABIAlignment(0)
639 : getPointerPrefAlignment(0));
640 case Type::PointerTyID: {
641 unsigned AS = dyn_cast<PointerType>(Ty)->getAddressSpace();
643 ? getPointerABIAlignment(AS)
644 : getPointerPrefAlignment(AS));
646 case Type::ArrayTyID:
647 return getAlignment(cast<ArrayType>(Ty)->getElementType(), abi_or_pref);
649 case Type::StructTyID: {
650 // Packed structure types always have an ABI alignment of one.
651 if (cast<StructType>(Ty)->isPacked() && abi_or_pref)
654 // Get the layout annotation... which is lazily created on demand.
655 const StructLayout *Layout = getStructLayout(cast<StructType>(Ty));
656 unsigned Align = getAlignmentInfo(AGGREGATE_ALIGN, 0, abi_or_pref, Ty);
657 return std::max(Align, Layout->getAlignment());
659 case Type::IntegerTyID:
660 AlignType = INTEGER_ALIGN;
663 case Type::FloatTyID:
664 case Type::DoubleTyID:
665 // PPC_FP128TyID and FP128TyID have different data contents, but the
666 // same size and alignment, so they look the same here.
667 case Type::PPC_FP128TyID:
668 case Type::FP128TyID:
669 case Type::X86_FP80TyID:
670 AlignType = FLOAT_ALIGN;
672 case Type::X86_MMXTyID:
673 case Type::VectorTyID:
674 AlignType = VECTOR_ALIGN;
677 llvm_unreachable("Bad type for getAlignment!!!");
680 return getAlignmentInfo((AlignTypeEnum)AlignType, getTypeSizeInBits(Ty),
684 unsigned DataLayout::getABITypeAlignment(Type *Ty) const {
685 return getAlignment(Ty, true);
688 /// getABIIntegerTypeAlignment - Return the minimum ABI-required alignment for
689 /// an integer type of the specified bitwidth.
690 unsigned DataLayout::getABIIntegerTypeAlignment(unsigned BitWidth) const {
691 return getAlignmentInfo(INTEGER_ALIGN, BitWidth, true, 0);
694 unsigned DataLayout::getPrefTypeAlignment(Type *Ty) const {
695 return getAlignment(Ty, false);
698 unsigned DataLayout::getPreferredTypeAlignmentShift(Type *Ty) const {
699 unsigned Align = getPrefTypeAlignment(Ty);
700 assert(!(Align & (Align-1)) && "Alignment is not a power of two!");
701 return Log2_32(Align);
704 IntegerType *DataLayout::getIntPtrType(LLVMContext &C,
705 unsigned AddressSpace) const {
706 return IntegerType::get(C, getPointerSizeInBits(AddressSpace));
709 Type *DataLayout::getIntPtrType(Type *Ty) const {
710 assert(Ty->isPtrOrPtrVectorTy() &&
711 "Expected a pointer or pointer vector type.");
712 unsigned NumBits = getTypeSizeInBits(Ty->getScalarType());
713 IntegerType *IntTy = IntegerType::get(Ty->getContext(), NumBits);
714 if (VectorType *VecTy = dyn_cast<VectorType>(Ty))
715 return VectorType::get(IntTy, VecTy->getNumElements());
719 Type *DataLayout::getSmallestLegalIntType(LLVMContext &C, unsigned Width) const {
720 for (unsigned LegalIntWidth : LegalIntWidths)
721 if (Width <= LegalIntWidth)
722 return Type::getIntNTy(C, LegalIntWidth);
726 unsigned DataLayout::getLargestLegalIntTypeSize() const {
727 auto Max = std::max_element(LegalIntWidths.begin(), LegalIntWidths.end());
728 return Max != LegalIntWidths.end() ? *Max : 0;
731 uint64_t DataLayout::getIndexedOffset(Type *ptrTy,
732 ArrayRef<Value *> Indices) const {
734 assert(Ty->isPointerTy() && "Illegal argument for getIndexedOffset()");
737 generic_gep_type_iterator<Value* const*>
738 TI = gep_type_begin(ptrTy, Indices);
739 for (unsigned CurIDX = 0, EndIDX = Indices.size(); CurIDX != EndIDX;
741 if (StructType *STy = dyn_cast<StructType>(*TI)) {
742 assert(Indices[CurIDX]->getType() ==
743 Type::getInt32Ty(ptrTy->getContext()) &&
744 "Illegal struct idx");
745 unsigned FieldNo = cast<ConstantInt>(Indices[CurIDX])->getZExtValue();
747 // Get structure layout information...
748 const StructLayout *Layout = getStructLayout(STy);
750 // Add in the offset, as calculated by the structure layout info...
751 Result += Layout->getElementOffset(FieldNo);
753 // Update Ty to refer to current element
754 Ty = STy->getElementType(FieldNo);
756 // Update Ty to refer to current element
757 Ty = cast<SequentialType>(Ty)->getElementType();
759 // Get the array index and the size of each array element.
760 if (int64_t arrayIdx = cast<ConstantInt>(Indices[CurIDX])->getSExtValue())
761 Result += (uint64_t)arrayIdx * getTypeAllocSize(Ty);
768 /// getPreferredAlignment - Return the preferred alignment of the specified
769 /// global. This includes an explicitly requested alignment (if the global
771 unsigned DataLayout::getPreferredAlignment(const GlobalVariable *GV) const {
772 Type *ElemType = GV->getType()->getElementType();
773 unsigned Alignment = getPrefTypeAlignment(ElemType);
774 unsigned GVAlignment = GV->getAlignment();
775 if (GVAlignment >= Alignment) {
776 Alignment = GVAlignment;
777 } else if (GVAlignment != 0) {
778 Alignment = std::max(GVAlignment, getABITypeAlignment(ElemType));
781 if (GV->hasInitializer() && GVAlignment == 0) {
782 if (Alignment < 16) {
783 // If the global is not external, see if it is large. If so, give it a
785 if (getTypeSizeInBits(ElemType) > 128)
786 Alignment = 16; // 16-byte alignment.
792 /// getPreferredAlignmentLog - Return the preferred alignment of the
793 /// specified global, returned in log form. This includes an explicitly
794 /// requested alignment (if the global has one).
795 unsigned DataLayout::getPreferredAlignmentLog(const GlobalVariable *GV) const {
796 return Log2_32(getPreferredAlignment(GV));
799 DataLayoutPass::DataLayoutPass() : ImmutablePass(ID), DL("") {
800 report_fatal_error("Bad DataLayoutPass ctor used. Tool did not specify a "
801 "DataLayout to use?");
804 DataLayoutPass::~DataLayoutPass() {}
806 DataLayoutPass::DataLayoutPass(const DataLayout &DL)
807 : ImmutablePass(ID), DL(DL) {
808 initializeDataLayoutPassPass(*PassRegistry::getPassRegistry());
811 DataLayoutPass::DataLayoutPass(const Module *M) : ImmutablePass(ID), DL(M) {
812 initializeDataLayoutPassPass(*PassRegistry::getPassRegistry());