1 //===--- CGRecordLayoutBuilder.cpp - CGRecordLayout builder ----*- C++ -*-===//
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 // Builder implementation for CGRecordLayout objects.
12 //===----------------------------------------------------------------------===//
14 #include "CGRecordLayout.h"
15 #include "clang/AST/ASTContext.h"
16 #include "clang/AST/Attr.h"
17 #include "clang/AST/CXXInheritance.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/AST/RecordLayout.h"
21 #include "CodeGenTypes.h"
23 #include "llvm/DerivedTypes.h"
24 #include "llvm/Type.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/raw_ostream.h"
27 #include "llvm/Target/TargetData.h"
28 using namespace clang;
29 using namespace CodeGen;
33 class CGRecordLayoutBuilder {
35 /// FieldTypes - Holds the LLVM types that the struct is created from.
37 std::vector<const llvm::Type *> FieldTypes;
39 /// BaseSubobjectType - Holds the LLVM type for the non-virtual part
40 /// of the struct. For example, consider:
42 /// struct A { int i; };
43 /// struct B { void *v; };
44 /// struct C : virtual A, B { };
46 /// The LLVM type of C will be
47 /// %struct.C = type { i32 (...)**, %struct.A, i32, %struct.B }
49 /// And the LLVM type of the non-virtual base struct will be
50 /// %struct.C.base = type { i32 (...)**, %struct.A, i32 }
52 /// This only gets initialized if the base subobject type is
53 /// different from the complete-object type.
54 const llvm::StructType *BaseSubobjectType;
56 /// FieldInfo - Holds a field and its corresponding LLVM field number.
57 llvm::DenseMap<const FieldDecl *, unsigned> Fields;
59 /// BitFieldInfo - Holds location and size information about a bit field.
60 llvm::DenseMap<const FieldDecl *, CGBitFieldInfo> BitFields;
62 llvm::DenseMap<const CXXRecordDecl *, unsigned> NonVirtualBases;
63 llvm::DenseMap<const CXXRecordDecl *, unsigned> VirtualBases;
65 /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are
66 /// primary base classes for some other direct or indirect base class.
67 CXXIndirectPrimaryBaseSet IndirectPrimaryBases;
69 /// LaidOutVirtualBases - A set of all laid out virtual bases, used to avoid
70 /// avoid laying out virtual bases more than once.
71 llvm::SmallPtrSet<const CXXRecordDecl *, 4> LaidOutVirtualBases;
73 /// IsZeroInitializable - Whether this struct can be C++
74 /// zero-initialized with an LLVM zeroinitializer.
75 bool IsZeroInitializable;
76 bool IsZeroInitializableAsBase;
78 /// Packed - Whether the resulting LLVM struct will be packed or not.
84 /// Alignment - Contains the alignment of the RecordDecl.
86 // FIXME: This is not needed and should be removed.
89 /// BitsAvailableInLastField - If a bit field spans only part of a LLVM field,
90 /// this will have the number of bits still available in the field.
91 char BitsAvailableInLastField;
93 /// NextFieldOffset - Holds the next field offset.
94 CharUnits NextFieldOffset;
96 /// LayoutUnionField - Will layout a field in an union and return the type
97 /// that the field will have.
98 const llvm::Type *LayoutUnionField(const FieldDecl *Field,
99 const ASTRecordLayout &Layout);
101 /// LayoutUnion - Will layout a union RecordDecl.
102 void LayoutUnion(const RecordDecl *D);
104 /// LayoutField - try to layout all fields in the record decl.
105 /// Returns false if the operation failed because the struct is not packed.
106 bool LayoutFields(const RecordDecl *D);
108 /// Layout a single base, virtual or non-virtual
109 void LayoutBase(const CXXRecordDecl *base,
110 const CGRecordLayout &baseLayout,
111 CharUnits baseOffset);
113 /// LayoutVirtualBase - layout a single virtual base.
114 void LayoutVirtualBase(const CXXRecordDecl *base,
115 CharUnits baseOffset);
117 /// LayoutVirtualBases - layout the virtual bases of a record decl.
118 void LayoutVirtualBases(const CXXRecordDecl *RD,
119 const ASTRecordLayout &Layout);
121 /// LayoutNonVirtualBase - layout a single non-virtual base.
122 void LayoutNonVirtualBase(const CXXRecordDecl *base,
123 CharUnits baseOffset);
125 /// LayoutNonVirtualBases - layout the virtual bases of a record decl.
126 void LayoutNonVirtualBases(const CXXRecordDecl *RD,
127 const ASTRecordLayout &Layout);
129 /// ComputeNonVirtualBaseType - Compute the non-virtual base field types.
130 bool ComputeNonVirtualBaseType(const CXXRecordDecl *RD);
132 /// LayoutField - layout a single field. Returns false if the operation failed
133 /// because the current struct is not packed.
134 bool LayoutField(const FieldDecl *D, uint64_t FieldOffset);
136 /// LayoutBitField - layout a single bit field.
137 void LayoutBitField(const FieldDecl *D, uint64_t FieldOffset);
139 /// AppendField - Appends a field with the given offset and type.
140 void AppendField(CharUnits fieldOffset, const llvm::Type *FieldTy);
142 /// AppendPadding - Appends enough padding bytes so that the total
143 /// struct size is a multiple of the field alignment.
144 void AppendPadding(CharUnits fieldOffset, CharUnits fieldAlignment);
146 /// getByteArrayType - Returns a byte array type with the given number of
148 const llvm::Type *getByteArrayType(CharUnits NumBytes);
150 /// AppendBytes - Append a given number of bytes to the record.
151 void AppendBytes(CharUnits numBytes);
153 /// AppendTailPadding - Append enough tail padding so that the type will have
155 void AppendTailPadding(uint64_t RecordSize);
157 CharUnits getTypeAlignment(const llvm::Type *Ty) const;
159 /// getAlignmentAsLLVMStruct - Returns the maximum alignment of all the
160 /// LLVM element types.
161 CharUnits getAlignmentAsLLVMStruct() const;
163 /// CheckZeroInitializable - Check if the given type contains a pointer
165 void CheckZeroInitializable(QualType T);
168 CGRecordLayoutBuilder(CodeGenTypes &Types)
169 : BaseSubobjectType(0),
170 IsZeroInitializable(true), IsZeroInitializableAsBase(true),
171 Packed(false), Types(Types), BitsAvailableInLastField(0) { }
173 /// Layout - Will layout a RecordDecl.
174 void Layout(const RecordDecl *D);
179 void CGRecordLayoutBuilder::Layout(const RecordDecl *D) {
180 Alignment = Types.getContext().getASTRecordLayout(D).getAlignment();
181 Packed = D->hasAttr<PackedAttr>();
191 // We weren't able to layout the struct. Try again with a packed struct
193 NextFieldOffset = CharUnits::Zero();
197 NonVirtualBases.clear();
198 VirtualBases.clear();
203 CGBitFieldInfo CGBitFieldInfo::MakeInfo(CodeGenTypes &Types,
205 uint64_t FieldOffset,
207 uint64_t ContainingTypeSizeInBits,
208 unsigned ContainingTypeAlign) {
209 const llvm::Type *Ty = Types.ConvertTypeForMemRecursive(FD->getType());
210 CharUnits TypeSizeInBytes =
211 CharUnits::fromQuantity(Types.getTargetData().getTypeAllocSize(Ty));
212 uint64_t TypeSizeInBits = Types.getContext().toBits(TypeSizeInBytes);
214 bool IsSigned = FD->getType()->isSignedIntegerType();
216 if (FieldSize > TypeSizeInBits) {
217 // We have a wide bit-field. The extra bits are only used for padding, so
218 // if we have a bitfield of type T, with size N:
222 // We can just assume that it's:
226 FieldSize = TypeSizeInBits;
229 // in big-endian machines the first fields are in higher bit positions,
230 // so revert the offset. The byte offsets are reversed(back) later.
231 if (Types.getTargetData().isBigEndian()) {
232 FieldOffset = ((ContainingTypeSizeInBits)-FieldOffset-FieldSize);
235 // Compute the access components. The policy we use is to start by attempting
236 // to access using the width of the bit-field type itself and to always access
237 // at aligned indices of that type. If such an access would fail because it
238 // extends past the bound of the type, then we reduce size to the next smaller
239 // power of two and retry. The current algorithm assumes pow2 sized types,
240 // although this is easy to fix.
242 assert(llvm::isPowerOf2_32(TypeSizeInBits) && "Unexpected type size!");
243 CGBitFieldInfo::AccessInfo Components[3];
244 unsigned NumComponents = 0;
245 unsigned AccessedTargetBits = 0; // The tumber of target bits accessed.
246 unsigned AccessWidth = TypeSizeInBits; // The current access width to attempt.
248 // Round down from the field offset to find the first access position that is
249 // at an aligned offset of the initial access type.
250 uint64_t AccessStart = FieldOffset - (FieldOffset % AccessWidth);
252 // Adjust initial access size to fit within record.
253 while (AccessWidth > Types.getTarget().getCharWidth() &&
254 AccessStart + AccessWidth > ContainingTypeSizeInBits) {
256 AccessStart = FieldOffset - (FieldOffset % AccessWidth);
259 while (AccessedTargetBits < FieldSize) {
260 // Check that we can access using a type of this size, without reading off
261 // the end of the structure. This can occur with packed structures and
262 // -fno-bitfield-type-align, for example.
263 if (AccessStart + AccessWidth > ContainingTypeSizeInBits) {
264 // If so, reduce access size to the next smaller power-of-two and retry.
266 assert(AccessWidth >= Types.getTarget().getCharWidth()
267 && "Cannot access under byte size!");
271 // Otherwise, add an access component.
273 // First, compute the bits inside this access which are part of the
274 // target. We are reading bits [AccessStart, AccessStart + AccessWidth); the
275 // intersection with [FieldOffset, FieldOffset + FieldSize) gives the bits
276 // in the target that we are reading.
277 assert(FieldOffset < AccessStart + AccessWidth && "Invalid access start!");
278 assert(AccessStart < FieldOffset + FieldSize && "Invalid access start!");
279 uint64_t AccessBitsInFieldStart = std::max(AccessStart, FieldOffset);
280 uint64_t AccessBitsInFieldSize =
281 std::min(AccessWidth + AccessStart,
282 FieldOffset + FieldSize) - AccessBitsInFieldStart;
284 assert(NumComponents < 3 && "Unexpected number of components!");
285 CGBitFieldInfo::AccessInfo &AI = Components[NumComponents++];
287 // FIXME: We still follow the old access pattern of only using the field
288 // byte offset. We should switch this once we fix the struct layout to be
291 // on big-endian machines we reverted the bit offset because first fields are
292 // in higher bits. But this also reverts the bytes, so fix this here by reverting
293 // the byte offset on big-endian machines.
294 if (Types.getTargetData().isBigEndian()) {
295 AI.FieldByteOffset = (ContainingTypeSizeInBits - AccessStart - AccessWidth )/8;
297 AI.FieldByteOffset = AccessStart / 8;
299 AI.FieldBitStart = AccessBitsInFieldStart - AccessStart;
300 AI.AccessWidth = AccessWidth;
301 AI.AccessAlignment = llvm::MinAlign(ContainingTypeAlign, AccessStart) / 8;
302 AI.TargetBitOffset = AccessedTargetBits;
303 AI.TargetBitWidth = AccessBitsInFieldSize;
305 AccessStart += AccessWidth;
306 AccessedTargetBits += AI.TargetBitWidth;
309 assert(AccessedTargetBits == FieldSize && "Invalid bit-field access!");
310 return CGBitFieldInfo(FieldSize, NumComponents, Components, IsSigned);
313 CGBitFieldInfo CGBitFieldInfo::MakeInfo(CodeGenTypes &Types,
315 uint64_t FieldOffset,
316 uint64_t FieldSize) {
317 const RecordDecl *RD = FD->getParent();
318 const ASTRecordLayout &RL = Types.getContext().getASTRecordLayout(RD);
319 uint64_t ContainingTypeSizeInBits = Types.getContext().toBits(RL.getSize());
320 unsigned ContainingTypeAlign = Types.getContext().toBits(RL.getAlignment());
322 return MakeInfo(Types, FD, FieldOffset, FieldSize, ContainingTypeSizeInBits,
323 ContainingTypeAlign);
326 void CGRecordLayoutBuilder::LayoutBitField(const FieldDecl *D,
327 uint64_t fieldOffset) {
329 D->getBitWidth()->EvaluateAsInt(Types.getContext()).getZExtValue();
334 uint64_t nextFieldOffsetInBits = Types.getContext().toBits(NextFieldOffset);
335 unsigned numBytesToAppend;
337 if (fieldOffset < nextFieldOffsetInBits) {
338 assert(BitsAvailableInLastField && "Bitfield size mismatch!");
339 assert(!NextFieldOffset.isZero() && "Must have laid out at least one byte");
341 // The bitfield begins in the previous bit-field.
343 llvm::RoundUpToAlignment(fieldSize - BitsAvailableInLastField, 8) / 8;
345 assert(fieldOffset % 8 == 0 && "Field offset not aligned correctly");
347 // Append padding if necessary.
348 AppendPadding(CharUnits::fromQuantity(fieldOffset / 8), CharUnits::One());
350 numBytesToAppend = llvm::RoundUpToAlignment(fieldSize, 8) / 8;
352 assert(numBytesToAppend && "No bytes to append!");
355 // Add the bit field info.
356 BitFields.insert(std::make_pair(D,
357 CGBitFieldInfo::MakeInfo(Types, D, fieldOffset, fieldSize)));
359 AppendBytes(CharUnits::fromQuantity(numBytesToAppend));
361 BitsAvailableInLastField =
362 NextFieldOffset.getQuantity() * 8 - (fieldOffset + fieldSize);
365 bool CGRecordLayoutBuilder::LayoutField(const FieldDecl *D,
366 uint64_t fieldOffset) {
367 // If the field is packed, then we need a packed struct.
368 if (!Packed && D->hasAttr<PackedAttr>())
371 if (D->isBitField()) {
372 // We must use packed structs for unnamed bit fields since they
373 // don't affect the struct alignment.
374 if (!Packed && !D->getDeclName())
377 LayoutBitField(D, fieldOffset);
381 CheckZeroInitializable(D->getType());
383 assert(fieldOffset % Types.getTarget().getCharWidth() == 0
384 && "field offset is not on a byte boundary!");
385 CharUnits fieldOffsetInBytes
386 = Types.getContext().toCharUnitsFromBits(fieldOffset);
388 const llvm::Type *Ty = Types.ConvertTypeForMemRecursive(D->getType());
389 CharUnits typeAlignment = getTypeAlignment(Ty);
391 // If the type alignment is larger then the struct alignment, we must use
393 if (typeAlignment > Alignment) {
394 assert(!Packed && "Alignment is wrong even with packed struct!");
399 if (const RecordType *RT = D->getType()->getAs<RecordType>()) {
400 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
401 if (const MaxFieldAlignmentAttr *MFAA =
402 RD->getAttr<MaxFieldAlignmentAttr>()) {
403 if (MFAA->getAlignment() != Types.getContext().toBits(typeAlignment))
409 // Round up the field offset to the alignment of the field type.
410 CharUnits alignedNextFieldOffsetInBytes =
411 NextFieldOffset.RoundUpToAlignment(typeAlignment);
413 if (fieldOffsetInBytes < alignedNextFieldOffsetInBytes) {
414 assert(!Packed && "Could not place field even with packed struct!");
418 AppendPadding(fieldOffsetInBytes, typeAlignment);
420 // Now append the field.
421 Fields[D] = FieldTypes.size();
422 AppendField(fieldOffsetInBytes, Ty);
428 CGRecordLayoutBuilder::LayoutUnionField(const FieldDecl *Field,
429 const ASTRecordLayout &Layout) {
430 if (Field->isBitField()) {
432 Field->getBitWidth()->EvaluateAsInt(Types.getContext()).getZExtValue();
434 // Ignore zero sized bit fields.
438 const llvm::Type *FieldTy = llvm::Type::getInt8Ty(Types.getLLVMContext());
439 unsigned NumBytesToAppend =
440 llvm::RoundUpToAlignment(FieldSize, 8) / 8;
442 if (NumBytesToAppend > 1)
443 FieldTy = llvm::ArrayType::get(FieldTy, NumBytesToAppend);
445 // Add the bit field info.
446 BitFields.insert(std::make_pair(Field,
447 CGBitFieldInfo::MakeInfo(Types, Field, 0, FieldSize)));
451 // This is a regular union field.
453 return Types.ConvertTypeForMemRecursive(Field->getType());
456 void CGRecordLayoutBuilder::LayoutUnion(const RecordDecl *D) {
457 assert(D->isUnion() && "Can't call LayoutUnion on a non-union record!");
459 const ASTRecordLayout &layout = Types.getContext().getASTRecordLayout(D);
461 const llvm::Type *unionType = 0;
462 CharUnits unionSize = CharUnits::Zero();
463 CharUnits unionAlign = CharUnits::Zero();
465 bool hasOnlyZeroSizedBitFields = true;
467 unsigned fieldNo = 0;
468 for (RecordDecl::field_iterator field = D->field_begin(),
469 fieldEnd = D->field_end(); field != fieldEnd; ++field, ++fieldNo) {
470 assert(layout.getFieldOffset(fieldNo) == 0 &&
471 "Union field offset did not start at the beginning of record!");
472 const llvm::Type *fieldType = LayoutUnionField(*field, layout);
477 hasOnlyZeroSizedBitFields = false;
479 CharUnits fieldAlign = CharUnits::fromQuantity(
480 Types.getTargetData().getABITypeAlignment(fieldType));
481 CharUnits fieldSize = CharUnits::fromQuantity(
482 Types.getTargetData().getTypeAllocSize(fieldType));
484 if (fieldAlign < unionAlign)
487 if (fieldAlign > unionAlign || fieldSize > unionSize) {
488 unionType = fieldType;
489 unionAlign = fieldAlign;
490 unionSize = fieldSize;
494 // Now add our field.
496 AppendField(CharUnits::Zero(), unionType);
498 if (getTypeAlignment(unionType) > layout.getAlignment()) {
499 // We need a packed struct.
501 unionAlign = CharUnits::One();
504 if (unionAlign.isZero()) {
505 assert(hasOnlyZeroSizedBitFields &&
506 "0-align record did not have all zero-sized bit-fields!");
507 unionAlign = CharUnits::One();
510 // Append tail padding.
511 CharUnits recordSize = layout.getSize();
512 if (recordSize > unionSize)
513 AppendPadding(recordSize, unionAlign);
516 void CGRecordLayoutBuilder::LayoutBase(const CXXRecordDecl *base,
517 const CGRecordLayout &baseLayout,
518 CharUnits baseOffset) {
519 AppendPadding(baseOffset, CharUnits::One());
521 const ASTRecordLayout &baseASTLayout
522 = Types.getContext().getASTRecordLayout(base);
524 // Fields and bases can be laid out in the tail padding of previous
525 // bases. If this happens, we need to allocate the base as an i8
526 // array; otherwise, we can use the subobject type. However,
527 // actually doing that would require knowledge of what immediately
528 // follows this base in the layout, so instead we do a conservative
529 // approximation, which is to use the base subobject type if it
530 // has the same LLVM storage size as the nvsize.
532 // The nvsize, i.e. the unpadded size of the base class.
533 CharUnits nvsize = baseASTLayout.getNonVirtualSize();
536 const llvm::StructType *subobjectType = baseLayout.getBaseSubobjectLLVMType();
537 const llvm::StructLayout *baseLLVMLayout =
538 Types.getTargetData().getStructLayout(subobjectType);
539 CharUnits stsize = CharUnits::fromQuantity(baseLLVMLayout->getSizeInBytes());
541 if (nvsize == stsize)
542 AppendField(baseOffset, subobjectType);
548 void CGRecordLayoutBuilder::LayoutNonVirtualBase(const CXXRecordDecl *base,
549 CharUnits baseOffset) {
550 // Ignore empty bases.
551 if (base->isEmpty()) return;
553 const CGRecordLayout &baseLayout = Types.getCGRecordLayout(base);
554 if (IsZeroInitializableAsBase) {
555 assert(IsZeroInitializable &&
556 "class zero-initializable as base but not as complete object");
558 IsZeroInitializable = IsZeroInitializableAsBase =
559 baseLayout.isZeroInitializableAsBase();
562 LayoutBase(base, baseLayout, baseOffset);
563 NonVirtualBases[base] = (FieldTypes.size() - 1);
567 CGRecordLayoutBuilder::LayoutVirtualBase(const CXXRecordDecl *base,
568 CharUnits baseOffset) {
569 // Ignore empty bases.
570 if (base->isEmpty()) return;
572 const CGRecordLayout &baseLayout = Types.getCGRecordLayout(base);
573 if (IsZeroInitializable)
574 IsZeroInitializable = baseLayout.isZeroInitializableAsBase();
576 LayoutBase(base, baseLayout, baseOffset);
577 VirtualBases[base] = (FieldTypes.size() - 1);
580 /// LayoutVirtualBases - layout the non-virtual bases of a record decl.
582 CGRecordLayoutBuilder::LayoutVirtualBases(const CXXRecordDecl *RD,
583 const ASTRecordLayout &Layout) {
584 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
585 E = RD->bases_end(); I != E; ++I) {
586 const CXXRecordDecl *BaseDecl =
587 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
589 // We only want to lay out virtual bases that aren't indirect primary bases
590 // of some other base.
591 if (I->isVirtual() && !IndirectPrimaryBases.count(BaseDecl)) {
592 // Only lay out the base once.
593 if (!LaidOutVirtualBases.insert(BaseDecl))
596 CharUnits vbaseOffset = Layout.getVBaseClassOffset(BaseDecl);
597 LayoutVirtualBase(BaseDecl, vbaseOffset);
600 if (!BaseDecl->getNumVBases()) {
601 // This base isn't interesting since it doesn't have any virtual bases.
605 LayoutVirtualBases(BaseDecl, Layout);
610 CGRecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl *RD,
611 const ASTRecordLayout &Layout) {
612 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
614 // Check if we need to add a vtable pointer.
615 if (RD->isDynamicClass()) {
617 const llvm::Type *FunctionType =
618 llvm::FunctionType::get(llvm::Type::getInt32Ty(Types.getLLVMContext()),
620 const llvm::Type *VTableTy = FunctionType->getPointerTo();
622 assert(NextFieldOffset.isZero() &&
623 "VTable pointer must come first!");
624 AppendField(CharUnits::Zero(), VTableTy->getPointerTo());
626 if (!Layout.isPrimaryBaseVirtual())
627 LayoutNonVirtualBase(PrimaryBase, CharUnits::Zero());
629 LayoutVirtualBase(PrimaryBase, CharUnits::Zero());
633 // Layout the non-virtual bases.
634 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
635 E = RD->bases_end(); I != E; ++I) {
639 const CXXRecordDecl *BaseDecl =
640 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
642 // We've already laid out the primary base.
643 if (BaseDecl == PrimaryBase && !Layout.isPrimaryBaseVirtual())
646 LayoutNonVirtualBase(BaseDecl, Layout.getBaseClassOffset(BaseDecl));
651 CGRecordLayoutBuilder::ComputeNonVirtualBaseType(const CXXRecordDecl *RD) {
652 const ASTRecordLayout &Layout = Types.getContext().getASTRecordLayout(RD);
654 CharUnits NonVirtualSize = Layout.getNonVirtualSize();
655 CharUnits NonVirtualAlign = Layout.getNonVirtualAlign();
656 CharUnits AlignedNonVirtualTypeSize =
657 NonVirtualSize.RoundUpToAlignment(NonVirtualAlign);
659 // First check if we can use the same fields as for the complete class.
660 CharUnits RecordSize = Layout.getSize();
661 if (AlignedNonVirtualTypeSize == RecordSize)
664 // Check if we need padding.
665 CharUnits AlignedNextFieldOffset =
666 NextFieldOffset.RoundUpToAlignment(getAlignmentAsLLVMStruct());
668 if (AlignedNextFieldOffset > AlignedNonVirtualTypeSize) {
669 assert(!Packed && "cannot layout even as packed struct");
670 return false; // Needs packing.
673 bool needsPadding = (AlignedNonVirtualTypeSize != AlignedNextFieldOffset);
675 CharUnits NumBytes = AlignedNonVirtualTypeSize - AlignedNextFieldOffset;
676 FieldTypes.push_back(getByteArrayType(NumBytes));
679 BaseSubobjectType = llvm::StructType::get(Types.getLLVMContext(),
683 // Pull the padding back off.
684 FieldTypes.pop_back();
690 bool CGRecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
691 assert(!D->isUnion() && "Can't call LayoutFields on a union!");
692 assert(!Alignment.isZero() && "Did not set alignment!");
694 const ASTRecordLayout &Layout = Types.getContext().getASTRecordLayout(D);
696 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D);
698 LayoutNonVirtualBases(RD, Layout);
700 unsigned FieldNo = 0;
702 for (RecordDecl::field_iterator Field = D->field_begin(),
703 FieldEnd = D->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
704 if (!LayoutField(*Field, Layout.getFieldOffset(FieldNo))) {
706 "Could not layout fields even with a packed LLVM struct!");
712 // We've laid out the non-virtual bases and the fields, now compute the
713 // non-virtual base field types.
714 if (!ComputeNonVirtualBaseType(RD)) {
715 assert(!Packed && "Could not layout even with a packed LLVM struct!");
719 // And lay out the virtual bases.
720 RD->getIndirectPrimaryBases(IndirectPrimaryBases);
721 if (Layout.isPrimaryBaseVirtual())
722 IndirectPrimaryBases.insert(Layout.getPrimaryBase());
723 LayoutVirtualBases(RD, Layout);
726 // Append tail padding if necessary.
727 AppendTailPadding(Types.getContext().toBits(Layout.getSize()));
732 void CGRecordLayoutBuilder::AppendTailPadding(uint64_t RecordSize) {
733 assert(RecordSize % 8 == 0 && "Invalid record size!");
735 CharUnits RecordSizeInBytes =
736 Types.getContext().toCharUnitsFromBits(RecordSize);
737 assert(NextFieldOffset <= RecordSizeInBytes && "Size mismatch!");
739 CharUnits AlignedNextFieldOffset =
740 NextFieldOffset.RoundUpToAlignment(getAlignmentAsLLVMStruct());
742 if (AlignedNextFieldOffset == RecordSizeInBytes) {
743 // We don't need any padding.
747 CharUnits NumPadBytes = RecordSizeInBytes - NextFieldOffset;
748 AppendBytes(NumPadBytes);
751 void CGRecordLayoutBuilder::AppendField(CharUnits fieldOffset,
752 const llvm::Type *fieldType) {
753 CharUnits fieldSize =
754 CharUnits::fromQuantity(Types.getTargetData().getTypeAllocSize(fieldType));
756 FieldTypes.push_back(fieldType);
758 NextFieldOffset = fieldOffset + fieldSize;
759 BitsAvailableInLastField = 0;
762 void CGRecordLayoutBuilder::AppendPadding(CharUnits fieldOffset,
763 CharUnits fieldAlignment) {
764 assert(NextFieldOffset <= fieldOffset &&
765 "Incorrect field layout!");
767 // Round up the field offset to the alignment of the field type.
768 CharUnits alignedNextFieldOffset =
769 NextFieldOffset.RoundUpToAlignment(fieldAlignment);
771 if (alignedNextFieldOffset < fieldOffset) {
772 // Even with alignment, the field offset is not at the right place,
774 CharUnits padding = fieldOffset - NextFieldOffset;
776 AppendBytes(padding);
780 const llvm::Type *CGRecordLayoutBuilder::getByteArrayType(CharUnits numBytes) {
781 assert(!numBytes.isZero() && "Empty byte arrays aren't allowed.");
783 const llvm::Type *Ty = llvm::Type::getInt8Ty(Types.getLLVMContext());
784 if (numBytes > CharUnits::One())
785 Ty = llvm::ArrayType::get(Ty, numBytes.getQuantity());
790 void CGRecordLayoutBuilder::AppendBytes(CharUnits numBytes) {
791 if (numBytes.isZero())
794 // Append the padding field
795 AppendField(NextFieldOffset, getByteArrayType(numBytes));
798 CharUnits CGRecordLayoutBuilder::getTypeAlignment(const llvm::Type *Ty) const {
800 return CharUnits::One();
802 return CharUnits::fromQuantity(Types.getTargetData().getABITypeAlignment(Ty));
805 CharUnits CGRecordLayoutBuilder::getAlignmentAsLLVMStruct() const {
807 return CharUnits::One();
809 CharUnits maxAlignment = CharUnits::One();
810 for (size_t i = 0; i != FieldTypes.size(); ++i)
811 maxAlignment = std::max(maxAlignment, getTypeAlignment(FieldTypes[i]));
816 /// Merge in whether a field of the given type is zero-initializable.
817 void CGRecordLayoutBuilder::CheckZeroInitializable(QualType T) {
818 // This record already contains a member pointer.
819 if (!IsZeroInitializableAsBase)
822 // Can only have member pointers if we're compiling C++.
823 if (!Types.getContext().getLangOptions().CPlusPlus)
826 const Type *elementType = T->getBaseElementTypeUnsafe();
828 if (const MemberPointerType *MPT = elementType->getAs<MemberPointerType>()) {
829 if (!Types.getCXXABI().isZeroInitializable(MPT))
830 IsZeroInitializable = IsZeroInitializableAsBase = false;
831 } else if (const RecordType *RT = elementType->getAs<RecordType>()) {
832 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
833 const CGRecordLayout &Layout = Types.getCGRecordLayout(RD);
834 if (!Layout.isZeroInitializable())
835 IsZeroInitializable = IsZeroInitializableAsBase = false;
839 CGRecordLayout *CodeGenTypes::ComputeRecordLayout(const RecordDecl *D) {
840 CGRecordLayoutBuilder Builder(*this);
844 const llvm::StructType *Ty = llvm::StructType::get(getLLVMContext(),
848 // If we're in C++, compute the base subobject type.
849 const llvm::StructType *BaseTy = 0;
850 if (isa<CXXRecordDecl>(D)) {
851 BaseTy = Builder.BaseSubobjectType;
852 if (!BaseTy) BaseTy = Ty;
856 new CGRecordLayout(Ty, BaseTy, Builder.IsZeroInitializable,
857 Builder.IsZeroInitializableAsBase);
859 RL->NonVirtualBases.swap(Builder.NonVirtualBases);
860 RL->CompleteObjectVirtualBases.swap(Builder.VirtualBases);
862 // Add all the field numbers.
863 RL->FieldInfo.swap(Builder.Fields);
865 // Add bitfield info.
866 RL->BitFields.swap(Builder.BitFields);
868 // Dump the layout, if requested.
869 if (getContext().getLangOptions().DumpRecordLayouts) {
870 llvm::errs() << "\n*** Dumping IRgen Record Layout\n";
871 llvm::errs() << "Record: ";
873 llvm::errs() << "\nLayout: ";
878 // Verify that the computed LLVM struct size matches the AST layout size.
879 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(D);
881 uint64_t TypeSizeInBits = getContext().toBits(Layout.getSize());
882 assert(TypeSizeInBits == getTargetData().getTypeAllocSizeInBits(Ty) &&
883 "Type size mismatch!");
886 CharUnits NonVirtualSize = Layout.getNonVirtualSize();
887 CharUnits NonVirtualAlign = Layout.getNonVirtualAlign();
888 CharUnits AlignedNonVirtualTypeSize =
889 NonVirtualSize.RoundUpToAlignment(NonVirtualAlign);
891 uint64_t AlignedNonVirtualTypeSizeInBits =
892 getContext().toBits(AlignedNonVirtualTypeSize);
894 assert(AlignedNonVirtualTypeSizeInBits ==
895 getTargetData().getTypeAllocSizeInBits(BaseTy) &&
896 "Type size mismatch!");
899 // Verify that the LLVM and AST field offsets agree.
900 const llvm::StructType *ST =
901 dyn_cast<llvm::StructType>(RL->getLLVMType());
902 const llvm::StructLayout *SL = getTargetData().getStructLayout(ST);
904 const ASTRecordLayout &AST_RL = getContext().getASTRecordLayout(D);
905 RecordDecl::field_iterator it = D->field_begin();
906 for (unsigned i = 0, e = AST_RL.getFieldCount(); i != e; ++i, ++it) {
907 const FieldDecl *FD = *it;
909 // For non-bit-fields, just check that the LLVM struct offset matches the
911 if (!FD->isBitField()) {
912 unsigned FieldNo = RL->getLLVMFieldNo(FD);
913 assert(AST_RL.getFieldOffset(i) == SL->getElementOffsetInBits(FieldNo) &&
914 "Invalid field offset!");
918 // Ignore unnamed bit-fields.
919 if (!FD->getDeclName())
922 const CGBitFieldInfo &Info = RL->getBitFieldInfo(FD);
923 for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) {
924 const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i);
926 // Verify that every component access is within the structure.
927 uint64_t FieldOffset = SL->getElementOffsetInBits(AI.FieldIndex);
928 uint64_t AccessBitOffset = FieldOffset +
929 getContext().toBits(CharUnits::fromQuantity(AI.FieldByteOffset));
930 assert(AccessBitOffset + AI.AccessWidth <= TypeSizeInBits &&
931 "Invalid bit-field access (out of range)!");
939 void CGRecordLayout::print(llvm::raw_ostream &OS) const {
940 OS << "<CGRecordLayout\n";
941 OS << " LLVMType:" << *CompleteObjectType << "\n";
942 if (BaseSubobjectType)
943 OS << " NonVirtualBaseLLVMType:" << *BaseSubobjectType << "\n";
944 OS << " IsZeroInitializable:" << IsZeroInitializable << "\n";
945 OS << " BitFields:[\n";
947 // Print bit-field infos in declaration order.
948 std::vector<std::pair<unsigned, const CGBitFieldInfo*> > BFIs;
949 for (llvm::DenseMap<const FieldDecl*, CGBitFieldInfo>::const_iterator
950 it = BitFields.begin(), ie = BitFields.end();
952 const RecordDecl *RD = it->first->getParent();
954 for (RecordDecl::field_iterator
955 it2 = RD->field_begin(); *it2 != it->first; ++it2)
957 BFIs.push_back(std::make_pair(Index, &it->second));
959 llvm::array_pod_sort(BFIs.begin(), BFIs.end());
960 for (unsigned i = 0, e = BFIs.size(); i != e; ++i) {
962 BFIs[i].second->print(OS);
969 void CGRecordLayout::dump() const {
973 void CGBitFieldInfo::print(llvm::raw_ostream &OS) const {
974 OS << "<CGBitFieldInfo";
975 OS << " Size:" << Size;
976 OS << " IsSigned:" << IsSigned << "\n";
978 OS.indent(4 + strlen("<CGBitFieldInfo"));
979 OS << " NumComponents:" << getNumComponents();
980 OS << " Components: [";
981 if (getNumComponents()) {
983 for (unsigned i = 0, e = getNumComponents(); i != e; ++i) {
984 const AccessInfo &AI = getComponent(i);
987 << " FieldIndex:" << AI.FieldIndex
988 << " FieldByteOffset:" << AI.FieldByteOffset
989 << " FieldBitStart:" << AI.FieldBitStart
990 << " AccessWidth:" << AI.AccessWidth << "\n";
991 OS.indent(8 + strlen("<AccessInfo"));
992 OS << " AccessAlignment:" << AI.AccessAlignment
993 << " TargetBitOffset:" << AI.TargetBitOffset
994 << " TargetBitWidth:" << AI.TargetBitWidth
1002 void CGBitFieldInfo::dump() const {
1003 print(llvm::errs());