1 //=== RecordLayoutBuilder.cpp - Helper class for building record layouts ---==//
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 #include "clang/AST/ASTContext.h"
11 #include "clang/AST/Attr.h"
12 #include "clang/AST/CXXInheritance.h"
13 #include "clang/AST/Decl.h"
14 #include "clang/AST/DeclCXX.h"
15 #include "clang/AST/DeclObjC.h"
16 #include "clang/AST/Expr.h"
17 #include "clang/AST/RecordLayout.h"
18 #include "clang/Basic/TargetInfo.h"
19 #include "clang/Sema/SemaDiagnostic.h"
20 #include "llvm/Support/Format.h"
21 #include "llvm/ADT/SmallSet.h"
22 #include "llvm/Support/MathExtras.h"
23 #include "llvm/Support/CrashRecoveryContext.h"
25 using namespace clang;
29 /// BaseSubobjectInfo - Represents a single base subobject in a complete class.
30 /// For a class hierarchy like
34 /// class C : A, B { };
36 /// The BaseSubobjectInfo graph for C will have three BaseSubobjectInfo
37 /// instances, one for B and two for A.
39 /// If a base is virtual, it will only have one BaseSubobjectInfo allocated.
40 struct BaseSubobjectInfo {
41 /// Class - The class for this base info.
42 const CXXRecordDecl *Class;
44 /// IsVirtual - Whether the BaseInfo represents a virtual base or not.
47 /// Bases - Information about the base subobjects.
48 SmallVector<BaseSubobjectInfo*, 4> Bases;
50 /// PrimaryVirtualBaseInfo - Holds the base info for the primary virtual base
51 /// of this base info (if one exists).
52 BaseSubobjectInfo *PrimaryVirtualBaseInfo;
55 const BaseSubobjectInfo *Derived;
58 /// EmptySubobjectMap - Keeps track of which empty subobjects exist at different
59 /// offsets while laying out a C++ class.
60 class EmptySubobjectMap {
61 const ASTContext &Context;
64 /// Class - The class whose empty entries we're keeping track of.
65 const CXXRecordDecl *Class;
67 /// EmptyClassOffsets - A map from offsets to empty record decls.
68 typedef SmallVector<const CXXRecordDecl *, 1> ClassVectorTy;
69 typedef llvm::DenseMap<CharUnits, ClassVectorTy> EmptyClassOffsetsMapTy;
70 EmptyClassOffsetsMapTy EmptyClassOffsets;
72 /// MaxEmptyClassOffset - The highest offset known to contain an empty
74 CharUnits MaxEmptyClassOffset;
76 /// ComputeEmptySubobjectSizes - Compute the size of the largest base or
77 /// member subobject that is empty.
78 void ComputeEmptySubobjectSizes();
80 void AddSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset);
82 void UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
83 CharUnits Offset, bool PlacingEmptyBase);
85 void UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
86 const CXXRecordDecl *Class,
88 void UpdateEmptyFieldSubobjects(const FieldDecl *FD, CharUnits Offset);
90 /// AnyEmptySubobjectsBeyondOffset - Returns whether there are any empty
91 /// subobjects beyond the given offset.
92 bool AnyEmptySubobjectsBeyondOffset(CharUnits Offset) const {
93 return Offset <= MaxEmptyClassOffset;
97 getFieldOffset(const ASTRecordLayout &Layout, unsigned FieldNo) const {
98 uint64_t FieldOffset = Layout.getFieldOffset(FieldNo);
99 assert(FieldOffset % CharWidth == 0 &&
100 "Field offset not at char boundary!");
102 return Context.toCharUnitsFromBits(FieldOffset);
106 bool CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
107 CharUnits Offset) const;
109 bool CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
112 bool CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
113 const CXXRecordDecl *Class,
114 CharUnits Offset) const;
115 bool CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
116 CharUnits Offset) const;
119 /// This holds the size of the largest empty subobject (either a base
120 /// or a member). Will be zero if the record being built doesn't contain
121 /// any empty classes.
122 CharUnits SizeOfLargestEmptySubobject;
124 EmptySubobjectMap(const ASTContext &Context, const CXXRecordDecl *Class)
125 : Context(Context), CharWidth(Context.getCharWidth()), Class(Class) {
126 ComputeEmptySubobjectSizes();
129 /// CanPlaceBaseAtOffset - Return whether the given base class can be placed
130 /// at the given offset.
131 /// Returns false if placing the record will result in two components
132 /// (direct or indirect) of the same type having the same offset.
133 bool CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
136 /// CanPlaceFieldAtOffset - Return whether a field can be placed at the given
138 bool CanPlaceFieldAtOffset(const FieldDecl *FD, CharUnits Offset);
141 void EmptySubobjectMap::ComputeEmptySubobjectSizes() {
143 for (CXXRecordDecl::base_class_const_iterator I = Class->bases_begin(),
144 E = Class->bases_end(); I != E; ++I) {
145 const CXXRecordDecl *BaseDecl =
146 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
149 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
150 if (BaseDecl->isEmpty()) {
151 // If the class decl is empty, get its size.
152 EmptySize = Layout.getSize();
154 // Otherwise, we get the largest empty subobject for the decl.
155 EmptySize = Layout.getSizeOfLargestEmptySubobject();
158 if (EmptySize > SizeOfLargestEmptySubobject)
159 SizeOfLargestEmptySubobject = EmptySize;
163 for (CXXRecordDecl::field_iterator I = Class->field_begin(),
164 E = Class->field_end(); I != E; ++I) {
166 const RecordType *RT =
167 Context.getBaseElementType(I->getType())->getAs<RecordType>();
169 // We only care about record types.
174 const CXXRecordDecl *MemberDecl = cast<CXXRecordDecl>(RT->getDecl());
175 const ASTRecordLayout &Layout = Context.getASTRecordLayout(MemberDecl);
176 if (MemberDecl->isEmpty()) {
177 // If the class decl is empty, get its size.
178 EmptySize = Layout.getSize();
180 // Otherwise, we get the largest empty subobject for the decl.
181 EmptySize = Layout.getSizeOfLargestEmptySubobject();
184 if (EmptySize > SizeOfLargestEmptySubobject)
185 SizeOfLargestEmptySubobject = EmptySize;
190 EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
191 CharUnits Offset) const {
192 // We only need to check empty bases.
196 EmptyClassOffsetsMapTy::const_iterator I = EmptyClassOffsets.find(Offset);
197 if (I == EmptyClassOffsets.end())
200 const ClassVectorTy& Classes = I->second;
201 if (std::find(Classes.begin(), Classes.end(), RD) == Classes.end())
204 // There is already an empty class of the same type at this offset.
208 void EmptySubobjectMap::AddSubobjectAtOffset(const CXXRecordDecl *RD,
210 // We only care about empty bases.
214 // If we have empty structures inside an union, we can assign both
215 // the same offset. Just avoid pushing them twice in the list.
216 ClassVectorTy& Classes = EmptyClassOffsets[Offset];
217 if (std::find(Classes.begin(), Classes.end(), RD) != Classes.end())
220 Classes.push_back(RD);
222 // Update the empty class offset.
223 if (Offset > MaxEmptyClassOffset)
224 MaxEmptyClassOffset = Offset;
228 EmptySubobjectMap::CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
230 // We don't have to keep looking past the maximum offset that's known to
231 // contain an empty class.
232 if (!AnyEmptySubobjectsBeyondOffset(Offset))
235 if (!CanPlaceSubobjectAtOffset(Info->Class, Offset))
238 // Traverse all non-virtual bases.
239 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
240 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
241 BaseSubobjectInfo* Base = Info->Bases[I];
245 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
247 if (!CanPlaceBaseSubobjectAtOffset(Base, BaseOffset))
251 if (Info->PrimaryVirtualBaseInfo) {
252 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
254 if (Info == PrimaryVirtualBaseInfo->Derived) {
255 if (!CanPlaceBaseSubobjectAtOffset(PrimaryVirtualBaseInfo, Offset))
260 // Traverse all member variables.
261 unsigned FieldNo = 0;
262 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
263 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
267 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
268 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
275 void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
277 bool PlacingEmptyBase) {
278 if (!PlacingEmptyBase && Offset >= SizeOfLargestEmptySubobject) {
279 // We know that the only empty subobjects that can conflict with empty
280 // subobject of non-empty bases, are empty bases that can be placed at
281 // offset zero. Because of this, we only need to keep track of empty base
282 // subobjects with offsets less than the size of the largest empty
283 // subobject for our class.
287 AddSubobjectAtOffset(Info->Class, Offset);
289 // Traverse all non-virtual bases.
290 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
291 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
292 BaseSubobjectInfo* Base = Info->Bases[I];
296 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
297 UpdateEmptyBaseSubobjects(Base, BaseOffset, PlacingEmptyBase);
300 if (Info->PrimaryVirtualBaseInfo) {
301 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
303 if (Info == PrimaryVirtualBaseInfo->Derived)
304 UpdateEmptyBaseSubobjects(PrimaryVirtualBaseInfo, Offset,
308 // Traverse all member variables.
309 unsigned FieldNo = 0;
310 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
311 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
315 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
316 UpdateEmptyFieldSubobjects(*I, FieldOffset);
320 bool EmptySubobjectMap::CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
322 // If we know this class doesn't have any empty subobjects we don't need to
324 if (SizeOfLargestEmptySubobject.isZero())
327 if (!CanPlaceBaseSubobjectAtOffset(Info, Offset))
330 // We are able to place the base at this offset. Make sure to update the
331 // empty base subobject map.
332 UpdateEmptyBaseSubobjects(Info, Offset, Info->Class->isEmpty());
337 EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
338 const CXXRecordDecl *Class,
339 CharUnits Offset) const {
340 // We don't have to keep looking past the maximum offset that's known to
341 // contain an empty class.
342 if (!AnyEmptySubobjectsBeyondOffset(Offset))
345 if (!CanPlaceSubobjectAtOffset(RD, Offset))
348 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
350 // Traverse all non-virtual bases.
351 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
352 E = RD->bases_end(); I != E; ++I) {
356 const CXXRecordDecl *BaseDecl =
357 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
359 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
360 if (!CanPlaceFieldSubobjectAtOffset(BaseDecl, Class, BaseOffset))
365 // This is the most derived class, traverse virtual bases as well.
366 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
367 E = RD->vbases_end(); I != E; ++I) {
368 const CXXRecordDecl *VBaseDecl =
369 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
371 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
372 if (!CanPlaceFieldSubobjectAtOffset(VBaseDecl, Class, VBaseOffset))
377 // Traverse all member variables.
378 unsigned FieldNo = 0;
379 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
380 I != E; ++I, ++FieldNo) {
384 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
386 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
394 EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
395 CharUnits Offset) const {
396 // We don't have to keep looking past the maximum offset that's known to
397 // contain an empty class.
398 if (!AnyEmptySubobjectsBeyondOffset(Offset))
401 QualType T = FD->getType();
402 if (const RecordType *RT = T->getAs<RecordType>()) {
403 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
404 return CanPlaceFieldSubobjectAtOffset(RD, RD, Offset);
407 // If we have an array type we need to look at every element.
408 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
409 QualType ElemTy = Context.getBaseElementType(AT);
410 const RecordType *RT = ElemTy->getAs<RecordType>();
414 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
415 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
417 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
418 CharUnits ElementOffset = Offset;
419 for (uint64_t I = 0; I != NumElements; ++I) {
420 // We don't have to keep looking past the maximum offset that's known to
421 // contain an empty class.
422 if (!AnyEmptySubobjectsBeyondOffset(ElementOffset))
425 if (!CanPlaceFieldSubobjectAtOffset(RD, RD, ElementOffset))
428 ElementOffset += Layout.getSize();
436 EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl *FD,
438 if (!CanPlaceFieldSubobjectAtOffset(FD, Offset))
441 // We are able to place the member variable at this offset.
442 // Make sure to update the empty base subobject map.
443 UpdateEmptyFieldSubobjects(FD, Offset);
447 void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
448 const CXXRecordDecl *Class,
450 // We know that the only empty subobjects that can conflict with empty
451 // field subobjects are subobjects of empty bases that can be placed at offset
452 // zero. Because of this, we only need to keep track of empty field
453 // subobjects with offsets less than the size of the largest empty
454 // subobject for our class.
455 if (Offset >= SizeOfLargestEmptySubobject)
458 AddSubobjectAtOffset(RD, Offset);
460 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
462 // Traverse all non-virtual bases.
463 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
464 E = RD->bases_end(); I != E; ++I) {
468 const CXXRecordDecl *BaseDecl =
469 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
471 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
472 UpdateEmptyFieldSubobjects(BaseDecl, Class, BaseOffset);
476 // This is the most derived class, traverse virtual bases as well.
477 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
478 E = RD->vbases_end(); I != E; ++I) {
479 const CXXRecordDecl *VBaseDecl =
480 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
482 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
483 UpdateEmptyFieldSubobjects(VBaseDecl, Class, VBaseOffset);
487 // Traverse all member variables.
488 unsigned FieldNo = 0;
489 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
490 I != E; ++I, ++FieldNo) {
494 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
496 UpdateEmptyFieldSubobjects(*I, FieldOffset);
500 void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const FieldDecl *FD,
502 QualType T = FD->getType();
503 if (const RecordType *RT = T->getAs<RecordType>()) {
504 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
505 UpdateEmptyFieldSubobjects(RD, RD, Offset);
509 // If we have an array type we need to update every element.
510 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
511 QualType ElemTy = Context.getBaseElementType(AT);
512 const RecordType *RT = ElemTy->getAs<RecordType>();
516 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
517 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
519 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
520 CharUnits ElementOffset = Offset;
522 for (uint64_t I = 0; I != NumElements; ++I) {
523 // We know that the only empty subobjects that can conflict with empty
524 // field subobjects are subobjects of empty bases that can be placed at
525 // offset zero. Because of this, we only need to keep track of empty field
526 // subobjects with offsets less than the size of the largest empty
527 // subobject for our class.
528 if (ElementOffset >= SizeOfLargestEmptySubobject)
531 UpdateEmptyFieldSubobjects(RD, RD, ElementOffset);
532 ElementOffset += Layout.getSize();
537 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> ClassSetTy;
539 class RecordLayoutBuilder {
541 // FIXME: Remove this and make the appropriate fields public.
542 friend class clang::ASTContext;
544 const ASTContext &Context;
546 EmptySubobjectMap *EmptySubobjects;
548 /// Size - The current size of the record layout.
551 /// Alignment - The current alignment of the record layout.
554 /// \brief The alignment if attribute packed is not used.
555 CharUnits UnpackedAlignment;
557 SmallVector<uint64_t, 16> FieldOffsets;
559 /// \brief Whether the external AST source has provided a layout for this
561 unsigned ExternalLayout : 1;
563 /// \brief Whether we need to infer alignment, even when we have an
564 /// externally-provided layout.
565 unsigned InferAlignment : 1;
567 /// Packed - Whether the record is packed or not.
570 unsigned IsUnion : 1;
572 unsigned IsMac68kAlign : 1;
574 unsigned IsMsStruct : 1;
576 /// UnfilledBitsInLastByte - If the last field laid out was a bitfield,
577 /// this contains the number of bits in the last byte that can be used for
578 /// an adjacent bitfield if necessary.
579 unsigned char UnfilledBitsInLastByte;
581 /// MaxFieldAlignment - The maximum allowed field alignment. This is set by
583 CharUnits MaxFieldAlignment;
585 /// DataSize - The data size of the record being laid out.
588 CharUnits NonVirtualSize;
589 CharUnits NonVirtualAlignment;
591 FieldDecl *ZeroLengthBitfield;
593 /// PrimaryBase - the primary base class (if one exists) of the class
594 /// we're laying out.
595 const CXXRecordDecl *PrimaryBase;
597 /// PrimaryBaseIsVirtual - Whether the primary base of the class we're laying
599 bool PrimaryBaseIsVirtual;
601 /// HasOwnVFPtr - Whether the class provides its own vtable/vftbl
602 /// pointer, as opposed to inheriting one from a primary base class.
605 /// VBPtrOffset - Virtual base table offset. Only for MS layout.
606 CharUnits VBPtrOffset;
608 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
610 /// Bases - base classes and their offsets in the record.
611 BaseOffsetsMapTy Bases;
613 // VBases - virtual base classes and their offsets in the record.
614 ASTRecordLayout::VBaseOffsetsMapTy VBases;
616 /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are
617 /// primary base classes for some other direct or indirect base class.
618 CXXIndirectPrimaryBaseSet IndirectPrimaryBases;
620 /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in
621 /// inheritance graph order. Used for determining the primary base class.
622 const CXXRecordDecl *FirstNearlyEmptyVBase;
624 /// VisitedVirtualBases - A set of all the visited virtual bases, used to
625 /// avoid visiting virtual bases more than once.
626 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
628 /// \brief Externally-provided size.
629 uint64_t ExternalSize;
631 /// \brief Externally-provided alignment.
632 uint64_t ExternalAlign;
634 /// \brief Externally-provided field offsets.
635 llvm::DenseMap<const FieldDecl *, uint64_t> ExternalFieldOffsets;
637 /// \brief Externally-provided direct, non-virtual base offsets.
638 llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalBaseOffsets;
640 /// \brief Externally-provided virtual base offsets.
641 llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalVirtualBaseOffsets;
643 RecordLayoutBuilder(const ASTContext &Context,
644 EmptySubobjectMap *EmptySubobjects)
645 : Context(Context), EmptySubobjects(EmptySubobjects), Size(0),
646 Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()),
647 ExternalLayout(false), InferAlignment(false),
648 Packed(false), IsUnion(false), IsMac68kAlign(false), IsMsStruct(false),
649 UnfilledBitsInLastByte(0), MaxFieldAlignment(CharUnits::Zero()),
650 DataSize(0), NonVirtualSize(CharUnits::Zero()),
651 NonVirtualAlignment(CharUnits::One()),
652 ZeroLengthBitfield(0), PrimaryBase(0),
653 PrimaryBaseIsVirtual(false),
655 VBPtrOffset(CharUnits::fromQuantity(-1)),
656 FirstNearlyEmptyVBase(0) { }
658 /// Reset this RecordLayoutBuilder to a fresh state, using the given
659 /// alignment as the initial alignment. This is used for the
660 /// correct layout of vb-table pointers in MSVC.
661 void resetWithTargetAlignment(CharUnits TargetAlignment) {
662 const ASTContext &Context = this->Context;
663 EmptySubobjectMap *EmptySubobjects = this->EmptySubobjects;
664 this->~RecordLayoutBuilder();
665 new (this) RecordLayoutBuilder(Context, EmptySubobjects);
666 Alignment = UnpackedAlignment = TargetAlignment;
669 void Layout(const RecordDecl *D);
670 void Layout(const CXXRecordDecl *D);
671 void Layout(const ObjCInterfaceDecl *D);
673 void LayoutFields(const RecordDecl *D);
674 void LayoutField(const FieldDecl *D);
675 void LayoutWideBitField(uint64_t FieldSize, uint64_t TypeSize,
676 bool FieldPacked, const FieldDecl *D);
677 void LayoutBitField(const FieldDecl *D);
679 bool isMicrosoftCXXABI() const {
680 return Context.getTargetInfo().getCXXABI() == CXXABI_Microsoft;
683 void MSLayoutVirtualBases(const CXXRecordDecl *RD);
685 /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects.
686 llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator;
688 typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *>
689 BaseSubobjectInfoMapTy;
691 /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases
692 /// of the class we're laying out to their base subobject info.
693 BaseSubobjectInfoMapTy VirtualBaseInfo;
695 /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the
696 /// class we're laying out to their base subobject info.
697 BaseSubobjectInfoMapTy NonVirtualBaseInfo;
699 /// ComputeBaseSubobjectInfo - Compute the base subobject information for the
700 /// bases of the given class.
701 void ComputeBaseSubobjectInfo(const CXXRecordDecl *RD);
703 /// ComputeBaseSubobjectInfo - Compute the base subobject information for a
704 /// single class and all of its base classes.
705 BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
707 BaseSubobjectInfo *Derived);
709 /// DeterminePrimaryBase - Determine the primary base of the given class.
710 void DeterminePrimaryBase(const CXXRecordDecl *RD);
712 void SelectPrimaryVBase(const CXXRecordDecl *RD);
714 void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign);
716 /// LayoutNonVirtualBases - Determines the primary base class (if any) and
717 /// lays it out. Will then proceed to lay out all non-virtual base clasess.
718 void LayoutNonVirtualBases(const CXXRecordDecl *RD);
720 /// LayoutNonVirtualBase - Lays out a single non-virtual base.
721 void LayoutNonVirtualBase(const BaseSubobjectInfo *Base);
723 void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
726 bool needsVFTable(const CXXRecordDecl *RD) const;
727 bool hasNewVirtualFunction(const CXXRecordDecl *RD,
728 bool IgnoreDestructor = false) const;
729 bool isPossiblePrimaryBase(const CXXRecordDecl *Base) const;
731 void computeVtordisps(const CXXRecordDecl *RD,
732 ClassSetTy &VtordispVBases);
734 /// LayoutVirtualBases - Lays out all the virtual bases.
735 void LayoutVirtualBases(const CXXRecordDecl *RD,
736 const CXXRecordDecl *MostDerivedClass);
738 /// LayoutVirtualBase - Lays out a single virtual base.
739 void LayoutVirtualBase(const BaseSubobjectInfo *Base,
740 bool IsVtordispNeed = false);
742 /// LayoutBase - Will lay out a base and return the offset where it was
743 /// placed, in chars.
744 CharUnits LayoutBase(const BaseSubobjectInfo *Base);
746 /// InitializeLayout - Initialize record layout for the given record decl.
747 void InitializeLayout(const Decl *D);
749 /// FinishLayout - Finalize record layout. Adjust record size based on the
751 void FinishLayout(const NamedDecl *D);
753 void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment);
754 void UpdateAlignment(CharUnits NewAlignment) {
755 UpdateAlignment(NewAlignment, NewAlignment);
758 /// \brief Retrieve the externally-supplied field offset for the given
761 /// \param Field The field whose offset is being queried.
762 /// \param ComputedOffset The offset that we've computed for this field.
763 uint64_t updateExternalFieldOffset(const FieldDecl *Field,
764 uint64_t ComputedOffset);
766 void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset,
767 uint64_t UnpackedOffset, unsigned UnpackedAlign,
768 bool isPacked, const FieldDecl *D);
770 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
772 CharUnits getSize() const {
773 assert(Size % Context.getCharWidth() == 0);
774 return Context.toCharUnitsFromBits(Size);
776 uint64_t getSizeInBits() const { return Size; }
778 void setSize(CharUnits NewSize) { Size = Context.toBits(NewSize); }
779 void setSize(uint64_t NewSize) { Size = NewSize; }
781 CharUnits getAligment() const { return Alignment; }
783 CharUnits getDataSize() const {
784 assert(DataSize % Context.getCharWidth() == 0);
785 return Context.toCharUnitsFromBits(DataSize);
787 uint64_t getDataSizeInBits() const { return DataSize; }
789 void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); }
790 void setDataSize(uint64_t NewSize) { DataSize = NewSize; }
792 RecordLayoutBuilder(const RecordLayoutBuilder&); // DO NOT IMPLEMENT
793 void operator=(const RecordLayoutBuilder&); // DO NOT IMPLEMENT
795 static const CXXMethodDecl *ComputeKeyFunction(const CXXRecordDecl *RD);
797 } // end anonymous namespace
800 RecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) {
801 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
802 E = RD->bases_end(); I != E; ++I) {
803 assert(!I->getType()->isDependentType() &&
804 "Cannot layout class with dependent bases.");
806 const CXXRecordDecl *Base =
807 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
809 // Check if this is a nearly empty virtual base.
810 if (I->isVirtual() && Context.isNearlyEmpty(Base)) {
811 // If it's not an indirect primary base, then we've found our primary
813 if (!IndirectPrimaryBases.count(Base)) {
815 PrimaryBaseIsVirtual = true;
819 // Is this the first nearly empty virtual base?
820 if (!FirstNearlyEmptyVBase)
821 FirstNearlyEmptyVBase = Base;
824 SelectPrimaryVBase(Base);
830 /// DeterminePrimaryBase - Determine the primary base of the given class.
831 void RecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) {
832 // If the class isn't dynamic, it won't have a primary base.
833 if (!RD->isDynamicClass())
836 // Compute all the primary virtual bases for all of our direct and
837 // indirect bases, and record all their primary virtual base classes.
838 RD->getIndirectPrimaryBases(IndirectPrimaryBases);
840 // If the record has a dynamic base class, attempt to choose a primary base
841 // class. It is the first (in direct base class order) non-virtual dynamic
842 // base class, if one exists.
843 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
844 e = RD->bases_end(); i != e; ++i) {
845 // Ignore virtual bases.
849 const CXXRecordDecl *Base =
850 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
852 if (isPossiblePrimaryBase(Base)) {
855 PrimaryBaseIsVirtual = false;
860 // The Microsoft ABI doesn't have primary virtual bases.
861 if (isMicrosoftCXXABI()) {
862 assert(!PrimaryBase && "Should not get here with a primary base!");
866 // Under the Itanium ABI, if there is no non-virtual primary base class,
867 // try to compute the primary virtual base. The primary virtual base is
868 // the first nearly empty virtual base that is not an indirect primary
869 // virtual base class, if one exists.
870 if (RD->getNumVBases() != 0) {
871 SelectPrimaryVBase(RD);
876 // Otherwise, it is the first indirect primary base class, if one exists.
877 if (FirstNearlyEmptyVBase) {
878 PrimaryBase = FirstNearlyEmptyVBase;
879 PrimaryBaseIsVirtual = true;
883 assert(!PrimaryBase && "Should not get here with a primary base!");
887 RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
889 BaseSubobjectInfo *Derived) {
890 BaseSubobjectInfo *Info;
893 // Check if we already have info about this virtual base.
894 BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD];
896 assert(InfoSlot->Class == RD && "Wrong class for virtual base info!");
900 // We don't, create it.
901 InfoSlot = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
904 Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
908 Info->IsVirtual = IsVirtual;
910 Info->PrimaryVirtualBaseInfo = 0;
912 const CXXRecordDecl *PrimaryVirtualBase = 0;
913 BaseSubobjectInfo *PrimaryVirtualBaseInfo = 0;
915 // Check if this base has a primary virtual base.
916 if (RD->getNumVBases()) {
917 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
918 if (Layout.isPrimaryBaseVirtual()) {
919 // This base does have a primary virtual base.
920 PrimaryVirtualBase = Layout.getPrimaryBase();
921 assert(PrimaryVirtualBase && "Didn't have a primary virtual base!");
923 // Now check if we have base subobject info about this primary base.
924 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
926 if (PrimaryVirtualBaseInfo) {
927 if (PrimaryVirtualBaseInfo->Derived) {
928 // We did have info about this primary base, and it turns out that it
929 // has already been claimed as a primary virtual base for another
931 PrimaryVirtualBase = 0;
933 // We can claim this base as our primary base.
934 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
935 PrimaryVirtualBaseInfo->Derived = Info;
941 // Now go through all direct bases.
942 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
943 E = RD->bases_end(); I != E; ++I) {
944 bool IsVirtual = I->isVirtual();
946 const CXXRecordDecl *BaseDecl =
947 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
949 Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info));
952 if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) {
953 // Traversing the bases must have created the base info for our primary
955 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
956 assert(PrimaryVirtualBaseInfo &&
957 "Did not create a primary virtual base!");
959 // Claim the primary virtual base as our primary virtual base.
960 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
961 PrimaryVirtualBaseInfo->Derived = Info;
967 void RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD) {
968 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
969 E = RD->bases_end(); I != E; ++I) {
970 bool IsVirtual = I->isVirtual();
972 const CXXRecordDecl *BaseDecl =
973 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
975 // Compute the base subobject info for this base.
976 BaseSubobjectInfo *Info = ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, 0);
979 // ComputeBaseInfo has already added this base for us.
980 assert(VirtualBaseInfo.count(BaseDecl) &&
981 "Did not add virtual base!");
983 // Add the base info to the map of non-virtual bases.
984 assert(!NonVirtualBaseInfo.count(BaseDecl) &&
985 "Non-virtual base already exists!");
986 NonVirtualBaseInfo.insert(std::make_pair(BaseDecl, Info));
992 RecordLayoutBuilder::EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign) {
993 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
995 // The maximum field alignment overrides base align.
996 if (!MaxFieldAlignment.isZero()) {
997 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
998 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
1001 // Round up the current record size to pointer alignment.
1002 setSize(getSize().RoundUpToAlignment(BaseAlign));
1003 setDataSize(getSize());
1005 // Update the alignment.
1006 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
1010 RecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl *RD) {
1011 // Then, determine the primary base class.
1012 DeterminePrimaryBase(RD);
1014 // Compute base subobject info.
1015 ComputeBaseSubobjectInfo(RD);
1017 // If we have a primary base class, lay it out.
1019 if (PrimaryBaseIsVirtual) {
1020 // If the primary virtual base was a primary virtual base of some other
1021 // base class we'll have to steal it.
1022 BaseSubobjectInfo *PrimaryBaseInfo = VirtualBaseInfo.lookup(PrimaryBase);
1023 PrimaryBaseInfo->Derived = 0;
1025 // We have a virtual primary base, insert it as an indirect primary base.
1026 IndirectPrimaryBases.insert(PrimaryBase);
1028 assert(!VisitedVirtualBases.count(PrimaryBase) &&
1029 "vbase already visited!");
1030 VisitedVirtualBases.insert(PrimaryBase);
1032 LayoutVirtualBase(PrimaryBaseInfo);
1034 BaseSubobjectInfo *PrimaryBaseInfo =
1035 NonVirtualBaseInfo.lookup(PrimaryBase);
1036 assert(PrimaryBaseInfo &&
1037 "Did not find base info for non-virtual primary base!");
1039 LayoutNonVirtualBase(PrimaryBaseInfo);
1042 // If this class needs a vtable/vf-table and didn't get one from a
1043 // primary base, add it in now.
1044 } else if (needsVFTable(RD)) {
1045 assert(DataSize == 0 && "Vtable pointer must be at offset zero!");
1046 CharUnits PtrWidth =
1047 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
1048 CharUnits PtrAlign =
1049 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
1050 EnsureVTablePointerAlignment(PtrAlign);
1052 setSize(getSize() + PtrWidth);
1053 setDataSize(getSize());
1056 bool HasDirectVirtualBases = false;
1057 bool HasNonVirtualBaseWithVBTable = false;
1059 // Now lay out the non-virtual bases.
1060 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1061 E = RD->bases_end(); I != E; ++I) {
1063 // Ignore virtual bases, but remember that we saw one.
1064 if (I->isVirtual()) {
1065 HasDirectVirtualBases = true;
1069 const CXXRecordDecl *BaseDecl =
1070 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1072 // Remember if this base has virtual bases itself.
1073 if (BaseDecl->getNumVBases())
1074 HasNonVirtualBaseWithVBTable = true;
1076 // Skip the primary base, because we've already laid it out. The
1077 // !PrimaryBaseIsVirtual check is required because we might have a
1078 // non-virtual base of the same type as a primary virtual base.
1079 if (BaseDecl == PrimaryBase && !PrimaryBaseIsVirtual)
1082 // Lay out the base.
1083 BaseSubobjectInfo *BaseInfo = NonVirtualBaseInfo.lookup(BaseDecl);
1084 assert(BaseInfo && "Did not find base info for non-virtual base!");
1086 LayoutNonVirtualBase(BaseInfo);
1089 // In the MS ABI, add the vb-table pointer if we need one, which is
1090 // whenever we have a virtual base and we can't re-use a vb-table
1091 // pointer from a non-virtual base.
1092 if (isMicrosoftCXXABI() &&
1093 HasDirectVirtualBases && !HasNonVirtualBaseWithVBTable) {
1094 CharUnits PtrWidth =
1095 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
1096 CharUnits PtrAlign =
1097 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
1099 // MSVC potentially over-aligns the vb-table pointer by giving it
1100 // the max alignment of all the non-virtual objects in the class.
1101 // This is completely unnecessary, but we're not here to pass
1104 // Note that we've only laid out the non-virtual bases, so on the
1105 // first pass Alignment won't be set correctly here, but if the
1106 // vb-table doesn't end up aligned correctly we'll come through
1107 // and redo the layout from scratch with the right alignment.
1109 // TODO: Instead of doing this, just lay out the fields as if the
1110 // vb-table were at offset zero, then retroactively bump the field
1112 PtrAlign = std::max(PtrAlign, Alignment);
1114 EnsureVTablePointerAlignment(PtrAlign);
1115 VBPtrOffset = getSize();
1116 setSize(getSize() + PtrWidth);
1117 setDataSize(getSize());
1121 void RecordLayoutBuilder::LayoutNonVirtualBase(const BaseSubobjectInfo *Base) {
1123 CharUnits Offset = LayoutBase(Base);
1125 // Add its base class offset.
1126 assert(!Bases.count(Base->Class) && "base offset already exists!");
1127 Bases.insert(std::make_pair(Base->Class, Offset));
1129 AddPrimaryVirtualBaseOffsets(Base, Offset);
1133 RecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
1135 // This base isn't interesting, it has no virtual bases.
1136 if (!Info->Class->getNumVBases())
1139 // First, check if we have a virtual primary base to add offsets for.
1140 if (Info->PrimaryVirtualBaseInfo) {
1141 assert(Info->PrimaryVirtualBaseInfo->IsVirtual &&
1142 "Primary virtual base is not virtual!");
1143 if (Info->PrimaryVirtualBaseInfo->Derived == Info) {
1145 assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) &&
1146 "primary vbase offset already exists!");
1147 VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class,
1148 ASTRecordLayout::VBaseInfo(Offset, false)));
1150 // Traverse the primary virtual base.
1151 AddPrimaryVirtualBaseOffsets(Info->PrimaryVirtualBaseInfo, Offset);
1155 // Now go through all direct non-virtual bases.
1156 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
1157 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
1158 const BaseSubobjectInfo *Base = Info->Bases[I];
1159 if (Base->IsVirtual)
1162 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
1163 AddPrimaryVirtualBaseOffsets(Base, BaseOffset);
1167 /// needsVFTable - Return true if this class needs a vtable or vf-table
1168 /// when laid out as a base class. These are treated the same because
1169 /// they're both always laid out at offset zero.
1171 /// This function assumes that the class has no primary base.
1172 bool RecordLayoutBuilder::needsVFTable(const CXXRecordDecl *RD) const {
1173 assert(!PrimaryBase);
1175 // In the Itanium ABI, every dynamic class needs a vtable: even if
1176 // this class has no virtual functions as a base class (i.e. it's
1177 // non-polymorphic or only has virtual functions from virtual
1178 // bases),x it still needs a vtable to locate its virtual bases.
1179 if (!isMicrosoftCXXABI())
1180 return RD->isDynamicClass();
1182 // In the MS ABI, we need a vfptr if the class has virtual functions
1183 // other than those declared by its virtual bases. The AST doesn't
1184 // tell us that directly, and checking manually for virtual
1185 // functions that aren't overrides is expensive, but there are
1186 // some important shortcuts:
1188 // - Non-polymorphic classes have no virtual functions at all.
1189 if (!RD->isPolymorphic()) return false;
1191 // - Polymorphic classes with no virtual bases must either declare
1192 // virtual functions directly or inherit them, but in the latter
1193 // case we would have a primary base.
1194 if (RD->getNumVBases() == 0) return true;
1196 return hasNewVirtualFunction(RD);
1199 /// Does the given class inherit non-virtually from any of the classes
1200 /// in the given set?
1201 static bool hasNonVirtualBaseInSet(const CXXRecordDecl *RD,
1202 const ClassSetTy &set) {
1203 for (CXXRecordDecl::base_class_const_iterator
1204 I = RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
1205 // Ignore virtual links.
1206 if (I->isVirtual()) continue;
1208 // Check whether the set contains the base.
1209 const CXXRecordDecl *base = I->getType()->getAsCXXRecordDecl();
1210 if (set.count(base))
1213 // Otherwise, recurse and propagate.
1214 if (hasNonVirtualBaseInSet(base, set))
1221 /// Does the given method (B::foo()) already override a method (A::foo())
1222 /// such that A requires a vtordisp in B? If so, we don't need to add a
1223 /// new vtordisp for B in a yet-more-derived class C providing C::foo().
1224 static bool overridesMethodRequiringVtorDisp(const ASTContext &Context,
1225 const CXXMethodDecl *M) {
1226 CXXMethodDecl::method_iterator
1227 I = M->begin_overridden_methods(), E = M->end_overridden_methods();
1228 if (I == E) return false;
1230 const ASTRecordLayout::VBaseOffsetsMapTy &offsets =
1231 Context.getASTRecordLayout(M->getParent()).getVBaseOffsetsMap();
1233 const CXXMethodDecl *overridden = *I;
1235 // If the overridden method's class isn't recognized as a virtual
1236 // base in the derived class, ignore it.
1237 ASTRecordLayout::VBaseOffsetsMapTy::const_iterator
1238 it = offsets.find(overridden->getParent());
1239 if (it == offsets.end()) continue;
1241 // Otherwise, check if the overridden method's class needs a vtordisp.
1242 if (it->second.hasVtorDisp()) return true;
1248 /// In the Microsoft ABI, decide which of the virtual bases require a
1250 void RecordLayoutBuilder::computeVtordisps(const CXXRecordDecl *RD,
1251 ClassSetTy &vtordispVBases) {
1252 // Bail out if we have no virtual bases.
1253 assert(RD->getNumVBases());
1255 // Build up the set of virtual bases that we haven't decided yet.
1256 ClassSetTy undecidedVBases;
1257 for (CXXRecordDecl::base_class_const_iterator
1258 I = RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
1259 const CXXRecordDecl *vbase = I->getType()->getAsCXXRecordDecl();
1260 undecidedVBases.insert(vbase);
1262 assert(!undecidedVBases.empty());
1264 // A virtual base requires a vtordisp field in a derived class if it
1265 // requires a vtordisp field in a base class. Walk all the direct
1266 // bases and collect this information.
1267 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1268 E = RD->bases_end(); I != E; ++I) {
1269 const CXXRecordDecl *base = I->getType()->getAsCXXRecordDecl();
1270 const ASTRecordLayout &baseLayout = Context.getASTRecordLayout(base);
1272 // Iterate over the set of virtual bases provided by this class.
1273 for (ASTRecordLayout::VBaseOffsetsMapTy::const_iterator
1274 VI = baseLayout.getVBaseOffsetsMap().begin(),
1275 VE = baseLayout.getVBaseOffsetsMap().end(); VI != VE; ++VI) {
1276 // If it doesn't need a vtordisp in this base, ignore it.
1277 if (!VI->second.hasVtorDisp()) continue;
1279 // If we've already seen it and decided it needs a vtordisp, ignore it.
1280 if (!undecidedVBases.erase(VI->first))
1284 vtordispVBases.insert(VI->first);
1286 // Quit as soon as we've decided everything.
1287 if (undecidedVBases.empty())
1292 // Okay, we have virtual bases that we haven't yet decided about. A
1293 // virtual base requires a vtordisp if any the non-destructor
1294 // virtual methods declared in this class directly override a method
1295 // provided by that virtual base. (If so, we need to emit a thunk
1296 // for that method, to be used in the construction vftable, which
1297 // applies an additional 'vtordisp' this-adjustment.)
1299 // Collect the set of bases directly overridden by any method in this class.
1300 // It's possible that some of these classes won't be virtual bases, or won't be
1301 // provided by virtual bases, or won't be virtual bases in the overridden
1302 // instance but are virtual bases elsewhere. Only the last matters for what
1303 // we're doing, and we can ignore those: if we don't directly override
1304 // a method provided by a virtual copy of a base class, but we do directly
1305 // override a method provided by a non-virtual copy of that base class,
1306 // then we must indirectly override the method provided by the virtual base,
1307 // and so we should already have collected it in the loop above.
1308 ClassSetTy overriddenBases;
1309 for (CXXRecordDecl::method_iterator
1310 M = RD->method_begin(), E = RD->method_end(); M != E; ++M) {
1311 // Ignore non-virtual methods and destructors.
1312 if (isa<CXXDestructorDecl>(*M) || !M->isVirtual())
1315 for (CXXMethodDecl::method_iterator I = M->begin_overridden_methods(),
1316 E = M->end_overridden_methods(); I != E; ++I) {
1317 const CXXMethodDecl *overriddenMethod = (*I);
1319 // Ignore methods that override methods from vbases that require
1320 // require vtordisps.
1321 if (overridesMethodRequiringVtorDisp(Context, overriddenMethod))
1324 // As an optimization, check immediately whether we're overriding
1325 // something from the undecided set.
1326 const CXXRecordDecl *overriddenBase = overriddenMethod->getParent();
1327 if (undecidedVBases.erase(overriddenBase)) {
1328 vtordispVBases.insert(overriddenBase);
1329 if (undecidedVBases.empty()) return;
1331 // We can't 'continue;' here because one of our undecided
1332 // vbases might non-virtually inherit from this base.
1334 // struct A { virtual void foo(); };
1336 // struct C : virtual A, virtual B { virtual void foo(); };
1337 // We need a vtordisp for B here.
1340 // Otherwise, just collect it.
1341 overriddenBases.insert(overriddenBase);
1345 // Walk the undecided v-bases and check whether they (non-virtually)
1346 // provide any of the overridden bases. We don't need to consider
1347 // virtual links because the vtordisp inheres to the layout
1348 // subobject containing the base.
1349 for (ClassSetTy::const_iterator
1350 I = undecidedVBases.begin(), E = undecidedVBases.end(); I != E; ++I) {
1351 if (hasNonVirtualBaseInSet(*I, overriddenBases))
1352 vtordispVBases.insert(*I);
1356 /// hasNewVirtualFunction - Does the given polymorphic class declare a
1357 /// virtual function that does not override a method from any of its
1360 RecordLayoutBuilder::hasNewVirtualFunction(const CXXRecordDecl *RD,
1361 bool IgnoreDestructor) const {
1362 if (!RD->getNumBases())
1365 for (CXXRecordDecl::method_iterator method = RD->method_begin();
1366 method != RD->method_end();
1368 if (method->isVirtual() && !method->size_overridden_methods() &&
1369 !(IgnoreDestructor && method->getKind() == Decl::CXXDestructor)) {
1376 /// isPossiblePrimaryBase - Is the given base class an acceptable
1377 /// primary base class?
1379 RecordLayoutBuilder::isPossiblePrimaryBase(const CXXRecordDecl *base) const {
1380 // In the Itanium ABI, a class can be a primary base class if it has
1381 // a vtable for any reason.
1382 if (!isMicrosoftCXXABI())
1383 return base->isDynamicClass();
1385 // In the MS ABI, a class can only be a primary base class if it
1386 // provides a vf-table at a static offset. That means it has to be
1387 // non-virtual base. The existence of a separate vb-table means
1388 // that it's possible to get virtual functions only from a virtual
1389 // base, which we have to guard against.
1391 // First off, it has to have virtual functions.
1392 if (!base->isPolymorphic()) return false;
1394 // If it has no virtual bases, then the vfptr must be at a static offset.
1395 if (!base->getNumVBases()) return true;
1397 // Otherwise, the necessary information is cached in the layout.
1398 const ASTRecordLayout &layout = Context.getASTRecordLayout(base);
1400 // If the base has its own vfptr, it can be a primary base.
1401 if (layout.hasOwnVFPtr()) return true;
1403 // If the base has a primary base class, then it can be a primary base.
1404 if (layout.getPrimaryBase()) return true;
1406 // Otherwise it can't.
1411 RecordLayoutBuilder::LayoutVirtualBases(const CXXRecordDecl *RD,
1412 const CXXRecordDecl *MostDerivedClass) {
1413 const CXXRecordDecl *PrimaryBase;
1414 bool PrimaryBaseIsVirtual;
1416 if (MostDerivedClass == RD) {
1417 PrimaryBase = this->PrimaryBase;
1418 PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual;
1420 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1421 PrimaryBase = Layout.getPrimaryBase();
1422 PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
1425 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1426 E = RD->bases_end(); I != E; ++I) {
1427 assert(!I->getType()->isDependentType() &&
1428 "Cannot layout class with dependent bases.");
1430 const CXXRecordDecl *BaseDecl =
1431 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1433 if (I->isVirtual()) {
1434 if (PrimaryBase != BaseDecl || !PrimaryBaseIsVirtual) {
1435 bool IndirectPrimaryBase = IndirectPrimaryBases.count(BaseDecl);
1437 // Only lay out the virtual base if it's not an indirect primary base.
1438 if (!IndirectPrimaryBase) {
1439 // Only visit virtual bases once.
1440 if (!VisitedVirtualBases.insert(BaseDecl))
1443 const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1444 assert(BaseInfo && "Did not find virtual base info!");
1445 LayoutVirtualBase(BaseInfo);
1450 if (!BaseDecl->getNumVBases()) {
1451 // This base isn't interesting since it doesn't have any virtual bases.
1455 LayoutVirtualBases(BaseDecl, MostDerivedClass);
1459 void RecordLayoutBuilder::MSLayoutVirtualBases(const CXXRecordDecl *RD) {
1460 if (!RD->getNumVBases())
1463 ClassSetTy VtordispVBases;
1464 computeVtordisps(RD, VtordispVBases);
1466 // This is substantially simplified because there are no virtual
1468 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
1469 E = RD->vbases_end(); I != E; ++I) {
1470 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
1471 const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1472 assert(BaseInfo && "Did not find virtual base info!");
1474 // If this base requires a vtordisp, add enough space for an int field.
1475 // This is apparently always 32-bits, even on x64.
1476 bool vtordispNeeded = false;
1477 if (VtordispVBases.count(BaseDecl)) {
1479 CharUnits::fromQuantity(Context.getTargetInfo().getIntWidth() / 8);
1481 setSize(getSize() + IntSize);
1482 setDataSize(getSize());
1483 vtordispNeeded = true;
1486 LayoutVirtualBase(BaseInfo, vtordispNeeded);
1490 void RecordLayoutBuilder::LayoutVirtualBase(const BaseSubobjectInfo *Base,
1491 bool IsVtordispNeed) {
1492 assert(!Base->Derived && "Trying to lay out a primary virtual base!");
1495 CharUnits Offset = LayoutBase(Base);
1497 // Add its base class offset.
1498 assert(!VBases.count(Base->Class) && "vbase offset already exists!");
1499 VBases.insert(std::make_pair(Base->Class,
1500 ASTRecordLayout::VBaseInfo(Offset, IsVtordispNeed)));
1502 if (!isMicrosoftCXXABI())
1503 AddPrimaryVirtualBaseOffsets(Base, Offset);
1506 CharUnits RecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) {
1507 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class);
1512 // Query the external layout to see if it provides an offset.
1513 bool HasExternalLayout = false;
1514 if (ExternalLayout) {
1515 llvm::DenseMap<const CXXRecordDecl *, CharUnits>::iterator Known;
1516 if (Base->IsVirtual) {
1517 Known = ExternalVirtualBaseOffsets.find(Base->Class);
1518 if (Known != ExternalVirtualBaseOffsets.end()) {
1519 Offset = Known->second;
1520 HasExternalLayout = true;
1523 Known = ExternalBaseOffsets.find(Base->Class);
1524 if (Known != ExternalBaseOffsets.end()) {
1525 Offset = Known->second;
1526 HasExternalLayout = true;
1531 // If we have an empty base class, try to place it at offset 0.
1532 if (Base->Class->isEmpty() &&
1533 (!HasExternalLayout || Offset == CharUnits::Zero()) &&
1534 EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) {
1535 setSize(std::max(getSize(), Layout.getSize()));
1537 return CharUnits::Zero();
1540 CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlign();
1541 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
1543 // The maximum field alignment overrides base align.
1544 if (!MaxFieldAlignment.isZero()) {
1545 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1546 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
1549 if (!HasExternalLayout) {
1550 // Round up the current record size to the base's alignment boundary.
1551 Offset = getDataSize().RoundUpToAlignment(BaseAlign);
1553 // Try to place the base.
1554 while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset))
1555 Offset += BaseAlign;
1557 bool Allowed = EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset);
1559 assert(Allowed && "Base subobject externally placed at overlapping offset");
1562 if (!Base->Class->isEmpty()) {
1563 // Update the data size.
1564 setDataSize(Offset + Layout.getNonVirtualSize());
1566 setSize(std::max(getSize(), getDataSize()));
1568 setSize(std::max(getSize(), Offset + Layout.getSize()));
1570 // Remember max struct/class alignment.
1571 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
1576 void RecordLayoutBuilder::InitializeLayout(const Decl *D) {
1577 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
1578 IsUnion = RD->isUnion();
1580 Packed = D->hasAttr<PackedAttr>();
1582 IsMsStruct = D->hasAttr<MsStructAttr>();
1584 // Honor the default struct packing maximum alignment flag.
1585 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) {
1586 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
1589 // mac68k alignment supersedes maximum field alignment and attribute aligned,
1590 // and forces all structures to have 2-byte alignment. The IBM docs on it
1591 // allude to additional (more complicated) semantics, especially with regard
1592 // to bit-fields, but gcc appears not to follow that.
1593 if (D->hasAttr<AlignMac68kAttr>()) {
1594 IsMac68kAlign = true;
1595 MaxFieldAlignment = CharUnits::fromQuantity(2);
1596 Alignment = CharUnits::fromQuantity(2);
1598 if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>())
1599 MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment());
1601 if (unsigned MaxAlign = D->getMaxAlignment())
1602 UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign));
1605 // If there is an external AST source, ask it for the various offsets.
1606 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
1607 if (ExternalASTSource *External = Context.getExternalSource()) {
1608 ExternalLayout = External->layoutRecordType(RD,
1611 ExternalFieldOffsets,
1612 ExternalBaseOffsets,
1613 ExternalVirtualBaseOffsets);
1615 // Update based on external alignment.
1616 if (ExternalLayout) {
1617 if (ExternalAlign > 0) {
1618 Alignment = Context.toCharUnitsFromBits(ExternalAlign);
1619 UnpackedAlignment = Alignment;
1621 // The external source didn't have alignment information; infer it.
1622 InferAlignment = true;
1628 void RecordLayoutBuilder::Layout(const RecordDecl *D) {
1629 InitializeLayout(D);
1632 // Finally, round the size of the total struct up to the alignment of the
1637 void RecordLayoutBuilder::Layout(const CXXRecordDecl *RD) {
1638 InitializeLayout(RD);
1640 // Lay out the vtable and the non-virtual bases.
1641 LayoutNonVirtualBases(RD);
1645 NonVirtualSize = Context.toCharUnitsFromBits(
1646 llvm::RoundUpToAlignment(getSizeInBits(),
1647 Context.getTargetInfo().getCharAlign()));
1648 NonVirtualAlignment = Alignment;
1650 if (isMicrosoftCXXABI()) {
1651 if (NonVirtualSize != NonVirtualSize.RoundUpToAlignment(Alignment)) {
1652 CharUnits AlignMember =
1653 NonVirtualSize.RoundUpToAlignment(Alignment) - NonVirtualSize;
1655 setSize(getSize() + AlignMember);
1656 setDataSize(getSize());
1658 NonVirtualSize = Context.toCharUnitsFromBits(
1659 llvm::RoundUpToAlignment(getSizeInBits(),
1660 Context.getTargetInfo().getCharAlign()));
1663 MSLayoutVirtualBases(RD);
1665 // Lay out the virtual bases and add the primary virtual base offsets.
1666 LayoutVirtualBases(RD, RD);
1669 // Finally, round the size of the total struct up to the alignment
1670 // of the struct itself.
1674 // Check that we have base offsets for all bases.
1675 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1676 E = RD->bases_end(); I != E; ++I) {
1680 const CXXRecordDecl *BaseDecl =
1681 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1683 assert(Bases.count(BaseDecl) && "Did not find base offset!");
1686 // And all virtual bases.
1687 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
1688 E = RD->vbases_end(); I != E; ++I) {
1689 const CXXRecordDecl *BaseDecl =
1690 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1692 assert(VBases.count(BaseDecl) && "Did not find base offset!");
1697 void RecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) {
1698 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
1699 const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD);
1701 UpdateAlignment(SL.getAlignment());
1703 // We start laying out ivars not at the end of the superclass
1704 // structure, but at the next byte following the last field.
1705 setSize(SL.getDataSize());
1706 setDataSize(getSize());
1709 InitializeLayout(D);
1710 // Layout each ivar sequentially.
1711 for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD;
1712 IVD = IVD->getNextIvar())
1715 // Finally, round the size of the total struct up to the alignment of the
1720 void RecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
1721 // Layout each field, for now, just sequentially, respecting alignment. In
1722 // the future, this will need to be tweakable by targets.
1723 const FieldDecl *LastFD = 0;
1724 ZeroLengthBitfield = 0;
1725 unsigned RemainingInAlignment = 0;
1726 for (RecordDecl::field_iterator Field = D->field_begin(),
1727 FieldEnd = D->field_end(); Field != FieldEnd; ++Field) {
1729 FieldDecl *FD = *Field;
1730 if (Context.ZeroBitfieldFollowsBitfield(FD, LastFD))
1731 ZeroLengthBitfield = FD;
1732 // Zero-length bitfields following non-bitfield members are
1734 else if (Context.ZeroBitfieldFollowsNonBitfield(FD, LastFD))
1736 // FIXME. streamline these conditions into a simple one.
1737 else if (Context.BitfieldFollowsBitfield(FD, LastFD) ||
1738 Context.BitfieldFollowsNonBitfield(FD, LastFD) ||
1739 Context.NonBitfieldFollowsBitfield(FD, LastFD)) {
1740 // 1) Adjacent bit fields are packed into the same 1-, 2-, or
1741 // 4-byte allocation unit if the integral types are the same
1742 // size and if the next bit field fits into the current
1743 // allocation unit without crossing the boundary imposed by the
1744 // common alignment requirements of the bit fields.
1745 // 2) Establish a new alignment for a bitfield following
1746 // a non-bitfield if size of their types differ.
1747 // 3) Establish a new alignment for a non-bitfield following
1748 // a bitfield if size of their types differ.
1749 std::pair<uint64_t, unsigned> FieldInfo =
1750 Context.getTypeInfo(FD->getType());
1751 uint64_t TypeSize = FieldInfo.first;
1752 unsigned FieldAlign = FieldInfo.second;
1753 // This check is needed for 'long long' in -m32 mode.
1754 if (TypeSize > FieldAlign &&
1755 (Context.hasSameType(FD->getType(),
1756 Context.UnsignedLongLongTy)
1757 ||Context.hasSameType(FD->getType(),
1758 Context.LongLongTy)))
1759 FieldAlign = TypeSize;
1760 FieldInfo = Context.getTypeInfo(LastFD->getType());
1761 uint64_t TypeSizeLastFD = FieldInfo.first;
1762 unsigned FieldAlignLastFD = FieldInfo.second;
1763 // This check is needed for 'long long' in -m32 mode.
1764 if (TypeSizeLastFD > FieldAlignLastFD &&
1765 (Context.hasSameType(LastFD->getType(),
1766 Context.UnsignedLongLongTy)
1767 || Context.hasSameType(LastFD->getType(),
1768 Context.LongLongTy)))
1769 FieldAlignLastFD = TypeSizeLastFD;
1771 if (TypeSizeLastFD != TypeSize) {
1772 if (RemainingInAlignment &&
1773 LastFD && LastFD->isBitField() &&
1774 LastFD->getBitWidthValue(Context)) {
1775 // If previous field was a bitfield with some remaining unfilled
1776 // bits, pad the field so current field starts on its type boundary.
1777 uint64_t FieldOffset =
1778 getDataSizeInBits() - UnfilledBitsInLastByte;
1779 uint64_t NewSizeInBits = RemainingInAlignment + FieldOffset;
1780 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
1781 Context.getTargetInfo().getCharAlign()));
1782 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1783 RemainingInAlignment = 0;
1786 uint64_t UnpaddedFieldOffset =
1787 getDataSizeInBits() - UnfilledBitsInLastByte;
1788 FieldAlign = std::max(FieldAlign, FieldAlignLastFD);
1790 // The maximum field alignment overrides the aligned attribute.
1791 if (!MaxFieldAlignment.isZero()) {
1792 unsigned MaxFieldAlignmentInBits =
1793 Context.toBits(MaxFieldAlignment);
1794 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1797 uint64_t NewSizeInBits =
1798 llvm::RoundUpToAlignment(UnpaddedFieldOffset, FieldAlign);
1799 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
1800 Context.getTargetInfo().getCharAlign()));
1801 UnfilledBitsInLastByte = getDataSizeInBits() - NewSizeInBits;
1802 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1804 if (FD->isBitField()) {
1805 uint64_t FieldSize = FD->getBitWidthValue(Context);
1806 assert (FieldSize > 0 && "LayoutFields - ms_struct layout");
1807 if (RemainingInAlignment < FieldSize)
1808 RemainingInAlignment = TypeSize - FieldSize;
1810 RemainingInAlignment -= FieldSize;
1813 else if (FD->isBitField()) {
1814 uint64_t FieldSize = FD->getBitWidthValue(Context);
1815 std::pair<uint64_t, unsigned> FieldInfo =
1816 Context.getTypeInfo(FD->getType());
1817 uint64_t TypeSize = FieldInfo.first;
1818 RemainingInAlignment = TypeSize - FieldSize;
1822 else if (!Context.getTargetInfo().useBitFieldTypeAlignment() &&
1823 Context.getTargetInfo().useZeroLengthBitfieldAlignment()) {
1824 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
1825 ZeroLengthBitfield = *Field;
1827 LayoutField(*Field);
1829 if (IsMsStruct && RemainingInAlignment &&
1830 LastFD && LastFD->isBitField() && LastFD->getBitWidthValue(Context)) {
1831 // If we ended a bitfield before the full length of the type then
1832 // pad the struct out to the full length of the last type.
1833 uint64_t FieldOffset =
1834 getDataSizeInBits() - UnfilledBitsInLastByte;
1835 uint64_t NewSizeInBits = RemainingInAlignment + FieldOffset;
1836 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
1837 Context.getTargetInfo().getCharAlign()));
1838 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1842 void RecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize,
1845 const FieldDecl *D) {
1846 assert(Context.getLangOpts().CPlusPlus &&
1847 "Can only have wide bit-fields in C++!");
1849 // Itanium C++ ABI 2.4:
1850 // If sizeof(T)*8 < n, let T' be the largest integral POD type with
1851 // sizeof(T')*8 <= n.
1853 QualType IntegralPODTypes[] = {
1854 Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy,
1855 Context.UnsignedLongTy, Context.UnsignedLongLongTy
1859 for (unsigned I = 0, E = llvm::array_lengthof(IntegralPODTypes);
1861 uint64_t Size = Context.getTypeSize(IntegralPODTypes[I]);
1863 if (Size > FieldSize)
1866 Type = IntegralPODTypes[I];
1868 assert(!Type.isNull() && "Did not find a type!");
1870 CharUnits TypeAlign = Context.getTypeAlignInChars(Type);
1872 // We're not going to use any of the unfilled bits in the last byte.
1873 UnfilledBitsInLastByte = 0;
1875 uint64_t FieldOffset;
1876 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastByte;
1879 setDataSize(std::max(getDataSizeInBits(), FieldSize));
1882 // The bitfield is allocated starting at the next offset aligned
1883 // appropriately for T', with length n bits.
1884 FieldOffset = llvm::RoundUpToAlignment(getDataSizeInBits(),
1885 Context.toBits(TypeAlign));
1887 uint64_t NewSizeInBits = FieldOffset + FieldSize;
1889 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
1890 Context.getTargetInfo().getCharAlign()));
1891 UnfilledBitsInLastByte = getDataSizeInBits() - NewSizeInBits;
1894 // Place this field at the current location.
1895 FieldOffsets.push_back(FieldOffset);
1897 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset,
1898 Context.toBits(TypeAlign), FieldPacked, D);
1901 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1903 // Remember max struct/class alignment.
1904 UpdateAlignment(TypeAlign);
1907 void RecordLayoutBuilder::LayoutBitField(const FieldDecl *D) {
1908 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
1909 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastByte;
1910 uint64_t FieldOffset = IsUnion ? 0 : UnpaddedFieldOffset;
1911 uint64_t FieldSize = D->getBitWidthValue(Context);
1913 std::pair<uint64_t, unsigned> FieldInfo = Context.getTypeInfo(D->getType());
1914 uint64_t TypeSize = FieldInfo.first;
1915 unsigned FieldAlign = FieldInfo.second;
1917 // This check is needed for 'long long' in -m32 mode.
1918 if (IsMsStruct && (TypeSize > FieldAlign) &&
1919 (Context.hasSameType(D->getType(),
1920 Context.UnsignedLongLongTy)
1921 || Context.hasSameType(D->getType(), Context.LongLongTy)))
1922 FieldAlign = TypeSize;
1924 if (ZeroLengthBitfield) {
1925 std::pair<uint64_t, unsigned> FieldInfo;
1926 unsigned ZeroLengthBitfieldAlignment;
1928 // If a zero-length bitfield is inserted after a bitfield,
1929 // and the alignment of the zero-length bitfield is
1930 // greater than the member that follows it, `bar', `bar'
1931 // will be aligned as the type of the zero-length bitfield.
1932 if (ZeroLengthBitfield != D) {
1933 FieldInfo = Context.getTypeInfo(ZeroLengthBitfield->getType());
1934 ZeroLengthBitfieldAlignment = FieldInfo.second;
1935 // Ignore alignment of subsequent zero-length bitfields.
1936 if ((ZeroLengthBitfieldAlignment > FieldAlign) || (FieldSize == 0))
1937 FieldAlign = ZeroLengthBitfieldAlignment;
1939 ZeroLengthBitfield = 0;
1942 // The alignment of a zero-length bitfield affects the alignment
1943 // of the next member. The alignment is the max of the zero
1944 // length bitfield's alignment and a target specific fixed value.
1945 unsigned ZeroLengthBitfieldBoundary =
1946 Context.getTargetInfo().getZeroLengthBitfieldBoundary();
1947 if (ZeroLengthBitfieldBoundary > FieldAlign)
1948 FieldAlign = ZeroLengthBitfieldBoundary;
1952 if (FieldSize > TypeSize) {
1953 LayoutWideBitField(FieldSize, TypeSize, FieldPacked, D);
1957 // The align if the field is not packed. This is to check if the attribute
1958 // was unnecessary (-Wpacked).
1959 unsigned UnpackedFieldAlign = FieldAlign;
1960 uint64_t UnpackedFieldOffset = FieldOffset;
1961 if (!Context.getTargetInfo().useBitFieldTypeAlignment() && !ZeroLengthBitfield)
1962 UnpackedFieldAlign = 1;
1965 (!Context.getTargetInfo().useBitFieldTypeAlignment() && !ZeroLengthBitfield))
1967 FieldAlign = std::max(FieldAlign, D->getMaxAlignment());
1968 UnpackedFieldAlign = std::max(UnpackedFieldAlign, D->getMaxAlignment());
1970 // The maximum field alignment overrides the aligned attribute.
1971 if (!MaxFieldAlignment.isZero() && FieldSize != 0) {
1972 unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment);
1973 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1974 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
1977 // Check if we need to add padding to give the field the correct alignment.
1978 if (FieldSize == 0 ||
1979 (MaxFieldAlignment.isZero() &&
1980 (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize))
1981 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
1983 if (FieldSize == 0 ||
1984 (MaxFieldAlignment.isZero() &&
1985 (UnpackedFieldOffset & (UnpackedFieldAlign-1)) + FieldSize > TypeSize))
1986 UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1987 UnpackedFieldAlign);
1989 // Padding members don't affect overall alignment, unless zero length bitfield
1990 // alignment is enabled.
1991 if (!D->getIdentifier() && !Context.getTargetInfo().useZeroLengthBitfieldAlignment())
1992 FieldAlign = UnpackedFieldAlign = 1;
1995 ZeroLengthBitfield = 0;
1998 FieldOffset = updateExternalFieldOffset(D, FieldOffset);
2000 // Place this field at the current location.
2001 FieldOffsets.push_back(FieldOffset);
2003 if (!ExternalLayout)
2004 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset,
2005 UnpackedFieldAlign, FieldPacked, D);
2007 // Update DataSize to include the last byte containing (part of) the bitfield.
2009 // FIXME: I think FieldSize should be TypeSize here.
2010 setDataSize(std::max(getDataSizeInBits(), FieldSize));
2012 uint64_t NewSizeInBits = FieldOffset + FieldSize;
2014 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
2015 Context.getTargetInfo().getCharAlign()));
2016 UnfilledBitsInLastByte = getDataSizeInBits() - NewSizeInBits;
2020 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
2022 // Remember max struct/class alignment.
2023 UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign),
2024 Context.toCharUnitsFromBits(UnpackedFieldAlign));
2027 void RecordLayoutBuilder::LayoutField(const FieldDecl *D) {
2028 if (D->isBitField()) {
2033 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastByte;
2035 // Reset the unfilled bits.
2036 UnfilledBitsInLastByte = 0;
2038 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
2039 CharUnits FieldOffset =
2040 IsUnion ? CharUnits::Zero() : getDataSize();
2041 CharUnits FieldSize;
2042 CharUnits FieldAlign;
2044 if (D->getType()->isIncompleteArrayType()) {
2045 // This is a flexible array member; we can't directly
2046 // query getTypeInfo about these, so we figure it out here.
2047 // Flexible array members don't have any size, but they
2048 // have to be aligned appropriately for their element type.
2049 FieldSize = CharUnits::Zero();
2050 const ArrayType* ATy = Context.getAsArrayType(D->getType());
2051 FieldAlign = Context.getTypeAlignInChars(ATy->getElementType());
2052 } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) {
2053 unsigned AS = RT->getPointeeType().getAddressSpace();
2055 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(AS));
2057 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(AS));
2059 std::pair<CharUnits, CharUnits> FieldInfo =
2060 Context.getTypeInfoInChars(D->getType());
2061 FieldSize = FieldInfo.first;
2062 FieldAlign = FieldInfo.second;
2064 if (ZeroLengthBitfield) {
2065 CharUnits ZeroLengthBitfieldBoundary =
2066 Context.toCharUnitsFromBits(
2067 Context.getTargetInfo().getZeroLengthBitfieldBoundary());
2068 if (ZeroLengthBitfieldBoundary == CharUnits::Zero()) {
2069 // If a zero-length bitfield is inserted after a bitfield,
2070 // and the alignment of the zero-length bitfield is
2071 // greater than the member that follows it, `bar', `bar'
2072 // will be aligned as the type of the zero-length bitfield.
2073 std::pair<CharUnits, CharUnits> FieldInfo =
2074 Context.getTypeInfoInChars(ZeroLengthBitfield->getType());
2075 CharUnits ZeroLengthBitfieldAlignment = FieldInfo.second;
2076 if (ZeroLengthBitfieldAlignment > FieldAlign)
2077 FieldAlign = ZeroLengthBitfieldAlignment;
2078 } else if (ZeroLengthBitfieldBoundary > FieldAlign) {
2079 // Align 'bar' based on a fixed alignment specified by the target.
2080 assert(Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
2081 "ZeroLengthBitfieldBoundary should only be used in conjunction"
2082 " with useZeroLengthBitfieldAlignment.");
2083 FieldAlign = ZeroLengthBitfieldBoundary;
2085 ZeroLengthBitfield = 0;
2088 if (Context.getLangOpts().MSBitfields || IsMsStruct) {
2089 // If MS bitfield layout is required, figure out what type is being
2090 // laid out and align the field to the width of that type.
2092 // Resolve all typedefs down to their base type and round up the field
2093 // alignment if necessary.
2094 QualType T = Context.getBaseElementType(D->getType());
2095 if (const BuiltinType *BTy = T->getAs<BuiltinType>()) {
2096 CharUnits TypeSize = Context.getTypeSizeInChars(BTy);
2097 if (TypeSize > FieldAlign)
2098 FieldAlign = TypeSize;
2103 // The align if the field is not packed. This is to check if the attribute
2104 // was unnecessary (-Wpacked).
2105 CharUnits UnpackedFieldAlign = FieldAlign;
2106 CharUnits UnpackedFieldOffset = FieldOffset;
2109 FieldAlign = CharUnits::One();
2110 CharUnits MaxAlignmentInChars =
2111 Context.toCharUnitsFromBits(D->getMaxAlignment());
2112 FieldAlign = std::max(FieldAlign, MaxAlignmentInChars);
2113 UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars);
2115 // The maximum field alignment overrides the aligned attribute.
2116 if (!MaxFieldAlignment.isZero()) {
2117 FieldAlign = std::min(FieldAlign, MaxFieldAlignment);
2118 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment);
2121 // Round up the current record size to the field's alignment boundary.
2122 FieldOffset = FieldOffset.RoundUpToAlignment(FieldAlign);
2123 UnpackedFieldOffset =
2124 UnpackedFieldOffset.RoundUpToAlignment(UnpackedFieldAlign);
2126 if (ExternalLayout) {
2127 FieldOffset = Context.toCharUnitsFromBits(
2128 updateExternalFieldOffset(D, Context.toBits(FieldOffset)));
2130 if (!IsUnion && EmptySubobjects) {
2131 // Record the fact that we're placing a field at this offset.
2132 bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset);
2134 assert(Allowed && "Externally-placed field cannot be placed here");
2137 if (!IsUnion && EmptySubobjects) {
2138 // Check if we can place the field at this offset.
2139 while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) {
2140 // We couldn't place the field at the offset. Try again at a new offset.
2141 FieldOffset += FieldAlign;
2146 // Place this field at the current location.
2147 FieldOffsets.push_back(Context.toBits(FieldOffset));
2149 if (!ExternalLayout)
2150 CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset,
2151 Context.toBits(UnpackedFieldOffset),
2152 Context.toBits(UnpackedFieldAlign), FieldPacked, D);
2154 // Reserve space for this field.
2155 uint64_t FieldSizeInBits = Context.toBits(FieldSize);
2157 setDataSize(std::max(getDataSizeInBits(), FieldSizeInBits));
2159 setDataSize(FieldOffset + FieldSize);
2162 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
2164 // Remember max struct/class alignment.
2165 UpdateAlignment(FieldAlign, UnpackedFieldAlign);
2168 void RecordLayoutBuilder::FinishLayout(const NamedDecl *D) {
2169 if (ExternalLayout) {
2170 setSize(ExternalSize);
2174 // In C++, records cannot be of size 0.
2175 if (Context.getLangOpts().CPlusPlus && getSizeInBits() == 0) {
2176 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2177 // Compatibility with gcc requires a class (pod or non-pod)
2178 // which is not empty but of size 0; such as having fields of
2179 // array of zero-length, remains of Size 0
2181 setSize(CharUnits::One());
2184 setSize(CharUnits::One());
2187 // MSVC doesn't round up to the alignment of the record with virtual bases.
2188 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2189 if (isMicrosoftCXXABI() && RD->getNumVBases())
2193 // Finally, round the size of the record up to the alignment of the
2195 uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastByte;
2196 uint64_t UnpackedSizeInBits =
2197 llvm::RoundUpToAlignment(getSizeInBits(),
2198 Context.toBits(UnpackedAlignment));
2199 CharUnits UnpackedSize = Context.toCharUnitsFromBits(UnpackedSizeInBits);
2200 setSize(llvm::RoundUpToAlignment(getSizeInBits(), Context.toBits(Alignment)));
2202 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
2203 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
2204 // Warn if padding was introduced to the struct/class/union.
2205 if (getSizeInBits() > UnpaddedSize) {
2206 unsigned PadSize = getSizeInBits() - UnpaddedSize;
2208 if (PadSize % CharBitNum == 0) {
2209 PadSize = PadSize / CharBitNum;
2212 Diag(RD->getLocation(), diag::warn_padded_struct_size)
2213 << Context.getTypeDeclType(RD)
2215 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
2218 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
2219 // bother since there won't be alignment issues.
2220 if (Packed && UnpackedAlignment > CharUnits::One() &&
2221 getSize() == UnpackedSize)
2222 Diag(D->getLocation(), diag::warn_unnecessary_packed)
2223 << Context.getTypeDeclType(RD);
2227 void RecordLayoutBuilder::UpdateAlignment(CharUnits NewAlignment,
2228 CharUnits UnpackedNewAlignment) {
2229 // The alignment is not modified when using 'mac68k' alignment or when
2230 // we have an externally-supplied layout that also provides overall alignment.
2231 if (IsMac68kAlign || (ExternalLayout && !InferAlignment))
2234 if (NewAlignment > Alignment) {
2235 assert(llvm::isPowerOf2_32(NewAlignment.getQuantity() &&
2236 "Alignment not a power of 2"));
2237 Alignment = NewAlignment;
2240 if (UnpackedNewAlignment > UnpackedAlignment) {
2241 assert(llvm::isPowerOf2_32(UnpackedNewAlignment.getQuantity() &&
2242 "Alignment not a power of 2"));
2243 UnpackedAlignment = UnpackedNewAlignment;
2248 RecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field,
2249 uint64_t ComputedOffset) {
2250 assert(ExternalFieldOffsets.find(Field) != ExternalFieldOffsets.end() &&
2251 "Field does not have an external offset");
2253 uint64_t ExternalFieldOffset = ExternalFieldOffsets[Field];
2255 if (InferAlignment && ExternalFieldOffset < ComputedOffset) {
2256 // The externally-supplied field offset is before the field offset we
2257 // computed. Assume that the structure is packed.
2258 Alignment = CharUnits::fromQuantity(1);
2259 InferAlignment = false;
2262 // Use the externally-supplied field offset.
2263 return ExternalFieldOffset;
2266 void RecordLayoutBuilder::CheckFieldPadding(uint64_t Offset,
2267 uint64_t UnpaddedOffset,
2268 uint64_t UnpackedOffset,
2269 unsigned UnpackedAlign,
2271 const FieldDecl *D) {
2272 // We let objc ivars without warning, objc interfaces generally are not used
2273 // for padding tricks.
2274 if (isa<ObjCIvarDecl>(D))
2277 // Don't warn about structs created without a SourceLocation. This can
2278 // be done by clients of the AST, such as codegen.
2279 if (D->getLocation().isInvalid())
2282 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
2284 // Warn if padding was introduced to the struct/class.
2285 if (!IsUnion && Offset > UnpaddedOffset) {
2286 unsigned PadSize = Offset - UnpaddedOffset;
2288 if (PadSize % CharBitNum == 0) {
2289 PadSize = PadSize / CharBitNum;
2292 if (D->getIdentifier())
2293 Diag(D->getLocation(), diag::warn_padded_struct_field)
2294 << (D->getParent()->isStruct() ? 0 : 1) // struct|class
2295 << Context.getTypeDeclType(D->getParent())
2297 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1) // plural or not
2298 << D->getIdentifier();
2300 Diag(D->getLocation(), diag::warn_padded_struct_anon_field)
2301 << (D->getParent()->isStruct() ? 0 : 1) // struct|class
2302 << Context.getTypeDeclType(D->getParent())
2304 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
2307 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
2308 // bother since there won't be alignment issues.
2309 if (isPacked && UnpackedAlign > CharBitNum && Offset == UnpackedOffset)
2310 Diag(D->getLocation(), diag::warn_unnecessary_packed)
2311 << D->getIdentifier();
2314 const CXXMethodDecl *
2315 RecordLayoutBuilder::ComputeKeyFunction(const CXXRecordDecl *RD) {
2316 // If a class isn't polymorphic it doesn't have a key function.
2317 if (!RD->isPolymorphic())
2320 // A class that is not externally visible doesn't have a key function. (Or
2321 // at least, there's no point to assigning a key function to such a class;
2322 // this doesn't affect the ABI.)
2323 if (RD->getLinkage() != ExternalLinkage)
2326 // Template instantiations don't have key functions,see Itanium C++ ABI 5.2.6.
2327 // Same behavior as GCC.
2328 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
2329 if (TSK == TSK_ImplicitInstantiation ||
2330 TSK == TSK_ExplicitInstantiationDefinition)
2333 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
2334 E = RD->method_end(); I != E; ++I) {
2335 const CXXMethodDecl *MD = *I;
2337 if (!MD->isVirtual())
2343 // Ignore implicit member functions, they are always marked as inline, but
2344 // they don't have a body until they're defined.
2345 if (MD->isImplicit())
2348 if (MD->isInlineSpecified())
2351 if (MD->hasInlineBody())
2354 // Ignore inline deleted or defaulted functions.
2355 if (!MD->isUserProvided())
2366 RecordLayoutBuilder::Diag(SourceLocation Loc, unsigned DiagID) {
2367 return Context.getDiagnostics().Report(Loc, DiagID);
2370 /// getASTRecordLayout - Get or compute information about the layout of the
2371 /// specified record (struct/union/class), which indicates its size and field
2372 /// position information.
2373 const ASTRecordLayout &
2374 ASTContext::getASTRecordLayout(const RecordDecl *D) const {
2375 // These asserts test different things. A record has a definition
2376 // as soon as we begin to parse the definition. That definition is
2377 // not a complete definition (which is what isDefinition() tests)
2378 // until we *finish* parsing the definition.
2380 if (D->hasExternalLexicalStorage() && !D->getDefinition())
2381 getExternalSource()->CompleteType(const_cast<RecordDecl*>(D));
2383 D = D->getDefinition();
2384 assert(D && "Cannot get layout of forward declarations!");
2385 assert(D->isCompleteDefinition() && "Cannot layout type before complete!");
2387 // Look up this layout, if already laid out, return what we have.
2388 // Note that we can't save a reference to the entry because this function
2390 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
2391 if (Entry) return *Entry;
2393 const ASTRecordLayout *NewEntry;
2395 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2396 EmptySubobjectMap EmptySubobjects(*this, RD);
2397 RecordLayoutBuilder Builder(*this, &EmptySubobjects);
2400 // MSVC gives the vb-table pointer an alignment equal to that of
2401 // the non-virtual part of the structure. That's an inherently
2402 // multi-pass operation. If our first pass doesn't give us
2403 // adequate alignment, try again with the specified minimum
2404 // alignment. This is *much* more maintainable than computing the
2405 // alignment in advance in a separately-coded pass; it's also
2406 // significantly more efficient in the common case where the
2407 // vb-table doesn't need extra padding.
2408 if (Builder.VBPtrOffset != CharUnits::fromQuantity(-1) &&
2409 (Builder.VBPtrOffset % Builder.NonVirtualAlignment) != 0) {
2410 Builder.resetWithTargetAlignment(Builder.NonVirtualAlignment);
2414 // FIXME: This is not always correct. See the part about bitfields at
2415 // http://www.codesourcery.com/public/cxx-abi/abi.html#POD for more info.
2416 // FIXME: IsPODForThePurposeOfLayout should be stored in the record layout.
2417 // This does not affect the calculations of MSVC layouts
2418 bool IsPODForThePurposeOfLayout =
2419 (!Builder.isMicrosoftCXXABI() && cast<CXXRecordDecl>(D)->isPOD());
2421 // FIXME: This should be done in FinalizeLayout.
2422 CharUnits DataSize =
2423 IsPODForThePurposeOfLayout ? Builder.getSize() : Builder.getDataSize();
2424 CharUnits NonVirtualSize =
2425 IsPODForThePurposeOfLayout ? DataSize : Builder.NonVirtualSize;
2428 new (*this) ASTRecordLayout(*this, Builder.getSize(),
2430 Builder.HasOwnVFPtr,
2431 Builder.VBPtrOffset,
2433 Builder.FieldOffsets.data(),
2434 Builder.FieldOffsets.size(),
2436 Builder.NonVirtualAlignment,
2437 EmptySubobjects.SizeOfLargestEmptySubobject,
2438 Builder.PrimaryBase,
2439 Builder.PrimaryBaseIsVirtual,
2440 Builder.Bases, Builder.VBases);
2442 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
2446 new (*this) ASTRecordLayout(*this, Builder.getSize(),
2449 Builder.FieldOffsets.data(),
2450 Builder.FieldOffsets.size());
2453 ASTRecordLayouts[D] = NewEntry;
2455 if (getLangOpts().DumpRecordLayouts) {
2456 llvm::errs() << "\n*** Dumping AST Record Layout\n";
2457 DumpRecordLayout(D, llvm::errs(), getLangOpts().DumpRecordLayoutsSimple);
2463 const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) {
2464 RD = cast<CXXRecordDecl>(RD->getDefinition());
2465 assert(RD && "Cannot get key function for forward declarations!");
2467 const CXXMethodDecl *&Entry = KeyFunctions[RD];
2469 Entry = RecordLayoutBuilder::ComputeKeyFunction(RD);
2474 static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) {
2475 const ASTRecordLayout &Layout = C.getASTRecordLayout(FD->getParent());
2476 return Layout.getFieldOffset(FD->getFieldIndex());
2479 uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const {
2480 uint64_t OffsetInBits;
2481 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
2482 OffsetInBits = ::getFieldOffset(*this, FD);
2484 const IndirectFieldDecl *IFD = cast<IndirectFieldDecl>(VD);
2487 for (IndirectFieldDecl::chain_iterator CI = IFD->chain_begin(),
2488 CE = IFD->chain_end();
2490 OffsetInBits += ::getFieldOffset(*this, cast<FieldDecl>(*CI));
2493 return OffsetInBits;
2496 /// getObjCLayout - Get or compute information about the layout of the
2497 /// given interface.
2499 /// \param Impl - If given, also include the layout of the interface's
2500 /// implementation. This may differ by including synthesized ivars.
2501 const ASTRecordLayout &
2502 ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
2503 const ObjCImplementationDecl *Impl) const {
2504 // Retrieve the definition
2505 if (D->hasExternalLexicalStorage() && !D->getDefinition())
2506 getExternalSource()->CompleteType(const_cast<ObjCInterfaceDecl*>(D));
2507 D = D->getDefinition();
2508 assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!");
2510 // Look up this layout, if already laid out, return what we have.
2511 ObjCContainerDecl *Key =
2512 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
2513 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
2516 // Add in synthesized ivar count if laying out an implementation.
2518 unsigned SynthCount = CountNonClassIvars(D);
2519 // If there aren't any sythesized ivars then reuse the interface
2520 // entry. Note we can't cache this because we simply free all
2521 // entries later; however we shouldn't look up implementations
2523 if (SynthCount == 0)
2524 return getObjCLayout(D, 0);
2527 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
2530 const ASTRecordLayout *NewEntry =
2531 new (*this) ASTRecordLayout(*this, Builder.getSize(),
2533 Builder.getDataSize(),
2534 Builder.FieldOffsets.data(),
2535 Builder.FieldOffsets.size());
2537 ObjCLayouts[Key] = NewEntry;
2542 static void PrintOffset(raw_ostream &OS,
2543 CharUnits Offset, unsigned IndentLevel) {
2544 OS << llvm::format("%4" PRId64 " | ", (int64_t)Offset.getQuantity());
2545 OS.indent(IndentLevel * 2);
2548 static void DumpCXXRecordLayout(raw_ostream &OS,
2549 const CXXRecordDecl *RD, const ASTContext &C,
2551 unsigned IndentLevel,
2552 const char* Description,
2553 bool IncludeVirtualBases) {
2554 const ASTRecordLayout &Layout = C.getASTRecordLayout(RD);
2556 PrintOffset(OS, Offset, IndentLevel);
2557 OS << C.getTypeDeclType(const_cast<CXXRecordDecl *>(RD)).getAsString();
2559 OS << ' ' << Description;
2566 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
2567 bool HasVfptr = Layout.hasOwnVFPtr();
2568 bool HasVbptr = Layout.getVBPtrOffset() != CharUnits::fromQuantity(-1);
2571 if (RD->isDynamicClass() && !PrimaryBase &&
2572 C.getTargetInfo().getCXXABI() != CXXABI_Microsoft) {
2573 PrintOffset(OS, Offset, IndentLevel);
2574 OS << '(' << *RD << " vtable pointer)\n";
2577 // Dump (non-virtual) bases
2578 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
2579 E = RD->bases_end(); I != E; ++I) {
2580 assert(!I->getType()->isDependentType() &&
2581 "Cannot layout class with dependent bases.");
2585 const CXXRecordDecl *Base =
2586 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
2588 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
2590 DumpCXXRecordLayout(OS, Base, C, BaseOffset, IndentLevel,
2591 Base == PrimaryBase ? "(primary base)" : "(base)",
2592 /*IncludeVirtualBases=*/false);
2595 // vfptr and vbptr (for Microsoft C++ ABI)
2597 PrintOffset(OS, Offset, IndentLevel);
2598 OS << '(' << *RD << " vftable pointer)\n";
2601 PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel);
2602 OS << '(' << *RD << " vbtable pointer)\n";
2606 uint64_t FieldNo = 0;
2607 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2608 E = RD->field_end(); I != E; ++I, ++FieldNo) {
2609 const FieldDecl &Field = **I;
2610 CharUnits FieldOffset = Offset +
2611 C.toCharUnitsFromBits(Layout.getFieldOffset(FieldNo));
2613 if (const RecordType *RT = Field.getType()->getAs<RecordType>()) {
2614 if (const CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2615 DumpCXXRecordLayout(OS, D, C, FieldOffset, IndentLevel,
2616 Field.getName().data(),
2617 /*IncludeVirtualBases=*/true);
2622 PrintOffset(OS, FieldOffset, IndentLevel);
2623 OS << Field.getType().getAsString() << ' ' << Field << '\n';
2626 if (!IncludeVirtualBases)
2629 // Dump virtual bases.
2630 const ASTRecordLayout::VBaseOffsetsMapTy &vtordisps =
2631 Layout.getVBaseOffsetsMap();
2632 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
2633 E = RD->vbases_end(); I != E; ++I) {
2634 assert(I->isVirtual() && "Found non-virtual class!");
2635 const CXXRecordDecl *VBase =
2636 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
2638 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
2640 if (vtordisps.find(VBase)->second.hasVtorDisp()) {
2641 PrintOffset(OS, VBaseOffset - CharUnits::fromQuantity(4), IndentLevel);
2642 OS << "(vtordisp for vbase " << *VBase << ")\n";
2645 DumpCXXRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel,
2646 VBase == PrimaryBase ?
2647 "(primary virtual base)" : "(virtual base)",
2648 /*IncludeVirtualBases=*/false);
2651 OS << " sizeof=" << Layout.getSize().getQuantity();
2652 OS << ", dsize=" << Layout.getDataSize().getQuantity();
2653 OS << ", align=" << Layout.getAlignment().getQuantity() << '\n';
2654 OS << " nvsize=" << Layout.getNonVirtualSize().getQuantity();
2655 OS << ", nvalign=" << Layout.getNonVirtualAlign().getQuantity() << '\n';
2659 void ASTContext::DumpRecordLayout(const RecordDecl *RD,
2661 bool Simple) const {
2662 const ASTRecordLayout &Info = getASTRecordLayout(RD);
2664 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2666 return DumpCXXRecordLayout(OS, CXXRD, *this, CharUnits(), 0, 0,
2667 /*IncludeVirtualBases=*/true);
2669 OS << "Type: " << getTypeDeclType(RD).getAsString() << "\n";
2675 OS << "<ASTRecordLayout\n";
2676 OS << " Size:" << toBits(Info.getSize()) << "\n";
2677 OS << " DataSize:" << toBits(Info.getDataSize()) << "\n";
2678 OS << " Alignment:" << toBits(Info.getAlignment()) << "\n";
2679 OS << " FieldOffsets: [";
2680 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) {
2682 OS << Info.getFieldOffset(i);