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/RecordLayout.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/AST/Attr.h"
13 #include "clang/AST/CXXInheritance.h"
14 #include "clang/AST/Decl.h"
15 #include "clang/AST/DeclCXX.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/Basic/TargetInfo.h"
19 #include "clang/Sema/SemaDiagnostic.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/Support/CrashRecoveryContext.h"
22 #include "llvm/Support/Format.h"
23 #include "llvm/Support/MathExtras.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 a 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 /// UnfilledBitsInLastUnit - If the last field laid out was a bitfield,
577 /// this contains the number of bits in the last unit that can be used for
578 /// an adjacent bitfield if necessary. The unit in question is usually
579 /// a byte, but larger units are used if IsMsStruct.
580 unsigned char UnfilledBitsInLastUnit;
581 /// LastBitfieldTypeSize - If IsMsStruct, represents the size of the type
582 /// of the previous field if it was a bitfield.
583 unsigned char LastBitfieldTypeSize;
585 /// MaxFieldAlignment - The maximum allowed field alignment. This is set by
587 CharUnits MaxFieldAlignment;
589 /// DataSize - The data size of the record being laid out.
592 CharUnits NonVirtualSize;
593 CharUnits NonVirtualAlignment;
595 /// PrimaryBase - the primary base class (if one exists) of the class
596 /// we're laying out.
597 const CXXRecordDecl *PrimaryBase;
599 /// PrimaryBaseIsVirtual - Whether the primary base of the class we're laying
601 bool PrimaryBaseIsVirtual;
603 /// HasOwnVFPtr - Whether the class provides its own vtable/vftbl
604 /// pointer, as opposed to inheriting one from a primary base class.
607 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
609 /// Bases - base classes and their offsets in the record.
610 BaseOffsetsMapTy Bases;
612 // VBases - virtual base classes and their offsets in the record.
613 ASTRecordLayout::VBaseOffsetsMapTy VBases;
615 /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are
616 /// primary base classes for some other direct or indirect base class.
617 CXXIndirectPrimaryBaseSet IndirectPrimaryBases;
619 /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in
620 /// inheritance graph order. Used for determining the primary base class.
621 const CXXRecordDecl *FirstNearlyEmptyVBase;
623 /// VisitedVirtualBases - A set of all the visited virtual bases, used to
624 /// avoid visiting virtual bases more than once.
625 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
627 /// \brief Externally-provided size.
628 uint64_t ExternalSize;
630 /// \brief Externally-provided alignment.
631 uint64_t ExternalAlign;
633 /// \brief Externally-provided field offsets.
634 llvm::DenseMap<const FieldDecl *, uint64_t> ExternalFieldOffsets;
636 /// \brief Externally-provided direct, non-virtual base offsets.
637 llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalBaseOffsets;
639 /// \brief Externally-provided virtual base offsets.
640 llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalVirtualBaseOffsets;
642 RecordLayoutBuilder(const ASTContext &Context,
643 EmptySubobjectMap *EmptySubobjects)
644 : Context(Context), EmptySubobjects(EmptySubobjects), Size(0),
645 Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()),
646 ExternalLayout(false), InferAlignment(false),
647 Packed(false), IsUnion(false), IsMac68kAlign(false), IsMsStruct(false),
648 UnfilledBitsInLastUnit(0), LastBitfieldTypeSize(0),
649 MaxFieldAlignment(CharUnits::Zero()),
650 DataSize(0), NonVirtualSize(CharUnits::Zero()),
651 NonVirtualAlignment(CharUnits::One()),
652 PrimaryBase(0), PrimaryBaseIsVirtual(false),
654 FirstNearlyEmptyVBase(0) { }
656 /// Reset this RecordLayoutBuilder to a fresh state, using the given
657 /// alignment as the initial alignment. This is used for the
658 /// correct layout of vb-table pointers in MSVC.
659 void resetWithTargetAlignment(CharUnits TargetAlignment) {
660 const ASTContext &Context = this->Context;
661 EmptySubobjectMap *EmptySubobjects = this->EmptySubobjects;
662 this->~RecordLayoutBuilder();
663 new (this) RecordLayoutBuilder(Context, EmptySubobjects);
664 Alignment = UnpackedAlignment = TargetAlignment;
667 void Layout(const RecordDecl *D);
668 void Layout(const CXXRecordDecl *D);
669 void Layout(const ObjCInterfaceDecl *D);
671 void LayoutFields(const RecordDecl *D);
672 void LayoutField(const FieldDecl *D);
673 void LayoutWideBitField(uint64_t FieldSize, uint64_t TypeSize,
674 bool FieldPacked, const FieldDecl *D);
675 void LayoutBitField(const FieldDecl *D);
677 TargetCXXABI getCXXABI() const {
678 return Context.getTargetInfo().getCXXABI();
681 /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects.
682 llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator;
684 typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *>
685 BaseSubobjectInfoMapTy;
687 /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases
688 /// of the class we're laying out to their base subobject info.
689 BaseSubobjectInfoMapTy VirtualBaseInfo;
691 /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the
692 /// class we're laying out to their base subobject info.
693 BaseSubobjectInfoMapTy NonVirtualBaseInfo;
695 /// ComputeBaseSubobjectInfo - Compute the base subobject information for the
696 /// bases of the given class.
697 void ComputeBaseSubobjectInfo(const CXXRecordDecl *RD);
699 /// ComputeBaseSubobjectInfo - Compute the base subobject information for a
700 /// single class and all of its base classes.
701 BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
703 BaseSubobjectInfo *Derived);
705 /// DeterminePrimaryBase - Determine the primary base of the given class.
706 void DeterminePrimaryBase(const CXXRecordDecl *RD);
708 void SelectPrimaryVBase(const CXXRecordDecl *RD);
710 void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign);
712 /// LayoutNonVirtualBases - Determines the primary base class (if any) and
713 /// lays it out. Will then proceed to lay out all non-virtual base clasess.
714 void LayoutNonVirtualBases(const CXXRecordDecl *RD);
716 /// LayoutNonVirtualBase - Lays out a single non-virtual base.
717 void LayoutNonVirtualBase(const BaseSubobjectInfo *Base);
719 void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
722 /// LayoutVirtualBases - Lays out all the virtual bases.
723 void LayoutVirtualBases(const CXXRecordDecl *RD,
724 const CXXRecordDecl *MostDerivedClass);
726 /// LayoutVirtualBase - Lays out a single virtual base.
727 void LayoutVirtualBase(const BaseSubobjectInfo *Base);
729 /// LayoutBase - Will lay out a base and return the offset where it was
730 /// placed, in chars.
731 CharUnits LayoutBase(const BaseSubobjectInfo *Base);
733 /// InitializeLayout - Initialize record layout for the given record decl.
734 void InitializeLayout(const Decl *D);
736 /// FinishLayout - Finalize record layout. Adjust record size based on the
738 void FinishLayout(const NamedDecl *D);
740 void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment);
741 void UpdateAlignment(CharUnits NewAlignment) {
742 UpdateAlignment(NewAlignment, NewAlignment);
745 /// \brief Retrieve the externally-supplied field offset for the given
748 /// \param Field The field whose offset is being queried.
749 /// \param ComputedOffset The offset that we've computed for this field.
750 uint64_t updateExternalFieldOffset(const FieldDecl *Field,
751 uint64_t ComputedOffset);
753 void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset,
754 uint64_t UnpackedOffset, unsigned UnpackedAlign,
755 bool isPacked, const FieldDecl *D);
757 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
759 CharUnits getSize() const {
760 assert(Size % Context.getCharWidth() == 0);
761 return Context.toCharUnitsFromBits(Size);
763 uint64_t getSizeInBits() const { return Size; }
765 void setSize(CharUnits NewSize) { Size = Context.toBits(NewSize); }
766 void setSize(uint64_t NewSize) { Size = NewSize; }
768 CharUnits getAligment() const { return Alignment; }
770 CharUnits getDataSize() const {
771 assert(DataSize % Context.getCharWidth() == 0);
772 return Context.toCharUnitsFromBits(DataSize);
774 uint64_t getDataSizeInBits() const { return DataSize; }
776 void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); }
777 void setDataSize(uint64_t NewSize) { DataSize = NewSize; }
779 RecordLayoutBuilder(const RecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
780 void operator=(const RecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
782 } // end anonymous namespace
785 RecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) {
786 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
787 E = RD->bases_end(); I != E; ++I) {
788 assert(!I->getType()->isDependentType() &&
789 "Cannot layout class with dependent bases.");
791 const CXXRecordDecl *Base =
792 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
794 // Check if this is a nearly empty virtual base.
795 if (I->isVirtual() && Context.isNearlyEmpty(Base)) {
796 // If it's not an indirect primary base, then we've found our primary
798 if (!IndirectPrimaryBases.count(Base)) {
800 PrimaryBaseIsVirtual = true;
804 // Is this the first nearly empty virtual base?
805 if (!FirstNearlyEmptyVBase)
806 FirstNearlyEmptyVBase = Base;
809 SelectPrimaryVBase(Base);
815 /// DeterminePrimaryBase - Determine the primary base of the given class.
816 void RecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) {
817 // If the class isn't dynamic, it won't have a primary base.
818 if (!RD->isDynamicClass())
821 // Compute all the primary virtual bases for all of our direct and
822 // indirect bases, and record all their primary virtual base classes.
823 RD->getIndirectPrimaryBases(IndirectPrimaryBases);
825 // If the record has a dynamic base class, attempt to choose a primary base
826 // class. It is the first (in direct base class order) non-virtual dynamic
827 // base class, if one exists.
828 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
829 e = RD->bases_end(); i != e; ++i) {
830 // Ignore virtual bases.
834 const CXXRecordDecl *Base =
835 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
837 if (Base->isDynamicClass()) {
840 PrimaryBaseIsVirtual = false;
845 // Under the Itanium ABI, if there is no non-virtual primary base class,
846 // try to compute the primary virtual base. The primary virtual base is
847 // the first nearly empty virtual base that is not an indirect primary
848 // virtual base class, if one exists.
849 if (RD->getNumVBases() != 0) {
850 SelectPrimaryVBase(RD);
855 // Otherwise, it is the first indirect primary base class, if one exists.
856 if (FirstNearlyEmptyVBase) {
857 PrimaryBase = FirstNearlyEmptyVBase;
858 PrimaryBaseIsVirtual = true;
862 assert(!PrimaryBase && "Should not get here with a primary base!");
866 RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
868 BaseSubobjectInfo *Derived) {
869 BaseSubobjectInfo *Info;
872 // Check if we already have info about this virtual base.
873 BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD];
875 assert(InfoSlot->Class == RD && "Wrong class for virtual base info!");
879 // We don't, create it.
880 InfoSlot = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
883 Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
887 Info->IsVirtual = IsVirtual;
889 Info->PrimaryVirtualBaseInfo = 0;
891 const CXXRecordDecl *PrimaryVirtualBase = 0;
892 BaseSubobjectInfo *PrimaryVirtualBaseInfo = 0;
894 // Check if this base has a primary virtual base.
895 if (RD->getNumVBases()) {
896 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
897 if (Layout.isPrimaryBaseVirtual()) {
898 // This base does have a primary virtual base.
899 PrimaryVirtualBase = Layout.getPrimaryBase();
900 assert(PrimaryVirtualBase && "Didn't have a primary virtual base!");
902 // Now check if we have base subobject info about this primary base.
903 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
905 if (PrimaryVirtualBaseInfo) {
906 if (PrimaryVirtualBaseInfo->Derived) {
907 // We did have info about this primary base, and it turns out that it
908 // has already been claimed as a primary virtual base for another
910 PrimaryVirtualBase = 0;
912 // We can claim this base as our primary base.
913 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
914 PrimaryVirtualBaseInfo->Derived = Info;
920 // Now go through all direct bases.
921 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
922 E = RD->bases_end(); I != E; ++I) {
923 bool IsVirtual = I->isVirtual();
925 const CXXRecordDecl *BaseDecl =
926 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
928 Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info));
931 if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) {
932 // Traversing the bases must have created the base info for our primary
934 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
935 assert(PrimaryVirtualBaseInfo &&
936 "Did not create a primary virtual base!");
938 // Claim the primary virtual base as our primary virtual base.
939 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
940 PrimaryVirtualBaseInfo->Derived = Info;
946 void RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD) {
947 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
948 E = RD->bases_end(); I != E; ++I) {
949 bool IsVirtual = I->isVirtual();
951 const CXXRecordDecl *BaseDecl =
952 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
954 // Compute the base subobject info for this base.
955 BaseSubobjectInfo *Info = ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, 0);
958 // ComputeBaseInfo has already added this base for us.
959 assert(VirtualBaseInfo.count(BaseDecl) &&
960 "Did not add virtual base!");
962 // Add the base info to the map of non-virtual bases.
963 assert(!NonVirtualBaseInfo.count(BaseDecl) &&
964 "Non-virtual base already exists!");
965 NonVirtualBaseInfo.insert(std::make_pair(BaseDecl, Info));
971 RecordLayoutBuilder::EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign) {
972 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
974 // The maximum field alignment overrides base align.
975 if (!MaxFieldAlignment.isZero()) {
976 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
977 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
980 // Round up the current record size to pointer alignment.
981 setSize(getSize().RoundUpToAlignment(BaseAlign));
982 setDataSize(getSize());
984 // Update the alignment.
985 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
989 RecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl *RD) {
990 // Then, determine the primary base class.
991 DeterminePrimaryBase(RD);
993 // Compute base subobject info.
994 ComputeBaseSubobjectInfo(RD);
996 // If we have a primary base class, lay it out.
998 if (PrimaryBaseIsVirtual) {
999 // If the primary virtual base was a primary virtual base of some other
1000 // base class we'll have to steal it.
1001 BaseSubobjectInfo *PrimaryBaseInfo = VirtualBaseInfo.lookup(PrimaryBase);
1002 PrimaryBaseInfo->Derived = 0;
1004 // We have a virtual primary base, insert it as an indirect primary base.
1005 IndirectPrimaryBases.insert(PrimaryBase);
1007 assert(!VisitedVirtualBases.count(PrimaryBase) &&
1008 "vbase already visited!");
1009 VisitedVirtualBases.insert(PrimaryBase);
1011 LayoutVirtualBase(PrimaryBaseInfo);
1013 BaseSubobjectInfo *PrimaryBaseInfo =
1014 NonVirtualBaseInfo.lookup(PrimaryBase);
1015 assert(PrimaryBaseInfo &&
1016 "Did not find base info for non-virtual primary base!");
1018 LayoutNonVirtualBase(PrimaryBaseInfo);
1021 // If this class needs a vtable/vf-table and didn't get one from a
1022 // primary base, add it in now.
1023 } else if (RD->isDynamicClass()) {
1024 assert(DataSize == 0 && "Vtable pointer must be at offset zero!");
1025 CharUnits PtrWidth =
1026 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
1027 CharUnits PtrAlign =
1028 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
1029 EnsureVTablePointerAlignment(PtrAlign);
1031 setSize(getSize() + PtrWidth);
1032 setDataSize(getSize());
1035 // Now lay out the non-virtual bases.
1036 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1037 E = RD->bases_end(); I != E; ++I) {
1039 // Ignore virtual bases.
1043 const CXXRecordDecl *BaseDecl =
1044 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1046 // Skip the primary base, because we've already laid it out. The
1047 // !PrimaryBaseIsVirtual check is required because we might have a
1048 // non-virtual base of the same type as a primary virtual base.
1049 if (BaseDecl == PrimaryBase && !PrimaryBaseIsVirtual)
1052 // Lay out the base.
1053 BaseSubobjectInfo *BaseInfo = NonVirtualBaseInfo.lookup(BaseDecl);
1054 assert(BaseInfo && "Did not find base info for non-virtual base!");
1056 LayoutNonVirtualBase(BaseInfo);
1060 void RecordLayoutBuilder::LayoutNonVirtualBase(const BaseSubobjectInfo *Base) {
1062 CharUnits Offset = LayoutBase(Base);
1064 // Add its base class offset.
1065 assert(!Bases.count(Base->Class) && "base offset already exists!");
1066 Bases.insert(std::make_pair(Base->Class, Offset));
1068 AddPrimaryVirtualBaseOffsets(Base, Offset);
1072 RecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
1074 // This base isn't interesting, it has no virtual bases.
1075 if (!Info->Class->getNumVBases())
1078 // First, check if we have a virtual primary base to add offsets for.
1079 if (Info->PrimaryVirtualBaseInfo) {
1080 assert(Info->PrimaryVirtualBaseInfo->IsVirtual &&
1081 "Primary virtual base is not virtual!");
1082 if (Info->PrimaryVirtualBaseInfo->Derived == Info) {
1084 assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) &&
1085 "primary vbase offset already exists!");
1086 VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class,
1087 ASTRecordLayout::VBaseInfo(Offset, false)));
1089 // Traverse the primary virtual base.
1090 AddPrimaryVirtualBaseOffsets(Info->PrimaryVirtualBaseInfo, Offset);
1094 // Now go through all direct non-virtual bases.
1095 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
1096 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
1097 const BaseSubobjectInfo *Base = Info->Bases[I];
1098 if (Base->IsVirtual)
1101 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
1102 AddPrimaryVirtualBaseOffsets(Base, BaseOffset);
1107 RecordLayoutBuilder::LayoutVirtualBases(const CXXRecordDecl *RD,
1108 const CXXRecordDecl *MostDerivedClass) {
1109 const CXXRecordDecl *PrimaryBase;
1110 bool PrimaryBaseIsVirtual;
1112 if (MostDerivedClass == RD) {
1113 PrimaryBase = this->PrimaryBase;
1114 PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual;
1116 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1117 PrimaryBase = Layout.getPrimaryBase();
1118 PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
1121 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1122 E = RD->bases_end(); I != E; ++I) {
1123 assert(!I->getType()->isDependentType() &&
1124 "Cannot layout class with dependent bases.");
1126 const CXXRecordDecl *BaseDecl =
1127 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1129 if (I->isVirtual()) {
1130 if (PrimaryBase != BaseDecl || !PrimaryBaseIsVirtual) {
1131 bool IndirectPrimaryBase = IndirectPrimaryBases.count(BaseDecl);
1133 // Only lay out the virtual base if it's not an indirect primary base.
1134 if (!IndirectPrimaryBase) {
1135 // Only visit virtual bases once.
1136 if (!VisitedVirtualBases.insert(BaseDecl))
1139 const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1140 assert(BaseInfo && "Did not find virtual base info!");
1141 LayoutVirtualBase(BaseInfo);
1146 if (!BaseDecl->getNumVBases()) {
1147 // This base isn't interesting since it doesn't have any virtual bases.
1151 LayoutVirtualBases(BaseDecl, MostDerivedClass);
1155 void RecordLayoutBuilder::LayoutVirtualBase(const BaseSubobjectInfo *Base) {
1156 assert(!Base->Derived && "Trying to lay out a primary virtual base!");
1159 CharUnits Offset = LayoutBase(Base);
1161 // Add its base class offset.
1162 assert(!VBases.count(Base->Class) && "vbase offset already exists!");
1163 VBases.insert(std::make_pair(Base->Class,
1164 ASTRecordLayout::VBaseInfo(Offset, false)));
1166 AddPrimaryVirtualBaseOffsets(Base, Offset);
1169 CharUnits RecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) {
1170 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class);
1175 // Query the external layout to see if it provides an offset.
1176 bool HasExternalLayout = false;
1177 if (ExternalLayout) {
1178 llvm::DenseMap<const CXXRecordDecl *, CharUnits>::iterator Known;
1179 if (Base->IsVirtual) {
1180 Known = ExternalVirtualBaseOffsets.find(Base->Class);
1181 if (Known != ExternalVirtualBaseOffsets.end()) {
1182 Offset = Known->second;
1183 HasExternalLayout = true;
1186 Known = ExternalBaseOffsets.find(Base->Class);
1187 if (Known != ExternalBaseOffsets.end()) {
1188 Offset = Known->second;
1189 HasExternalLayout = true;
1194 CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlign();
1195 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
1197 // If we have an empty base class, try to place it at offset 0.
1198 if (Base->Class->isEmpty() &&
1199 (!HasExternalLayout || Offset == CharUnits::Zero()) &&
1200 EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) {
1201 setSize(std::max(getSize(), Layout.getSize()));
1202 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
1204 return CharUnits::Zero();
1207 // The maximum field alignment overrides base align.
1208 if (!MaxFieldAlignment.isZero()) {
1209 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1210 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
1213 if (!HasExternalLayout) {
1214 // Round up the current record size to the base's alignment boundary.
1215 Offset = getDataSize().RoundUpToAlignment(BaseAlign);
1217 // Try to place the base.
1218 while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset))
1219 Offset += BaseAlign;
1221 bool Allowed = EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset);
1223 assert(Allowed && "Base subobject externally placed at overlapping offset");
1225 if (InferAlignment && Offset < getDataSize().RoundUpToAlignment(BaseAlign)){
1226 // The externally-supplied base offset is before the base offset we
1227 // computed. Assume that the structure is packed.
1228 Alignment = CharUnits::One();
1229 InferAlignment = false;
1233 if (!Base->Class->isEmpty()) {
1234 // Update the data size.
1235 setDataSize(Offset + Layout.getNonVirtualSize());
1237 setSize(std::max(getSize(), getDataSize()));
1239 setSize(std::max(getSize(), Offset + Layout.getSize()));
1241 // Remember max struct/class alignment.
1242 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
1247 void RecordLayoutBuilder::InitializeLayout(const Decl *D) {
1248 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1249 IsUnion = RD->isUnion();
1250 IsMsStruct = RD->isMsStruct(Context);
1253 Packed = D->hasAttr<PackedAttr>();
1255 // Honor the default struct packing maximum alignment flag.
1256 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) {
1257 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
1260 // mac68k alignment supersedes maximum field alignment and attribute aligned,
1261 // and forces all structures to have 2-byte alignment. The IBM docs on it
1262 // allude to additional (more complicated) semantics, especially with regard
1263 // to bit-fields, but gcc appears not to follow that.
1264 if (D->hasAttr<AlignMac68kAttr>()) {
1265 IsMac68kAlign = true;
1266 MaxFieldAlignment = CharUnits::fromQuantity(2);
1267 Alignment = CharUnits::fromQuantity(2);
1269 if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>())
1270 MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment());
1272 if (unsigned MaxAlign = D->getMaxAlignment())
1273 UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign));
1276 // If there is an external AST source, ask it for the various offsets.
1277 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
1278 if (ExternalASTSource *External = Context.getExternalSource()) {
1279 ExternalLayout = External->layoutRecordType(RD,
1282 ExternalFieldOffsets,
1283 ExternalBaseOffsets,
1284 ExternalVirtualBaseOffsets);
1286 // Update based on external alignment.
1287 if (ExternalLayout) {
1288 if (ExternalAlign > 0) {
1289 Alignment = Context.toCharUnitsFromBits(ExternalAlign);
1291 // The external source didn't have alignment information; infer it.
1292 InferAlignment = true;
1298 void RecordLayoutBuilder::Layout(const RecordDecl *D) {
1299 InitializeLayout(D);
1302 // Finally, round the size of the total struct up to the alignment of the
1307 void RecordLayoutBuilder::Layout(const CXXRecordDecl *RD) {
1308 InitializeLayout(RD);
1310 // Lay out the vtable and the non-virtual bases.
1311 LayoutNonVirtualBases(RD);
1315 NonVirtualSize = Context.toCharUnitsFromBits(
1316 llvm::RoundUpToAlignment(getSizeInBits(),
1317 Context.getTargetInfo().getCharAlign()));
1318 NonVirtualAlignment = Alignment;
1320 // Lay out the virtual bases and add the primary virtual base offsets.
1321 LayoutVirtualBases(RD, RD);
1323 // Finally, round the size of the total struct up to the alignment
1324 // of the struct itself.
1328 // Check that we have base offsets for all bases.
1329 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1330 E = RD->bases_end(); I != E; ++I) {
1334 const CXXRecordDecl *BaseDecl =
1335 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1337 assert(Bases.count(BaseDecl) && "Did not find base offset!");
1340 // And all virtual bases.
1341 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
1342 E = RD->vbases_end(); I != E; ++I) {
1343 const CXXRecordDecl *BaseDecl =
1344 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1346 assert(VBases.count(BaseDecl) && "Did not find base offset!");
1351 void RecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) {
1352 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
1353 const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD);
1355 UpdateAlignment(SL.getAlignment());
1357 // We start laying out ivars not at the end of the superclass
1358 // structure, but at the next byte following the last field.
1359 setSize(SL.getDataSize());
1360 setDataSize(getSize());
1363 InitializeLayout(D);
1364 // Layout each ivar sequentially.
1365 for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD;
1366 IVD = IVD->getNextIvar())
1369 // Finally, round the size of the total struct up to the alignment of the
1374 void RecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
1375 // Layout each field, for now, just sequentially, respecting alignment. In
1376 // the future, this will need to be tweakable by targets.
1377 for (RecordDecl::field_iterator Field = D->field_begin(),
1378 FieldEnd = D->field_end(); Field != FieldEnd; ++Field)
1379 LayoutField(*Field);
1382 void RecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize,
1385 const FieldDecl *D) {
1386 assert(Context.getLangOpts().CPlusPlus &&
1387 "Can only have wide bit-fields in C++!");
1389 // Itanium C++ ABI 2.4:
1390 // If sizeof(T)*8 < n, let T' be the largest integral POD type with
1391 // sizeof(T')*8 <= n.
1393 QualType IntegralPODTypes[] = {
1394 Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy,
1395 Context.UnsignedLongTy, Context.UnsignedLongLongTy
1399 for (unsigned I = 0, E = llvm::array_lengthof(IntegralPODTypes);
1401 uint64_t Size = Context.getTypeSize(IntegralPODTypes[I]);
1403 if (Size > FieldSize)
1406 Type = IntegralPODTypes[I];
1408 assert(!Type.isNull() && "Did not find a type!");
1410 CharUnits TypeAlign = Context.getTypeAlignInChars(Type);
1412 // We're not going to use any of the unfilled bits in the last byte.
1413 UnfilledBitsInLastUnit = 0;
1414 LastBitfieldTypeSize = 0;
1416 uint64_t FieldOffset;
1417 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
1420 setDataSize(std::max(getDataSizeInBits(), FieldSize));
1423 // The bitfield is allocated starting at the next offset aligned
1424 // appropriately for T', with length n bits.
1425 FieldOffset = llvm::RoundUpToAlignment(getDataSizeInBits(),
1426 Context.toBits(TypeAlign));
1428 uint64_t NewSizeInBits = FieldOffset + FieldSize;
1430 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
1431 Context.getTargetInfo().getCharAlign()));
1432 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
1435 // Place this field at the current location.
1436 FieldOffsets.push_back(FieldOffset);
1438 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset,
1439 Context.toBits(TypeAlign), FieldPacked, D);
1442 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1444 // Remember max struct/class alignment.
1445 UpdateAlignment(TypeAlign);
1448 void RecordLayoutBuilder::LayoutBitField(const FieldDecl *D) {
1449 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
1450 uint64_t FieldSize = D->getBitWidthValue(Context);
1451 std::pair<uint64_t, unsigned> FieldInfo = Context.getTypeInfo(D->getType());
1452 uint64_t TypeSize = FieldInfo.first;
1453 unsigned FieldAlign = FieldInfo.second;
1456 // The field alignment for integer types in ms_struct structs is
1458 FieldAlign = TypeSize;
1459 // Ignore zero-length bitfields after non-bitfields in ms_struct structs.
1460 if (!FieldSize && !LastBitfieldTypeSize)
1462 // If a bitfield is followed by a bitfield of a different size, don't
1463 // pack the bits together in ms_struct structs.
1464 if (LastBitfieldTypeSize != TypeSize) {
1465 UnfilledBitsInLastUnit = 0;
1466 LastBitfieldTypeSize = 0;
1470 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
1471 uint64_t FieldOffset = IsUnion ? 0 : UnpaddedFieldOffset;
1473 bool ZeroLengthBitfield = false;
1474 if (!Context.getTargetInfo().useBitFieldTypeAlignment() &&
1475 Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
1477 // The alignment of a zero-length bitfield affects the alignment
1478 // of the next member. The alignment is the max of the zero
1479 // length bitfield's alignment and a target specific fixed value.
1480 ZeroLengthBitfield = true;
1481 unsigned ZeroLengthBitfieldBoundary =
1482 Context.getTargetInfo().getZeroLengthBitfieldBoundary();
1483 if (ZeroLengthBitfieldBoundary > FieldAlign)
1484 FieldAlign = ZeroLengthBitfieldBoundary;
1487 if (FieldSize > TypeSize) {
1488 LayoutWideBitField(FieldSize, TypeSize, FieldPacked, D);
1492 // The align if the field is not packed. This is to check if the attribute
1493 // was unnecessary (-Wpacked).
1494 unsigned UnpackedFieldAlign = FieldAlign;
1495 uint64_t UnpackedFieldOffset = FieldOffset;
1496 if (!Context.getTargetInfo().useBitFieldTypeAlignment() && !ZeroLengthBitfield)
1497 UnpackedFieldAlign = 1;
1500 (!Context.getTargetInfo().useBitFieldTypeAlignment() && !ZeroLengthBitfield))
1502 FieldAlign = std::max(FieldAlign, D->getMaxAlignment());
1503 UnpackedFieldAlign = std::max(UnpackedFieldAlign, D->getMaxAlignment());
1505 // The maximum field alignment overrides the aligned attribute.
1506 if (!MaxFieldAlignment.isZero() && FieldSize != 0) {
1507 unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment);
1508 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1509 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
1512 // ms_struct bitfields always have to start at a round alignment.
1513 if (IsMsStruct && !LastBitfieldTypeSize) {
1514 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
1515 UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1516 UnpackedFieldAlign);
1519 // Check if we need to add padding to give the field the correct alignment.
1520 if (FieldSize == 0 ||
1521 (MaxFieldAlignment.isZero() &&
1522 (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize))
1523 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
1525 if (FieldSize == 0 ||
1526 (MaxFieldAlignment.isZero() &&
1527 (UnpackedFieldOffset & (UnpackedFieldAlign-1)) + FieldSize > TypeSize))
1528 UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1529 UnpackedFieldAlign);
1531 // Padding members don't affect overall alignment, unless zero length bitfield
1532 // alignment is enabled.
1533 if (!D->getIdentifier() &&
1534 !Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
1536 FieldAlign = UnpackedFieldAlign = 1;
1539 FieldOffset = updateExternalFieldOffset(D, FieldOffset);
1541 // Place this field at the current location.
1542 FieldOffsets.push_back(FieldOffset);
1544 if (!ExternalLayout)
1545 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset,
1546 UnpackedFieldAlign, FieldPacked, D);
1548 // Update DataSize to include the last byte containing (part of) the bitfield.
1550 // FIXME: I think FieldSize should be TypeSize here.
1551 setDataSize(std::max(getDataSizeInBits(), FieldSize));
1553 if (IsMsStruct && FieldSize) {
1554 // Under ms_struct, a bitfield always takes up space equal to the size
1555 // of the type. We can't just change the alignment computation on the
1556 // other codepath because of the way this interacts with #pragma pack:
1557 // in a packed struct, we need to allocate misaligned space in the
1558 // struct to hold the bitfield.
1559 if (!UnfilledBitsInLastUnit) {
1560 setDataSize(FieldOffset + TypeSize);
1561 UnfilledBitsInLastUnit = TypeSize - FieldSize;
1562 } else if (UnfilledBitsInLastUnit < FieldSize) {
1563 setDataSize(getDataSizeInBits() + TypeSize);
1564 UnfilledBitsInLastUnit = TypeSize - FieldSize;
1566 UnfilledBitsInLastUnit -= FieldSize;
1568 LastBitfieldTypeSize = TypeSize;
1570 uint64_t NewSizeInBits = FieldOffset + FieldSize;
1571 uint64_t BitfieldAlignment = Context.getTargetInfo().getCharAlign();
1572 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits, BitfieldAlignment));
1573 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
1574 LastBitfieldTypeSize = 0;
1579 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1581 // Remember max struct/class alignment.
1582 UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign),
1583 Context.toCharUnitsFromBits(UnpackedFieldAlign));
1586 void RecordLayoutBuilder::LayoutField(const FieldDecl *D) {
1587 if (D->isBitField()) {
1592 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
1594 // Reset the unfilled bits.
1595 UnfilledBitsInLastUnit = 0;
1596 LastBitfieldTypeSize = 0;
1598 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
1599 CharUnits FieldOffset =
1600 IsUnion ? CharUnits::Zero() : getDataSize();
1601 CharUnits FieldSize;
1602 CharUnits FieldAlign;
1604 if (D->getType()->isIncompleteArrayType()) {
1605 // This is a flexible array member; we can't directly
1606 // query getTypeInfo about these, so we figure it out here.
1607 // Flexible array members don't have any size, but they
1608 // have to be aligned appropriately for their element type.
1609 FieldSize = CharUnits::Zero();
1610 const ArrayType* ATy = Context.getAsArrayType(D->getType());
1611 FieldAlign = Context.getTypeAlignInChars(ATy->getElementType());
1612 } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) {
1613 unsigned AS = RT->getPointeeType().getAddressSpace();
1615 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(AS));
1617 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(AS));
1619 std::pair<CharUnits, CharUnits> FieldInfo =
1620 Context.getTypeInfoInChars(D->getType());
1621 FieldSize = FieldInfo.first;
1622 FieldAlign = FieldInfo.second;
1625 // If MS bitfield layout is required, figure out what type is being
1626 // laid out and align the field to the width of that type.
1628 // Resolve all typedefs down to their base type and round up the field
1629 // alignment if necessary.
1630 QualType T = Context.getBaseElementType(D->getType());
1631 if (const BuiltinType *BTy = T->getAs<BuiltinType>()) {
1632 CharUnits TypeSize = Context.getTypeSizeInChars(BTy);
1633 if (TypeSize > FieldAlign)
1634 FieldAlign = TypeSize;
1639 // The align if the field is not packed. This is to check if the attribute
1640 // was unnecessary (-Wpacked).
1641 CharUnits UnpackedFieldAlign = FieldAlign;
1642 CharUnits UnpackedFieldOffset = FieldOffset;
1645 FieldAlign = CharUnits::One();
1646 CharUnits MaxAlignmentInChars =
1647 Context.toCharUnitsFromBits(D->getMaxAlignment());
1648 FieldAlign = std::max(FieldAlign, MaxAlignmentInChars);
1649 UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars);
1651 // The maximum field alignment overrides the aligned attribute.
1652 if (!MaxFieldAlignment.isZero()) {
1653 FieldAlign = std::min(FieldAlign, MaxFieldAlignment);
1654 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment);
1657 // Round up the current record size to the field's alignment boundary.
1658 FieldOffset = FieldOffset.RoundUpToAlignment(FieldAlign);
1659 UnpackedFieldOffset =
1660 UnpackedFieldOffset.RoundUpToAlignment(UnpackedFieldAlign);
1662 if (ExternalLayout) {
1663 FieldOffset = Context.toCharUnitsFromBits(
1664 updateExternalFieldOffset(D, Context.toBits(FieldOffset)));
1666 if (!IsUnion && EmptySubobjects) {
1667 // Record the fact that we're placing a field at this offset.
1668 bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset);
1670 assert(Allowed && "Externally-placed field cannot be placed here");
1673 if (!IsUnion && EmptySubobjects) {
1674 // Check if we can place the field at this offset.
1675 while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) {
1676 // We couldn't place the field at the offset. Try again at a new offset.
1677 FieldOffset += FieldAlign;
1682 // Place this field at the current location.
1683 FieldOffsets.push_back(Context.toBits(FieldOffset));
1685 if (!ExternalLayout)
1686 CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset,
1687 Context.toBits(UnpackedFieldOffset),
1688 Context.toBits(UnpackedFieldAlign), FieldPacked, D);
1690 // Reserve space for this field.
1691 uint64_t FieldSizeInBits = Context.toBits(FieldSize);
1693 setDataSize(std::max(getDataSizeInBits(), FieldSizeInBits));
1695 setDataSize(FieldOffset + FieldSize);
1698 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1700 // Remember max struct/class alignment.
1701 UpdateAlignment(FieldAlign, UnpackedFieldAlign);
1704 void RecordLayoutBuilder::FinishLayout(const NamedDecl *D) {
1705 // In C++, records cannot be of size 0.
1706 if (Context.getLangOpts().CPlusPlus && getSizeInBits() == 0) {
1707 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
1708 // Compatibility with gcc requires a class (pod or non-pod)
1709 // which is not empty but of size 0; such as having fields of
1710 // array of zero-length, remains of Size 0
1712 setSize(CharUnits::One());
1715 setSize(CharUnits::One());
1718 // Finally, round the size of the record up to the alignment of the
1720 uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastUnit;
1721 uint64_t UnpackedSizeInBits =
1722 llvm::RoundUpToAlignment(getSizeInBits(),
1723 Context.toBits(UnpackedAlignment));
1724 CharUnits UnpackedSize = Context.toCharUnitsFromBits(UnpackedSizeInBits);
1725 uint64_t RoundedSize
1726 = llvm::RoundUpToAlignment(getSizeInBits(), Context.toBits(Alignment));
1728 if (ExternalLayout) {
1729 // If we're inferring alignment, and the external size is smaller than
1730 // our size after we've rounded up to alignment, conservatively set the
1732 if (InferAlignment && ExternalSize < RoundedSize) {
1733 Alignment = CharUnits::One();
1734 InferAlignment = false;
1736 setSize(ExternalSize);
1740 // Set the size to the final size.
1741 setSize(RoundedSize);
1743 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
1744 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1745 // Warn if padding was introduced to the struct/class/union.
1746 if (getSizeInBits() > UnpaddedSize) {
1747 unsigned PadSize = getSizeInBits() - UnpaddedSize;
1749 if (PadSize % CharBitNum == 0) {
1750 PadSize = PadSize / CharBitNum;
1753 Diag(RD->getLocation(), diag::warn_padded_struct_size)
1754 << Context.getTypeDeclType(RD)
1756 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
1759 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
1760 // bother since there won't be alignment issues.
1761 if (Packed && UnpackedAlignment > CharUnits::One() &&
1762 getSize() == UnpackedSize)
1763 Diag(D->getLocation(), diag::warn_unnecessary_packed)
1764 << Context.getTypeDeclType(RD);
1768 void RecordLayoutBuilder::UpdateAlignment(CharUnits NewAlignment,
1769 CharUnits UnpackedNewAlignment) {
1770 // The alignment is not modified when using 'mac68k' alignment or when
1771 // we have an externally-supplied layout that also provides overall alignment.
1772 if (IsMac68kAlign || (ExternalLayout && !InferAlignment))
1775 if (NewAlignment > Alignment) {
1776 assert(llvm::isPowerOf2_32(NewAlignment.getQuantity() &&
1777 "Alignment not a power of 2"));
1778 Alignment = NewAlignment;
1781 if (UnpackedNewAlignment > UnpackedAlignment) {
1782 assert(llvm::isPowerOf2_32(UnpackedNewAlignment.getQuantity() &&
1783 "Alignment not a power of 2"));
1784 UnpackedAlignment = UnpackedNewAlignment;
1789 RecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field,
1790 uint64_t ComputedOffset) {
1791 assert(ExternalFieldOffsets.find(Field) != ExternalFieldOffsets.end() &&
1792 "Field does not have an external offset");
1794 uint64_t ExternalFieldOffset = ExternalFieldOffsets[Field];
1796 if (InferAlignment && ExternalFieldOffset < ComputedOffset) {
1797 // The externally-supplied field offset is before the field offset we
1798 // computed. Assume that the structure is packed.
1799 Alignment = CharUnits::One();
1800 InferAlignment = false;
1803 // Use the externally-supplied field offset.
1804 return ExternalFieldOffset;
1807 /// \brief Get diagnostic %select index for tag kind for
1808 /// field padding diagnostic message.
1809 /// WARNING: Indexes apply to particular diagnostics only!
1811 /// \returns diagnostic %select index.
1812 static unsigned getPaddingDiagFromTagKind(TagTypeKind Tag) {
1814 case TTK_Struct: return 0;
1815 case TTK_Interface: return 1;
1816 case TTK_Class: return 2;
1817 default: llvm_unreachable("Invalid tag kind for field padding diagnostic!");
1821 void RecordLayoutBuilder::CheckFieldPadding(uint64_t Offset,
1822 uint64_t UnpaddedOffset,
1823 uint64_t UnpackedOffset,
1824 unsigned UnpackedAlign,
1826 const FieldDecl *D) {
1827 // We let objc ivars without warning, objc interfaces generally are not used
1828 // for padding tricks.
1829 if (isa<ObjCIvarDecl>(D))
1832 // Don't warn about structs created without a SourceLocation. This can
1833 // be done by clients of the AST, such as codegen.
1834 if (D->getLocation().isInvalid())
1837 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
1839 // Warn if padding was introduced to the struct/class.
1840 if (!IsUnion && Offset > UnpaddedOffset) {
1841 unsigned PadSize = Offset - UnpaddedOffset;
1843 if (PadSize % CharBitNum == 0) {
1844 PadSize = PadSize / CharBitNum;
1847 if (D->getIdentifier())
1848 Diag(D->getLocation(), diag::warn_padded_struct_field)
1849 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
1850 << Context.getTypeDeclType(D->getParent())
1852 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1) // plural or not
1853 << D->getIdentifier();
1855 Diag(D->getLocation(), diag::warn_padded_struct_anon_field)
1856 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
1857 << Context.getTypeDeclType(D->getParent())
1859 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
1862 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
1863 // bother since there won't be alignment issues.
1864 if (isPacked && UnpackedAlign > CharBitNum && Offset == UnpackedOffset)
1865 Diag(D->getLocation(), diag::warn_unnecessary_packed)
1866 << D->getIdentifier();
1869 static const CXXMethodDecl *computeKeyFunction(ASTContext &Context,
1870 const CXXRecordDecl *RD) {
1871 // If a class isn't polymorphic it doesn't have a key function.
1872 if (!RD->isPolymorphic())
1875 // A class that is not externally visible doesn't have a key function. (Or
1876 // at least, there's no point to assigning a key function to such a class;
1877 // this doesn't affect the ABI.)
1878 if (!RD->isExternallyVisible())
1881 // Template instantiations don't have key functions,see Itanium C++ ABI 5.2.6.
1882 // Same behavior as GCC.
1883 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
1884 if (TSK == TSK_ImplicitInstantiation ||
1885 TSK == TSK_ExplicitInstantiationDefinition)
1888 bool allowInlineFunctions =
1889 Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline();
1891 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
1892 E = RD->method_end(); I != E; ++I) {
1893 const CXXMethodDecl *MD = *I;
1895 if (!MD->isVirtual())
1901 // Ignore implicit member functions, they are always marked as inline, but
1902 // they don't have a body until they're defined.
1903 if (MD->isImplicit())
1906 if (MD->isInlineSpecified())
1909 if (MD->hasInlineBody())
1912 // Ignore inline deleted or defaulted functions.
1913 if (!MD->isUserProvided())
1916 // In certain ABIs, ignore functions with out-of-line inline definitions.
1917 if (!allowInlineFunctions) {
1918 const FunctionDecl *Def;
1919 if (MD->hasBody(Def) && Def->isInlineSpecified())
1931 RecordLayoutBuilder::Diag(SourceLocation Loc, unsigned DiagID) {
1932 return Context.getDiagnostics().Report(Loc, DiagID);
1935 /// Does the target C++ ABI require us to skip over the tail-padding
1936 /// of the given class (considering it as a base class) when allocating
1938 static bool mustSkipTailPadding(TargetCXXABI ABI, const CXXRecordDecl *RD) {
1939 switch (ABI.getTailPaddingUseRules()) {
1940 case TargetCXXABI::AlwaysUseTailPadding:
1943 case TargetCXXABI::UseTailPaddingUnlessPOD03:
1944 // FIXME: To the extent that this is meant to cover the Itanium ABI
1945 // rules, we should implement the restrictions about over-sized
1948 // http://mentorembedded.github.com/cxx-abi/abi.html#POD :
1949 // In general, a type is considered a POD for the purposes of
1950 // layout if it is a POD type (in the sense of ISO C++
1951 // [basic.types]). However, a POD-struct or POD-union (in the
1952 // sense of ISO C++ [class]) with a bitfield member whose
1953 // declared width is wider than the declared type of the
1954 // bitfield is not a POD for the purpose of layout. Similarly,
1955 // an array type is not a POD for the purpose of layout if the
1956 // element type of the array is not a POD for the purpose of
1959 // Where references to the ISO C++ are made in this paragraph,
1960 // the Technical Corrigendum 1 version of the standard is
1964 case TargetCXXABI::UseTailPaddingUnlessPOD11:
1965 // This is equivalent to RD->getTypeForDecl().isCXX11PODType(),
1966 // but with a lot of abstraction penalty stripped off. This does
1967 // assume that these properties are set correctly even in C++98
1968 // mode; fortunately, that is true because we want to assign
1969 // consistently semantics to the type-traits intrinsics (or at
1970 // least as many of them as possible).
1971 return RD->isTrivial() && RD->isStandardLayout();
1974 llvm_unreachable("bad tail-padding use kind");
1977 static bool isMsLayout(const RecordDecl* D) {
1978 return D->getASTContext().getTargetInfo().getCXXABI().isMicrosoft();
1981 // This section contains an implementation of struct layout that is, up to the
1982 // included tests, compatible with cl.exe (2012). The layout produced is
1983 // significantly different than those produced by the Itanium ABI. Here we note
1984 // the most important differences.
1986 // * The alignment of bitfields in unions is ignored when computing the
1987 // alignment of the union.
1988 // * The existance of zero-width bitfield that occurs after anything other than
1989 // a non-zero length bitfield is ignored.
1990 // * The Itanium equivalent vtable pointers are split into a vfptr (virtual
1991 // function pointer) and a vbptr (virtual base pointer). They can each be
1992 // shared with a, non-virtual bases. These bases need not be the same. vfptrs
1993 // always occur at offset 0. vbptrs can occur at an
1994 // arbitrary offset and are placed after non-virtual bases but before fields.
1995 // * Virtual bases sometimes require a 'vtordisp' field that is laid out before
1996 // the virtual base and is used in conjunction with virtual overrides during
1997 // construction and destruction.
1998 // * vfptrs are allocated in a block of memory equal to the alignment of the
1999 // fields and non-virtual bases at offset 0 in 32 bit mode and in a pointer
2000 // sized block of memory in 64 bit mode.
2001 // * vbptrs are allocated in a block of memory equal to the alignment of the
2002 // fields and non-virtual bases. This block is at a potentially unaligned
2003 // offset. If the allocation slot is unaligned and the alignment is less than
2004 // or equal to the pointer size, additional space is allocated so that the
2005 // pointer can be aligned properly. This causes very strange effects on the
2006 // placement of objects after the allocated block. (see the code).
2007 // * vtordisps are allocated in a block of memory with size and alignment equal
2008 // to the alignment of the completed structure (before applying __declspec(
2009 // align())). The vtordisp always occur at the end of the allocation block,
2010 // immediately prior to the virtual base.
2011 // * The last zero sized non-virtual base is allocated after the placement of
2012 // vbptr if one exists and can be placed at the end of the struct, potentially
2013 // aliasing either the first member or another struct allocated after this
2015 // * The last zero size virtual base may be placed at the end of the struct.
2016 // and can potentially alias a zero sized type in the next struct.
2017 // * If the last field is a non-zero length bitfield and we have any virtual
2018 // bases then some extra padding is added before the virtual bases for no
2020 // * When laying out empty non-virtual bases, an extra byte of padding is added
2021 // if the non-virtual base before the empty non-virtual base has a vbptr.
2025 struct MicrosoftRecordLayoutBuilder {
2026 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
2027 MicrosoftRecordLayoutBuilder(const ASTContext &Context) : Context(Context) {}
2029 MicrosoftRecordLayoutBuilder(const MicrosoftRecordLayoutBuilder &)
2030 LLVM_DELETED_FUNCTION;
2031 void operator=(const MicrosoftRecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
2034 void layout(const RecordDecl *RD);
2035 void cxxLayout(const CXXRecordDecl *RD);
2036 /// \brief Initializes size and alignment and honors some flags.
2037 void initializeLayout(const RecordDecl *RD);
2038 /// \brief Initialized C++ layout, compute alignment and virtual alignment and
2039 /// existance of vfptrs and vbptrs. Alignment is needed before the vfptr is
2041 void initializeCXXLayout(const CXXRecordDecl *RD);
2042 void layoutVFPtr(const CXXRecordDecl *RD);
2043 void layoutNonVirtualBases(const CXXRecordDecl *RD);
2044 void layoutNonVirtualBase(const CXXRecordDecl *RD);
2045 void layoutVBPtr(const CXXRecordDecl *RD);
2046 /// \brief Lays out the fields of the record. Also rounds size up to
2048 void layoutFields(const RecordDecl *RD);
2049 void layoutField(const FieldDecl *FD);
2050 void layoutBitField(const FieldDecl *FD);
2051 /// \brief Lays out a single zero-width bit-field in the record and handles
2052 /// special cases associated with zero-width bit-fields.
2053 void layoutZeroWidthBitField(const FieldDecl *FD);
2054 void layoutVirtualBases(const CXXRecordDecl *RD);
2055 void layoutVirtualBase(const CXXRecordDecl *RD, bool HasVtordisp);
2056 /// \brief Flushes the lazy virtual base and conditionally rounds up to
2058 void finalizeCXXLayout(const CXXRecordDecl *RD);
2059 void honorDeclspecAlign(const RecordDecl *RD);
2061 /// \brief Updates the alignment of the type. This function doesn't take any
2062 /// properties (such as packedness) into account. getAdjustedFieldInfo()
2063 /// adjustes for packedness.
2064 void updateAlignment(CharUnits NewAlignment) {
2065 Alignment = std::max(Alignment, NewAlignment);
2067 /// \brief Gets the size and alignment taking attributes into account.
2068 std::pair<CharUnits, CharUnits> getAdjustedFieldInfo(const FieldDecl *FD);
2069 /// \brief Places a field at offset 0.
2070 void placeFieldAtZero() { FieldOffsets.push_back(0); }
2071 /// \brief Places a field at an offset in CharUnits.
2072 void placeFieldAtOffset(CharUnits FieldOffset) {
2073 FieldOffsets.push_back(Context.toBits(FieldOffset));
2075 /// \brief Places a bitfield at a bit offset.
2076 void placeFieldAtBitOffset(uint64_t FieldOffset) {
2077 FieldOffsets.push_back(FieldOffset);
2079 /// \brief Compute the set of virtual bases for which vtordisps are required.
2080 llvm::SmallPtrSet<const CXXRecordDecl *, 2>
2081 computeVtorDispSet(const CXXRecordDecl *RD);
2083 const ASTContext &Context;
2084 /// \brief The size of the record being laid out.
2086 /// \brief The current alignment of the record layout.
2087 CharUnits Alignment;
2088 /// \brief The collection of field offsets.
2089 SmallVector<uint64_t, 16> FieldOffsets;
2090 /// \brief The maximum allowed field alignment. This is set by #pragma pack.
2091 CharUnits MaxFieldAlignment;
2092 /// \brief Alignment does not occur for virtual bases unless something
2093 /// forces it to by explicitly using __declspec(align())
2094 bool AlignAfterVBases : 1;
2096 /// \brief True if the last field laid out was a bitfield and was not 0
2098 bool LastFieldIsNonZeroWidthBitfield : 1;
2099 /// \brief The size of the allocation of the currently active bitfield.
2100 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield
2102 CharUnits CurrentBitfieldSize;
2103 /// \brief The number of remaining bits in our last bitfield allocation.
2104 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield is
2106 unsigned RemainingBitsInField;
2108 /// \brief The data alignment of the record layout.
2110 /// \brief The alignment of the non-virtual portion of the record layout
2111 /// without the impact of the virtual pointers.
2112 /// Only used for C++ layouts.
2113 CharUnits BasesAndFieldsAlignment;
2114 /// \brief The alignment of the non-virtual portion of the record layout
2115 /// Only used for C++ layouts.
2116 CharUnits NonVirtualAlignment;
2117 /// \brief The additional alignment imposed by the virtual bases.
2118 CharUnits VirtualAlignment;
2119 /// \brief The primary base class (if one exists).
2120 const CXXRecordDecl *PrimaryBase;
2121 /// \brief The class we share our vb-pointer with.
2122 const CXXRecordDecl *SharedVBPtrBase;
2123 /// \brief True if the class has a vftable pointer that can be extended
2124 /// by this class or classes derived from it. Such a vfptr will always occur
2126 bool HasExtendableVFPtr : 1;
2127 /// \brief True if the class has a (not necessarily its own) vbtable pointer.
2129 /// \brief Offset to the virtual base table pointer (if one exists).
2130 CharUnits VBPtrOffset;
2131 /// \brief Base classes and their offsets in the record.
2132 BaseOffsetsMapTy Bases;
2133 /// \brief virtual base classes and their offsets in the record.
2134 ASTRecordLayout::VBaseOffsetsMapTy VBases;
2135 /// \brief The size of a pointer.
2136 CharUnits PointerSize;
2137 /// \brief The alignment of a pointer.
2138 CharUnits PointerAlignment;
2139 /// \brief Holds an empty base we haven't yet laid out.
2140 const CXXRecordDecl *LazyEmptyBase;
2141 /// \brief Lets us know if the last base we laid out was empty. Only used
2142 /// when adjusting the placement of a last zero-sized base in 64 bit mode.
2143 bool LastBaseWasEmpty;
2144 /// \brief Lets us know if we're in 64-bit mode
2146 /// \brief True if the last non-virtual base has a vbptr.
2147 bool LastNonVirtualBaseHasVBPtr;
2151 std::pair<CharUnits, CharUnits>
2152 MicrosoftRecordLayoutBuilder::getAdjustedFieldInfo(const FieldDecl *FD) {
2153 std::pair<CharUnits, CharUnits> FieldInfo =
2154 Context.getTypeInfoInChars(FD->getType());
2156 // If we're not on win32 and using ms_struct the field alignment will be wrong
2157 // for 64 bit types, so we fix that here.
2158 if (FD->getASTContext().getTargetInfo().getTriple().getOS() !=
2159 llvm::Triple::Win32) {
2160 QualType T = Context.getBaseElementType(FD->getType());
2161 if (const BuiltinType *BTy = T->getAs<BuiltinType>()) {
2162 CharUnits TypeSize = Context.getTypeSizeInChars(BTy);
2163 if (TypeSize > FieldInfo.second)
2164 FieldInfo.second = TypeSize;
2168 // Respect packed attribute.
2169 if (FD->hasAttr<PackedAttr>())
2170 FieldInfo.second = CharUnits::One();
2171 // Respect pack pragma.
2172 else if (!MaxFieldAlignment.isZero())
2173 FieldInfo.second = std::min(FieldInfo.second, MaxFieldAlignment);
2174 // Respect alignment attributes.
2175 if (unsigned fieldAlign = FD->getMaxAlignment()) {
2176 CharUnits FieldAlign = Context.toCharUnitsFromBits(fieldAlign);
2177 AlignAfterVBases = true;
2178 FieldInfo.second = std::max(FieldInfo.second, FieldAlign);
2183 void MicrosoftRecordLayoutBuilder::initializeLayout(const RecordDecl *RD) {
2184 IsUnion = RD->isUnion();
2185 Is64BitMode = Context.getTargetInfo().getPointerWidth(0) == 64;
2187 Size = CharUnits::Zero();
2188 Alignment = CharUnits::One();
2189 AlignAfterVBases = false;
2191 // Compute the maximum field alignment.
2192 MaxFieldAlignment = CharUnits::Zero();
2193 // Honor the default struct packing maximum alignment flag.
2194 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct)
2195 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
2196 // Honor the packing attribute.
2197 if (const MaxFieldAlignmentAttr *MFAA = RD->getAttr<MaxFieldAlignmentAttr>())
2198 MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment());
2199 // Packed attribute forces max field alignment to be 1.
2200 if (RD->hasAttr<PackedAttr>())
2201 MaxFieldAlignment = CharUnits::One();
2204 void MicrosoftRecordLayoutBuilder::layout(const RecordDecl *RD) {
2205 initializeLayout(RD);
2207 honorDeclspecAlign(RD);
2210 void MicrosoftRecordLayoutBuilder::cxxLayout(const CXXRecordDecl *RD) {
2211 initializeLayout(RD);
2212 initializeCXXLayout(RD);
2214 layoutNonVirtualBases(RD);
2218 NonVirtualAlignment = Alignment;
2219 layoutVirtualBases(RD);
2220 finalizeCXXLayout(RD);
2221 honorDeclspecAlign(RD);
2225 MicrosoftRecordLayoutBuilder::initializeCXXLayout(const CXXRecordDecl *RD) {
2226 // Calculate pointer size and alignment.
2228 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
2229 PointerAlignment = PointerSize;
2230 if (!MaxFieldAlignment.isZero())
2231 PointerAlignment = std::min(PointerAlignment, MaxFieldAlignment);
2233 // Initialize information about the bases.
2235 HasExtendableVFPtr = false;
2236 SharedVBPtrBase = 0;
2238 VirtualAlignment = CharUnits::One();
2239 AlignAfterVBases = Is64BitMode;
2241 // If the record has a dynamic base class, attempt to choose a primary base
2242 // class. It is the first (in direct base class order) non-virtual dynamic
2243 // base class, if one exists.
2244 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
2245 e = RD->bases_end();
2247 const CXXRecordDecl *BaseDecl =
2248 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
2249 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
2250 // Handle forced alignment.
2251 if (Layout.getAlignAfterVBases())
2252 AlignAfterVBases = true;
2253 // Handle virtual bases.
2254 if (i->isVirtual()) {
2255 VirtualAlignment = std::max(VirtualAlignment, Layout.getAlignment());
2259 // We located a primary base class!
2260 if (!PrimaryBase && Layout.hasExtendableVFPtr()) {
2261 PrimaryBase = BaseDecl;
2262 HasExtendableVFPtr = true;
2264 // We located a base to share a VBPtr with!
2265 if (!SharedVBPtrBase && Layout.hasVBPtr()) {
2266 SharedVBPtrBase = BaseDecl;
2269 updateAlignment(Layout.getAlignment());
2272 // Use LayoutFields to compute the alignment of the fields. The layout
2273 // is discarded. This is the simplest way to get all of the bit-field
2274 // behavior correct and is not actually very expensive.
2276 Size = CharUnits::Zero();
2277 BasesAndFieldsAlignment = Alignment;
2278 FieldOffsets.clear();
2281 void MicrosoftRecordLayoutBuilder::layoutVFPtr(const CXXRecordDecl *RD) {
2282 // If we have a primary base then our VFPtr was already laid out
2286 // Look at all of our methods to determine if we need a VFPtr. We need a
2287 // vfptr if we define a new virtual function.
2288 if (!HasExtendableVFPtr && RD->isDynamicClass())
2289 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2290 e = RD->method_end();
2291 !HasExtendableVFPtr && i != e; ++i)
2292 HasExtendableVFPtr = i->isVirtual() && i->size_overridden_methods() == 0;
2293 if (!HasExtendableVFPtr)
2296 // MSVC 32 (but not 64) potentially over-aligns the vf-table pointer by giving
2297 // it the max alignment of all the non-virtual data in the class. The
2298 // resulting layout is essentially { vftbl, { nvdata } }. This is completely
2299 // unnecessary, but we're not here to pass judgment.
2300 updateAlignment(PointerAlignment);
2302 Size = Size.RoundUpToAlignment(PointerAlignment) + PointerSize;
2304 Size = Size.RoundUpToAlignment(PointerAlignment) + Alignment;
2308 MicrosoftRecordLayoutBuilder::layoutNonVirtualBases(const CXXRecordDecl *RD) {
2310 LastBaseWasEmpty = false;
2311 LastNonVirtualBaseHasVBPtr = false;
2313 // Lay out the primary base first.
2315 layoutNonVirtualBase(PrimaryBase);
2317 // Iterate through the bases and lay out the non-virtual ones.
2318 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
2319 e = RD->bases_end();
2323 const CXXRecordDecl *BaseDecl =
2324 cast<CXXRecordDecl>(i->getType()->castAs<RecordType>()->getDecl());
2325 if (BaseDecl != PrimaryBase)
2326 layoutNonVirtualBase(BaseDecl);
2331 MicrosoftRecordLayoutBuilder::layoutNonVirtualBase(const CXXRecordDecl *RD) {
2332 const ASTRecordLayout *Layout = RD ? &Context.getASTRecordLayout(RD) : 0;
2334 // If we have a lazy empty base we haven't laid out yet, do that now.
2335 if (LazyEmptyBase) {
2336 const ASTRecordLayout &LazyLayout =
2337 Context.getASTRecordLayout(LazyEmptyBase);
2338 Size = Size.RoundUpToAlignment(LazyLayout.getAlignment());
2339 // If the last non-virtual base has a vbptr we add a byte of padding for no
2341 if (LastNonVirtualBaseHasVBPtr)
2343 Bases.insert(std::make_pair(LazyEmptyBase, Size));
2344 // Empty bases only consume space when followed by another empty base.
2345 if (RD && Layout->getNonVirtualSize().isZero()) {
2346 LastBaseWasEmpty = true;
2350 LastNonVirtualBaseHasVBPtr = false;
2353 // RD is null when flushing the final lazy base.
2357 if (Layout->getNonVirtualSize().isZero()) {
2362 // Insert the base here.
2363 CharUnits BaseOffset = Size.RoundUpToAlignment(Layout->getAlignment());
2364 Bases.insert(std::make_pair(RD, BaseOffset));
2365 Size = BaseOffset + Layout->getDataSize();
2366 // Note: we don't update alignment here because it was accounted
2367 // for during initalization.
2368 LastBaseWasEmpty = false;
2369 LastNonVirtualBaseHasVBPtr = Layout->hasVBPtr();
2372 void MicrosoftRecordLayoutBuilder::layoutVBPtr(const CXXRecordDecl *RD) {
2374 VBPtrOffset = CharUnits::fromQuantity(-1);
2375 else if (SharedVBPtrBase) {
2376 const ASTRecordLayout &Layout = Context.getASTRecordLayout(SharedVBPtrBase);
2377 VBPtrOffset = Bases[SharedVBPtrBase] + Layout.getVBPtrOffset();
2379 VBPtrOffset = Size.RoundUpToAlignment(PointerAlignment);
2380 CharUnits OldSize = Size;
2381 Size = VBPtrOffset + PointerSize;
2382 if (BasesAndFieldsAlignment <= PointerAlignment) {
2383 // Handle strange padding rules for the lazily placed base. I have no
2384 // explanation for why the last virtual base is padded in such an odd way.
2385 // Two things to note about this padding are that the rules are different
2386 // if the alignment of the bases+fields is <= to the alignemnt of a
2387 // pointer and that the rule in 64-bit mode behaves differently depending
2388 // on if the second to last base was also zero sized.
2389 Size += OldSize % BasesAndFieldsAlignment.getQuantity();
2392 Size += LastBaseWasEmpty ? CharUnits::One() : CharUnits::Zero();
2394 Size = OldSize + BasesAndFieldsAlignment;
2396 updateAlignment(PointerAlignment);
2399 // Flush the lazy empty base.
2400 layoutNonVirtualBase(0);
2403 void MicrosoftRecordLayoutBuilder::layoutFields(const RecordDecl *RD) {
2404 LastFieldIsNonZeroWidthBitfield = false;
2405 for (RecordDecl::field_iterator Field = RD->field_begin(),
2406 FieldEnd = RD->field_end();
2407 Field != FieldEnd; ++Field)
2408 layoutField(*Field);
2409 Size = Size.RoundUpToAlignment(Alignment);
2412 void MicrosoftRecordLayoutBuilder::layoutField(const FieldDecl *FD) {
2413 if (FD->isBitField()) {
2417 LastFieldIsNonZeroWidthBitfield = false;
2419 std::pair<CharUnits, CharUnits> FieldInfo = getAdjustedFieldInfo(FD);
2420 CharUnits FieldSize = FieldInfo.first;
2421 CharUnits FieldAlign = FieldInfo.second;
2423 updateAlignment(FieldAlign);
2426 Size = std::max(Size, FieldSize);
2428 // Round up the current record size to the field's alignment boundary.
2429 CharUnits FieldOffset = Size.RoundUpToAlignment(FieldAlign);
2430 placeFieldAtOffset(FieldOffset);
2431 Size = FieldOffset + FieldSize;
2435 void MicrosoftRecordLayoutBuilder::layoutBitField(const FieldDecl *FD) {
2436 unsigned Width = FD->getBitWidthValue(Context);
2438 layoutZeroWidthBitField(FD);
2442 std::pair<CharUnits, CharUnits> FieldInfo = getAdjustedFieldInfo(FD);
2443 CharUnits FieldSize = FieldInfo.first;
2444 CharUnits FieldAlign = FieldInfo.second;
2446 // Clamp the bitfield to a containable size for the sake of being able
2447 // to lay them out. Sema will throw an error.
2448 if (Width > Context.toBits(FieldSize))
2449 Width = Context.toBits(FieldSize);
2451 // Check to see if this bitfield fits into an existing allocation. Note:
2452 // MSVC refuses to pack bitfields of formal types with different sizes
2453 // into the same allocation.
2454 if (!IsUnion && LastFieldIsNonZeroWidthBitfield &&
2455 CurrentBitfieldSize == FieldSize && Width <= RemainingBitsInField) {
2456 placeFieldAtBitOffset(Context.toBits(Size) - RemainingBitsInField);
2457 RemainingBitsInField -= Width;
2461 LastFieldIsNonZeroWidthBitfield = true;
2462 CurrentBitfieldSize = FieldSize;
2465 Size = std::max(Size, FieldSize);
2466 // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
2468 // Allocate a new block of memory and place the bitfield in it.
2469 CharUnits FieldOffset = Size.RoundUpToAlignment(FieldAlign);
2470 placeFieldAtOffset(FieldOffset);
2471 Size = FieldOffset + FieldSize;
2472 updateAlignment(FieldAlign);
2473 RemainingBitsInField = Context.toBits(FieldSize) - Width;
2478 MicrosoftRecordLayoutBuilder::layoutZeroWidthBitField(const FieldDecl *FD) {
2479 // Zero-width bitfields are ignored unless they follow a non-zero-width
2481 std::pair<CharUnits, CharUnits> FieldInfo = getAdjustedFieldInfo(FD);
2482 CharUnits FieldSize = FieldInfo.first;
2483 CharUnits FieldAlign = FieldInfo.second;
2485 if (!LastFieldIsNonZeroWidthBitfield) {
2486 placeFieldAtOffset(IsUnion ? CharUnits::Zero() : Size);
2487 // TODO: Add a Sema warning that MS ignores alignment for zero
2488 // sized bitfields that occur after zero-size bitfields or non bitfields.
2492 LastFieldIsNonZeroWidthBitfield = false;
2495 Size = std::max(Size, FieldSize);
2497 // Round up the current record size to the field's alignment boundary.
2498 CharUnits FieldOffset = Size.RoundUpToAlignment(FieldAlign);
2499 placeFieldAtOffset(FieldOffset);
2501 updateAlignment(FieldAlign);
2505 void MicrosoftRecordLayoutBuilder::layoutVirtualBases(const CXXRecordDecl *RD) {
2509 updateAlignment(VirtualAlignment);
2511 // Zero-sized v-bases obey the alignment attribute so apply it here. The
2512 // alignment attribute is normally accounted for in FinalizeLayout.
2513 if (unsigned MaxAlign = RD->getMaxAlignment())
2514 updateAlignment(Context.toCharUnitsFromBits(MaxAlign));
2516 llvm::SmallPtrSet<const CXXRecordDecl *, 2> HasVtordisp =
2517 computeVtorDispSet(RD);
2519 // If the last field we laid out was a non-zero length bitfield then add some
2520 // extra padding for no obvious reason.
2521 if (LastFieldIsNonZeroWidthBitfield)
2522 Size += CurrentBitfieldSize;
2524 // Iterate through the virtual bases and lay them out.
2525 for (CXXRecordDecl::base_class_const_iterator i = RD->vbases_begin(),
2526 e = RD->vbases_end();
2528 const CXXRecordDecl *BaseDecl =
2529 cast<CXXRecordDecl>(i->getType()->castAs<RecordType>()->getDecl());
2530 layoutVirtualBase(BaseDecl, HasVtordisp.count(BaseDecl));
2534 void MicrosoftRecordLayoutBuilder::layoutVirtualBase(const CXXRecordDecl *RD,
2536 if (LazyEmptyBase) {
2537 const ASTRecordLayout &LazyLayout =
2538 Context.getASTRecordLayout(LazyEmptyBase);
2539 Size = Size.RoundUpToAlignment(LazyLayout.getAlignment());
2541 std::make_pair(LazyEmptyBase, ASTRecordLayout::VBaseInfo(Size, false)));
2542 // Empty bases only consume space when followed by another empty base.
2543 // The space consumed is in an Alignment sized/aligned block and the v-base
2544 // is placed at its alignment offset into the chunk, unless its alignment
2545 // is less than 4 bytes, at which it is placed at 4 byte offset in the
2546 // chunk. We have no idea why.
2547 if (RD && Context.getASTRecordLayout(RD).getNonVirtualSize().isZero())
2548 Size = Size.RoundUpToAlignment(Alignment) + CharUnits::fromQuantity(4);
2552 // RD is null when flushing the final lazy virtual base.
2556 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
2557 if (Layout.getNonVirtualSize().isZero() && !HasVtordisp) {
2562 CharUnits BaseNVSize = Layout.getNonVirtualSize();
2563 CharUnits BaseAlign = Layout.getAlignment();
2565 // vtordisps are always 4 bytes (even in 64-bit mode)
2567 Size = Size.RoundUpToAlignment(Alignment) + CharUnits::fromQuantity(4);
2568 Size = Size.RoundUpToAlignment(BaseAlign);
2570 // Insert the base here.
2571 CharUnits BaseOffset = Size.RoundUpToAlignment(BaseAlign);
2573 std::make_pair(RD, ASTRecordLayout::VBaseInfo(BaseOffset, HasVtordisp)));
2574 Size = BaseOffset + BaseNVSize;
2575 // Note: we don't update alignment here because it was accounted for in
2576 // InitializeLayout.
2579 void MicrosoftRecordLayoutBuilder::finalizeCXXLayout(const CXXRecordDecl *RD) {
2580 // Flush the lazy virtual base.
2581 layoutVirtualBase(0, false);
2583 if (RD->vbases_begin() == RD->vbases_end() || AlignAfterVBases)
2584 Size = Size.RoundUpToAlignment(Alignment);
2590 void MicrosoftRecordLayoutBuilder::honorDeclspecAlign(const RecordDecl *RD) {
2591 if (unsigned MaxAlign = RD->getMaxAlignment()) {
2592 AlignAfterVBases = true;
2593 updateAlignment(Context.toCharUnitsFromBits(MaxAlign));
2594 Size = Size.RoundUpToAlignment(Alignment);
2599 RequiresVtordisp(const llvm::SmallPtrSet<const CXXRecordDecl *, 2> &HasVtordisp,
2600 const CXXRecordDecl *RD) {
2601 if (HasVtordisp.count(RD))
2603 // If any of a virtual bases non-virtual bases (recursively) requires a
2604 // vtordisp than so does this virtual base.
2605 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
2606 e = RD->bases_end();
2608 if (!i->isVirtual() &&
2611 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl())))
2616 llvm::SmallPtrSet<const CXXRecordDecl *, 2>
2617 MicrosoftRecordLayoutBuilder::computeVtorDispSet(const CXXRecordDecl *RD) {
2618 llvm::SmallPtrSet<const CXXRecordDecl *, 2> HasVtordisp;
2620 // If any of our bases need a vtordisp for this type, so do we. Check our
2621 // direct bases for vtordisp requirements.
2622 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
2623 e = RD->bases_end();
2625 const CXXRecordDecl *BaseDecl =
2626 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
2627 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
2628 for (ASTRecordLayout::VBaseOffsetsMapTy::const_iterator
2629 bi = Layout.getVBaseOffsetsMap().begin(),
2630 be = Layout.getVBaseOffsetsMap().end();
2632 if (bi->second.hasVtorDisp())
2633 HasVtordisp.insert(bi->first);
2636 // If we define a constructor or destructor and override a function that is
2637 // defined in a virtual base's vtable, that virtual bases need a vtordisp.
2638 // Here we collect a list of classes with vtables for which our virtual bases
2639 // actually live. The virtual bases with this property will require
2640 // vtordisps. In addition, virtual bases that contain non-virtual bases that
2641 // define functions we override also require vtordisps, this case is checked
2642 // explicitly below.
2643 if (RD->hasUserDeclaredConstructor() || RD->hasUserDeclaredDestructor()) {
2644 llvm::SmallPtrSet<const CXXMethodDecl *, 8> Work;
2645 // Seed the working set with our non-destructor virtual methods.
2646 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2647 e = RD->method_end();
2649 if ((*i)->isVirtual() && !isa<CXXDestructorDecl>(*i))
2651 while (!Work.empty()) {
2652 const CXXMethodDecl *MD = *Work.begin();
2653 CXXMethodDecl::method_iterator i = MD->begin_overridden_methods(),
2654 e = MD->end_overridden_methods();
2656 // If a virtual method has no-overrides it lives in its parent's vtable.
2657 HasVtordisp.insert(MD->getParent());
2660 // We've finished processing this element, remove it from the working set.
2665 // Re-check all of our vbases for vtordisp requirements (in case their
2666 // non-virtual bases have vtordisp requirements).
2667 for (CXXRecordDecl::base_class_const_iterator i = RD->vbases_begin(),
2668 e = RD->vbases_end();
2670 const CXXRecordDecl *BaseDecl = i->getType()->getAsCXXRecordDecl();
2671 if (!HasVtordisp.count(BaseDecl) && RequiresVtordisp(HasVtordisp, BaseDecl))
2672 HasVtordisp.insert(BaseDecl);
2678 /// \brief Get or compute information about the layout of the specified record
2679 /// (struct/union/class), which indicates its size and field position
2681 const ASTRecordLayout *
2682 ASTContext::BuildMicrosoftASTRecordLayout(const RecordDecl *D) const {
2683 MicrosoftRecordLayoutBuilder Builder(*this);
2684 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2685 Builder.cxxLayout(RD);
2686 return new (*this) ASTRecordLayout(
2687 *this, Builder.Size, Builder.Alignment,
2688 Builder.HasExtendableVFPtr && !Builder.PrimaryBase,
2689 Builder.HasExtendableVFPtr,
2690 Builder.VBPtrOffset, Builder.DataSize, Builder.FieldOffsets.data(),
2691 Builder.FieldOffsets.size(), Builder.DataSize,
2692 Builder.NonVirtualAlignment, CharUnits::Zero(), Builder.PrimaryBase,
2693 false, Builder.SharedVBPtrBase, Builder.AlignAfterVBases, Builder.Bases,
2697 return new (*this) ASTRecordLayout(
2698 *this, Builder.Size, Builder.Alignment, Builder.Size,
2699 Builder.FieldOffsets.data(), Builder.FieldOffsets.size());
2703 /// getASTRecordLayout - Get or compute information about the layout of the
2704 /// specified record (struct/union/class), which indicates its size and field
2705 /// position information.
2706 const ASTRecordLayout &
2707 ASTContext::getASTRecordLayout(const RecordDecl *D) const {
2708 // These asserts test different things. A record has a definition
2709 // as soon as we begin to parse the definition. That definition is
2710 // not a complete definition (which is what isDefinition() tests)
2711 // until we *finish* parsing the definition.
2713 if (D->hasExternalLexicalStorage() && !D->getDefinition())
2714 getExternalSource()->CompleteType(const_cast<RecordDecl*>(D));
2716 D = D->getDefinition();
2717 assert(D && "Cannot get layout of forward declarations!");
2718 assert(!D->isInvalidDecl() && "Cannot get layout of invalid decl!");
2719 assert(D->isCompleteDefinition() && "Cannot layout type before complete!");
2721 // Look up this layout, if already laid out, return what we have.
2722 // Note that we can't save a reference to the entry because this function
2724 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
2725 if (Entry) return *Entry;
2727 const ASTRecordLayout *NewEntry = 0;
2729 if (isMsLayout(D) && !D->getASTContext().getExternalSource()) {
2730 NewEntry = BuildMicrosoftASTRecordLayout(D);
2731 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2732 EmptySubobjectMap EmptySubobjects(*this, RD);
2733 RecordLayoutBuilder Builder(*this, &EmptySubobjects);
2736 // In certain situations, we are allowed to lay out objects in the
2737 // tail-padding of base classes. This is ABI-dependent.
2738 // FIXME: this should be stored in the record layout.
2739 bool skipTailPadding =
2740 mustSkipTailPadding(getTargetInfo().getCXXABI(), cast<CXXRecordDecl>(D));
2742 // FIXME: This should be done in FinalizeLayout.
2743 CharUnits DataSize =
2744 skipTailPadding ? Builder.getSize() : Builder.getDataSize();
2745 CharUnits NonVirtualSize =
2746 skipTailPadding ? DataSize : Builder.NonVirtualSize;
2748 new (*this) ASTRecordLayout(*this, Builder.getSize(),
2750 Builder.HasOwnVFPtr,
2751 RD->isDynamicClass(),
2752 CharUnits::fromQuantity(-1),
2754 Builder.FieldOffsets.data(),
2755 Builder.FieldOffsets.size(),
2757 Builder.NonVirtualAlignment,
2758 EmptySubobjects.SizeOfLargestEmptySubobject,
2759 Builder.PrimaryBase,
2760 Builder.PrimaryBaseIsVirtual,
2762 Builder.Bases, Builder.VBases);
2764 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
2768 new (*this) ASTRecordLayout(*this, Builder.getSize(),
2771 Builder.FieldOffsets.data(),
2772 Builder.FieldOffsets.size());
2775 ASTRecordLayouts[D] = NewEntry;
2777 if (getLangOpts().DumpRecordLayouts) {
2778 llvm::outs() << "\n*** Dumping AST Record Layout\n";
2779 DumpRecordLayout(D, llvm::outs(), getLangOpts().DumpRecordLayoutsSimple);
2785 const CXXMethodDecl *ASTContext::getCurrentKeyFunction(const CXXRecordDecl *RD) {
2786 if (!getTargetInfo().getCXXABI().hasKeyFunctions())
2789 assert(RD->getDefinition() && "Cannot get key function for forward decl!");
2790 RD = cast<CXXRecordDecl>(RD->getDefinition());
2792 LazyDeclPtr &Entry = KeyFunctions[RD];
2794 Entry = const_cast<CXXMethodDecl*>(computeKeyFunction(*this, RD));
2796 return cast_or_null<CXXMethodDecl>(Entry.get(getExternalSource()));
2799 void ASTContext::setNonKeyFunction(const CXXMethodDecl *Method) {
2800 assert(Method == Method->getFirstDecl() &&
2801 "not working with method declaration from class definition");
2803 // Look up the cache entry. Since we're working with the first
2804 // declaration, its parent must be the class definition, which is
2805 // the correct key for the KeyFunctions hash.
2806 llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr>::iterator
2807 I = KeyFunctions.find(Method->getParent());
2809 // If it's not cached, there's nothing to do.
2810 if (I == KeyFunctions.end()) return;
2812 // If it is cached, check whether it's the target method, and if so,
2813 // remove it from the cache.
2814 if (I->second.get(getExternalSource()) == Method) {
2815 // FIXME: remember that we did this for module / chained PCH state?
2816 KeyFunctions.erase(I);
2820 static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) {
2821 const ASTRecordLayout &Layout = C.getASTRecordLayout(FD->getParent());
2822 return Layout.getFieldOffset(FD->getFieldIndex());
2825 uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const {
2826 uint64_t OffsetInBits;
2827 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
2828 OffsetInBits = ::getFieldOffset(*this, FD);
2830 const IndirectFieldDecl *IFD = cast<IndirectFieldDecl>(VD);
2833 for (IndirectFieldDecl::chain_iterator CI = IFD->chain_begin(),
2834 CE = IFD->chain_end();
2836 OffsetInBits += ::getFieldOffset(*this, cast<FieldDecl>(*CI));
2839 return OffsetInBits;
2842 /// getObjCLayout - Get or compute information about the layout of the
2843 /// given interface.
2845 /// \param Impl - If given, also include the layout of the interface's
2846 /// implementation. This may differ by including synthesized ivars.
2847 const ASTRecordLayout &
2848 ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
2849 const ObjCImplementationDecl *Impl) const {
2850 // Retrieve the definition
2851 if (D->hasExternalLexicalStorage() && !D->getDefinition())
2852 getExternalSource()->CompleteType(const_cast<ObjCInterfaceDecl*>(D));
2853 D = D->getDefinition();
2854 assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!");
2856 // Look up this layout, if already laid out, return what we have.
2857 const ObjCContainerDecl *Key =
2858 Impl ? (const ObjCContainerDecl*) Impl : (const ObjCContainerDecl*) D;
2859 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
2862 // Add in synthesized ivar count if laying out an implementation.
2864 unsigned SynthCount = CountNonClassIvars(D);
2865 // If there aren't any sythesized ivars then reuse the interface
2866 // entry. Note we can't cache this because we simply free all
2867 // entries later; however we shouldn't look up implementations
2869 if (SynthCount == 0)
2870 return getObjCLayout(D, 0);
2873 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
2876 const ASTRecordLayout *NewEntry =
2877 new (*this) ASTRecordLayout(*this, Builder.getSize(),
2879 Builder.getDataSize(),
2880 Builder.FieldOffsets.data(),
2881 Builder.FieldOffsets.size());
2883 ObjCLayouts[Key] = NewEntry;
2888 static void PrintOffset(raw_ostream &OS,
2889 CharUnits Offset, unsigned IndentLevel) {
2890 OS << llvm::format("%4" PRId64 " | ", (int64_t)Offset.getQuantity());
2891 OS.indent(IndentLevel * 2);
2894 static void PrintIndentNoOffset(raw_ostream &OS, unsigned IndentLevel) {
2896 OS.indent(IndentLevel * 2);
2899 static void DumpCXXRecordLayout(raw_ostream &OS,
2900 const CXXRecordDecl *RD, const ASTContext &C,
2902 unsigned IndentLevel,
2903 const char* Description,
2904 bool IncludeVirtualBases) {
2905 const ASTRecordLayout &Layout = C.getASTRecordLayout(RD);
2907 PrintOffset(OS, Offset, IndentLevel);
2908 OS << C.getTypeDeclType(const_cast<CXXRecordDecl *>(RD)).getAsString();
2910 OS << ' ' << Description;
2917 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
2918 bool HasOwnVFPtr = Layout.hasOwnVFPtr();
2919 bool HasOwnVBPtr = Layout.hasOwnVBPtr();
2922 if (RD->isDynamicClass() && !PrimaryBase && !isMsLayout(RD)) {
2923 PrintOffset(OS, Offset, IndentLevel);
2924 OS << '(' << *RD << " vtable pointer)\n";
2925 } else if (HasOwnVFPtr) {
2926 PrintOffset(OS, Offset, IndentLevel);
2927 // vfptr (for Microsoft C++ ABI)
2928 OS << '(' << *RD << " vftable pointer)\n";
2931 // Dump (non-virtual) bases
2932 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
2933 E = RD->bases_end(); I != E; ++I) {
2934 assert(!I->getType()->isDependentType() &&
2935 "Cannot layout class with dependent bases.");
2939 const CXXRecordDecl *Base =
2940 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
2942 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
2944 DumpCXXRecordLayout(OS, Base, C, BaseOffset, IndentLevel,
2945 Base == PrimaryBase ? "(primary base)" : "(base)",
2946 /*IncludeVirtualBases=*/false);
2949 // vbptr (for Microsoft C++ ABI)
2951 PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel);
2952 OS << '(' << *RD << " vbtable pointer)\n";
2956 uint64_t FieldNo = 0;
2957 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2958 E = RD->field_end(); I != E; ++I, ++FieldNo) {
2959 const FieldDecl &Field = **I;
2960 CharUnits FieldOffset = Offset +
2961 C.toCharUnitsFromBits(Layout.getFieldOffset(FieldNo));
2963 if (const RecordType *RT = Field.getType()->getAs<RecordType>()) {
2964 if (const CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2965 DumpCXXRecordLayout(OS, D, C, FieldOffset, IndentLevel,
2966 Field.getName().data(),
2967 /*IncludeVirtualBases=*/true);
2972 PrintOffset(OS, FieldOffset, IndentLevel);
2973 OS << Field.getType().getAsString() << ' ' << Field << '\n';
2976 if (!IncludeVirtualBases)
2979 // Dump virtual bases.
2980 const ASTRecordLayout::VBaseOffsetsMapTy &vtordisps =
2981 Layout.getVBaseOffsetsMap();
2982 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
2983 E = RD->vbases_end(); I != E; ++I) {
2984 assert(I->isVirtual() && "Found non-virtual class!");
2985 const CXXRecordDecl *VBase =
2986 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
2988 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
2990 if (vtordisps.find(VBase)->second.hasVtorDisp()) {
2991 PrintOffset(OS, VBaseOffset - CharUnits::fromQuantity(4), IndentLevel);
2992 OS << "(vtordisp for vbase " << *VBase << ")\n";
2995 DumpCXXRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel,
2996 VBase == PrimaryBase ?
2997 "(primary virtual base)" : "(virtual base)",
2998 /*IncludeVirtualBases=*/false);
3001 PrintIndentNoOffset(OS, IndentLevel - 1);
3002 OS << "[sizeof=" << Layout.getSize().getQuantity();
3003 if (!isMsLayout(RD))
3004 OS << ", dsize=" << Layout.getDataSize().getQuantity();
3005 OS << ", align=" << Layout.getAlignment().getQuantity() << '\n';
3007 PrintIndentNoOffset(OS, IndentLevel - 1);
3008 OS << " nvsize=" << Layout.getNonVirtualSize().getQuantity();
3009 OS << ", nvalign=" << Layout.getNonVirtualAlign().getQuantity() << "]\n";
3013 void ASTContext::DumpRecordLayout(const RecordDecl *RD,
3015 bool Simple) const {
3016 const ASTRecordLayout &Info = getASTRecordLayout(RD);
3018 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
3020 return DumpCXXRecordLayout(OS, CXXRD, *this, CharUnits(), 0, 0,
3021 /*IncludeVirtualBases=*/true);
3023 OS << "Type: " << getTypeDeclType(RD).getAsString() << "\n";
3029 OS << "<ASTRecordLayout\n";
3030 OS << " Size:" << toBits(Info.getSize()) << "\n";
3031 if (!isMsLayout(RD))
3032 OS << " DataSize:" << toBits(Info.getDataSize()) << "\n";
3033 OS << " Alignment:" << toBits(Info.getAlignment()) << "\n";
3034 OS << " FieldOffsets: [";
3035 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) {
3037 OS << Info.getFieldOffset(i);