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 llvm::TinyPtrVector
<const CXXRecordDecl
*> 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 (const CXXBaseSpecifier
&Base
: Class
->bases()) {
144 const CXXRecordDecl
*BaseDecl
= Base
.getType()->getAsCXXRecordDecl();
147 const ASTRecordLayout
&Layout
= Context
.getASTRecordLayout(BaseDecl
);
148 if (BaseDecl
->isEmpty()) {
149 // If the class decl is empty, get its size.
150 EmptySize
= Layout
.getSize();
152 // Otherwise, we get the largest empty subobject for the decl.
153 EmptySize
= Layout
.getSizeOfLargestEmptySubobject();
156 if (EmptySize
> SizeOfLargestEmptySubobject
)
157 SizeOfLargestEmptySubobject
= EmptySize
;
161 for (const FieldDecl
*FD
: Class
->fields()) {
162 const RecordType
*RT
=
163 Context
.getBaseElementType(FD
->getType())->getAs
<RecordType
>();
165 // We only care about record types.
170 const CXXRecordDecl
*MemberDecl
= RT
->getAsCXXRecordDecl();
171 const ASTRecordLayout
&Layout
= Context
.getASTRecordLayout(MemberDecl
);
172 if (MemberDecl
->isEmpty()) {
173 // If the class decl is empty, get its size.
174 EmptySize
= Layout
.getSize();
176 // Otherwise, we get the largest empty subobject for the decl.
177 EmptySize
= Layout
.getSizeOfLargestEmptySubobject();
180 if (EmptySize
> SizeOfLargestEmptySubobject
)
181 SizeOfLargestEmptySubobject
= EmptySize
;
186 EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl
*RD
,
187 CharUnits Offset
) const {
188 // We only need to check empty bases.
192 EmptyClassOffsetsMapTy::const_iterator I
= EmptyClassOffsets
.find(Offset
);
193 if (I
== EmptyClassOffsets
.end())
196 const ClassVectorTy
&Classes
= I
->second
;
197 if (std::find(Classes
.begin(), Classes
.end(), RD
) == Classes
.end())
200 // There is already an empty class of the same type at this offset.
204 void EmptySubobjectMap::AddSubobjectAtOffset(const CXXRecordDecl
*RD
,
206 // We only care about empty bases.
210 // If we have empty structures inside a union, we can assign both
211 // the same offset. Just avoid pushing them twice in the list.
212 ClassVectorTy
&Classes
= EmptyClassOffsets
[Offset
];
213 if (std::find(Classes
.begin(), Classes
.end(), RD
) != Classes
.end())
216 Classes
.push_back(RD
);
218 // Update the empty class offset.
219 if (Offset
> MaxEmptyClassOffset
)
220 MaxEmptyClassOffset
= Offset
;
224 EmptySubobjectMap::CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo
*Info
,
226 // We don't have to keep looking past the maximum offset that's known to
227 // contain an empty class.
228 if (!AnyEmptySubobjectsBeyondOffset(Offset
))
231 if (!CanPlaceSubobjectAtOffset(Info
->Class
, Offset
))
234 // Traverse all non-virtual bases.
235 const ASTRecordLayout
&Layout
= Context
.getASTRecordLayout(Info
->Class
);
236 for (const BaseSubobjectInfo
*Base
: Info
->Bases
) {
240 CharUnits BaseOffset
= Offset
+ Layout
.getBaseClassOffset(Base
->Class
);
242 if (!CanPlaceBaseSubobjectAtOffset(Base
, BaseOffset
))
246 if (Info
->PrimaryVirtualBaseInfo
) {
247 BaseSubobjectInfo
*PrimaryVirtualBaseInfo
= Info
->PrimaryVirtualBaseInfo
;
249 if (Info
== PrimaryVirtualBaseInfo
->Derived
) {
250 if (!CanPlaceBaseSubobjectAtOffset(PrimaryVirtualBaseInfo
, Offset
))
255 // Traverse all member variables.
256 unsigned FieldNo
= 0;
257 for (CXXRecordDecl::field_iterator I
= Info
->Class
->field_begin(),
258 E
= Info
->Class
->field_end(); I
!= E
; ++I
, ++FieldNo
) {
262 CharUnits FieldOffset
= Offset
+ getFieldOffset(Layout
, FieldNo
);
263 if (!CanPlaceFieldSubobjectAtOffset(*I
, FieldOffset
))
270 void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo
*Info
,
272 bool PlacingEmptyBase
) {
273 if (!PlacingEmptyBase
&& Offset
>= SizeOfLargestEmptySubobject
) {
274 // We know that the only empty subobjects that can conflict with empty
275 // subobject of non-empty bases, are empty bases that can be placed at
276 // offset zero. Because of this, we only need to keep track of empty base
277 // subobjects with offsets less than the size of the largest empty
278 // subobject for our class.
282 AddSubobjectAtOffset(Info
->Class
, Offset
);
284 // Traverse all non-virtual bases.
285 const ASTRecordLayout
&Layout
= Context
.getASTRecordLayout(Info
->Class
);
286 for (const BaseSubobjectInfo
*Base
: Info
->Bases
) {
290 CharUnits BaseOffset
= Offset
+ Layout
.getBaseClassOffset(Base
->Class
);
291 UpdateEmptyBaseSubobjects(Base
, BaseOffset
, PlacingEmptyBase
);
294 if (Info
->PrimaryVirtualBaseInfo
) {
295 BaseSubobjectInfo
*PrimaryVirtualBaseInfo
= Info
->PrimaryVirtualBaseInfo
;
297 if (Info
== PrimaryVirtualBaseInfo
->Derived
)
298 UpdateEmptyBaseSubobjects(PrimaryVirtualBaseInfo
, Offset
,
302 // Traverse all member variables.
303 unsigned FieldNo
= 0;
304 for (CXXRecordDecl::field_iterator I
= Info
->Class
->field_begin(),
305 E
= Info
->Class
->field_end(); I
!= E
; ++I
, ++FieldNo
) {
309 CharUnits FieldOffset
= Offset
+ getFieldOffset(Layout
, FieldNo
);
310 UpdateEmptyFieldSubobjects(*I
, FieldOffset
);
314 bool EmptySubobjectMap::CanPlaceBaseAtOffset(const BaseSubobjectInfo
*Info
,
316 // If we know this class doesn't have any empty subobjects we don't need to
318 if (SizeOfLargestEmptySubobject
.isZero())
321 if (!CanPlaceBaseSubobjectAtOffset(Info
, Offset
))
324 // We are able to place the base at this offset. Make sure to update the
325 // empty base subobject map.
326 UpdateEmptyBaseSubobjects(Info
, Offset
, Info
->Class
->isEmpty());
331 EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl
*RD
,
332 const CXXRecordDecl
*Class
,
333 CharUnits Offset
) const {
334 // We don't have to keep looking past the maximum offset that's known to
335 // contain an empty class.
336 if (!AnyEmptySubobjectsBeyondOffset(Offset
))
339 if (!CanPlaceSubobjectAtOffset(RD
, Offset
))
342 const ASTRecordLayout
&Layout
= Context
.getASTRecordLayout(RD
);
344 // Traverse all non-virtual bases.
345 for (const CXXBaseSpecifier
&Base
: RD
->bases()) {
346 if (Base
.isVirtual())
349 const CXXRecordDecl
*BaseDecl
= Base
.getType()->getAsCXXRecordDecl();
351 CharUnits BaseOffset
= Offset
+ Layout
.getBaseClassOffset(BaseDecl
);
352 if (!CanPlaceFieldSubobjectAtOffset(BaseDecl
, Class
, BaseOffset
))
357 // This is the most derived class, traverse virtual bases as well.
358 for (const CXXBaseSpecifier
&Base
: RD
->vbases()) {
359 const CXXRecordDecl
*VBaseDecl
= Base
.getType()->getAsCXXRecordDecl();
361 CharUnits VBaseOffset
= Offset
+ Layout
.getVBaseClassOffset(VBaseDecl
);
362 if (!CanPlaceFieldSubobjectAtOffset(VBaseDecl
, Class
, VBaseOffset
))
367 // Traverse all member variables.
368 unsigned FieldNo
= 0;
369 for (CXXRecordDecl::field_iterator I
= RD
->field_begin(), E
= RD
->field_end();
370 I
!= E
; ++I
, ++FieldNo
) {
374 CharUnits FieldOffset
= Offset
+ getFieldOffset(Layout
, FieldNo
);
376 if (!CanPlaceFieldSubobjectAtOffset(*I
, FieldOffset
))
384 EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl
*FD
,
385 CharUnits Offset
) const {
386 // We don't have to keep looking past the maximum offset that's known to
387 // contain an empty class.
388 if (!AnyEmptySubobjectsBeyondOffset(Offset
))
391 QualType T
= FD
->getType();
392 if (const CXXRecordDecl
*RD
= T
->getAsCXXRecordDecl())
393 return CanPlaceFieldSubobjectAtOffset(RD
, RD
, Offset
);
395 // If we have an array type we need to look at every element.
396 if (const ConstantArrayType
*AT
= Context
.getAsConstantArrayType(T
)) {
397 QualType ElemTy
= Context
.getBaseElementType(AT
);
398 const RecordType
*RT
= ElemTy
->getAs
<RecordType
>();
402 const CXXRecordDecl
*RD
= RT
->getAsCXXRecordDecl();
403 const ASTRecordLayout
&Layout
= Context
.getASTRecordLayout(RD
);
405 uint64_t NumElements
= Context
.getConstantArrayElementCount(AT
);
406 CharUnits ElementOffset
= Offset
;
407 for (uint64_t I
= 0; I
!= NumElements
; ++I
) {
408 // We don't have to keep looking past the maximum offset that's known to
409 // contain an empty class.
410 if (!AnyEmptySubobjectsBeyondOffset(ElementOffset
))
413 if (!CanPlaceFieldSubobjectAtOffset(RD
, RD
, ElementOffset
))
416 ElementOffset
+= Layout
.getSize();
424 EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl
*FD
,
426 if (!CanPlaceFieldSubobjectAtOffset(FD
, Offset
))
429 // We are able to place the member variable at this offset.
430 // Make sure to update the empty base subobject map.
431 UpdateEmptyFieldSubobjects(FD
, Offset
);
435 void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl
*RD
,
436 const CXXRecordDecl
*Class
,
438 // We know that the only empty subobjects that can conflict with empty
439 // field subobjects are subobjects of empty bases that can be placed at offset
440 // zero. Because of this, we only need to keep track of empty field
441 // subobjects with offsets less than the size of the largest empty
442 // subobject for our class.
443 if (Offset
>= SizeOfLargestEmptySubobject
)
446 AddSubobjectAtOffset(RD
, Offset
);
448 const ASTRecordLayout
&Layout
= Context
.getASTRecordLayout(RD
);
450 // Traverse all non-virtual bases.
451 for (const CXXBaseSpecifier
&Base
: RD
->bases()) {
452 if (Base
.isVirtual())
455 const CXXRecordDecl
*BaseDecl
= Base
.getType()->getAsCXXRecordDecl();
457 CharUnits BaseOffset
= Offset
+ Layout
.getBaseClassOffset(BaseDecl
);
458 UpdateEmptyFieldSubobjects(BaseDecl
, Class
, BaseOffset
);
462 // This is the most derived class, traverse virtual bases as well.
463 for (const CXXBaseSpecifier
&Base
: RD
->vbases()) {
464 const CXXRecordDecl
*VBaseDecl
= Base
.getType()->getAsCXXRecordDecl();
466 CharUnits VBaseOffset
= Offset
+ Layout
.getVBaseClassOffset(VBaseDecl
);
467 UpdateEmptyFieldSubobjects(VBaseDecl
, Class
, VBaseOffset
);
471 // Traverse all member variables.
472 unsigned FieldNo
= 0;
473 for (CXXRecordDecl::field_iterator I
= RD
->field_begin(), E
= RD
->field_end();
474 I
!= E
; ++I
, ++FieldNo
) {
478 CharUnits FieldOffset
= Offset
+ getFieldOffset(Layout
, FieldNo
);
480 UpdateEmptyFieldSubobjects(*I
, FieldOffset
);
484 void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const FieldDecl
*FD
,
486 QualType T
= FD
->getType();
487 if (const CXXRecordDecl
*RD
= T
->getAsCXXRecordDecl()) {
488 UpdateEmptyFieldSubobjects(RD
, RD
, Offset
);
492 // If we have an array type we need to update every element.
493 if (const ConstantArrayType
*AT
= Context
.getAsConstantArrayType(T
)) {
494 QualType ElemTy
= Context
.getBaseElementType(AT
);
495 const RecordType
*RT
= ElemTy
->getAs
<RecordType
>();
499 const CXXRecordDecl
*RD
= RT
->getAsCXXRecordDecl();
500 const ASTRecordLayout
&Layout
= Context
.getASTRecordLayout(RD
);
502 uint64_t NumElements
= Context
.getConstantArrayElementCount(AT
);
503 CharUnits ElementOffset
= Offset
;
505 for (uint64_t I
= 0; I
!= NumElements
; ++I
) {
506 // We know that the only empty subobjects that can conflict with empty
507 // field subobjects are subobjects of empty bases that can be placed at
508 // offset zero. Because of this, we only need to keep track of empty field
509 // subobjects with offsets less than the size of the largest empty
510 // subobject for our class.
511 if (ElementOffset
>= SizeOfLargestEmptySubobject
)
514 UpdateEmptyFieldSubobjects(RD
, RD
, ElementOffset
);
515 ElementOffset
+= Layout
.getSize();
520 typedef llvm::SmallPtrSet
<const CXXRecordDecl
*, 4> ClassSetTy
;
522 class RecordLayoutBuilder
{
524 // FIXME: Remove this and make the appropriate fields public.
525 friend class clang::ASTContext
;
527 const ASTContext
&Context
;
529 EmptySubobjectMap
*EmptySubobjects
;
531 /// Size - The current size of the record layout.
534 /// Alignment - The current alignment of the record layout.
537 /// \brief The alignment if attribute packed is not used.
538 CharUnits UnpackedAlignment
;
540 SmallVector
<uint64_t, 16> FieldOffsets
;
542 /// \brief Whether the external AST source has provided a layout for this
544 unsigned ExternalLayout
: 1;
546 /// \brief Whether we need to infer alignment, even when we have an
547 /// externally-provided layout.
548 unsigned InferAlignment
: 1;
550 /// Packed - Whether the record is packed or not.
553 unsigned IsUnion
: 1;
555 unsigned IsMac68kAlign
: 1;
557 unsigned IsMsStruct
: 1;
559 /// UnfilledBitsInLastUnit - If the last field laid out was a bitfield,
560 /// this contains the number of bits in the last unit that can be used for
561 /// an adjacent bitfield if necessary. The unit in question is usually
562 /// a byte, but larger units are used if IsMsStruct.
563 unsigned char UnfilledBitsInLastUnit
;
564 /// LastBitfieldTypeSize - If IsMsStruct, represents the size of the type
565 /// of the previous field if it was a bitfield.
566 unsigned char LastBitfieldTypeSize
;
568 /// MaxFieldAlignment - The maximum allowed field alignment. This is set by
570 CharUnits MaxFieldAlignment
;
572 /// DataSize - The data size of the record being laid out.
575 CharUnits NonVirtualSize
;
576 CharUnits NonVirtualAlignment
;
578 /// PrimaryBase - the primary base class (if one exists) of the class
579 /// we're laying out.
580 const CXXRecordDecl
*PrimaryBase
;
582 /// PrimaryBaseIsVirtual - Whether the primary base of the class we're laying
584 bool PrimaryBaseIsVirtual
;
586 /// HasOwnVFPtr - Whether the class provides its own vtable/vftbl
587 /// pointer, as opposed to inheriting one from a primary base class.
590 typedef llvm::DenseMap
<const CXXRecordDecl
*, CharUnits
> BaseOffsetsMapTy
;
592 /// Bases - base classes and their offsets in the record.
593 BaseOffsetsMapTy Bases
;
595 // VBases - virtual base classes and their offsets in the record.
596 ASTRecordLayout::VBaseOffsetsMapTy VBases
;
598 /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are
599 /// primary base classes for some other direct or indirect base class.
600 CXXIndirectPrimaryBaseSet IndirectPrimaryBases
;
602 /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in
603 /// inheritance graph order. Used for determining the primary base class.
604 const CXXRecordDecl
*FirstNearlyEmptyVBase
;
606 /// VisitedVirtualBases - A set of all the visited virtual bases, used to
607 /// avoid visiting virtual bases more than once.
608 llvm::SmallPtrSet
<const CXXRecordDecl
*, 4> VisitedVirtualBases
;
610 /// \brief Externally-provided size.
611 uint64_t ExternalSize
;
613 /// \brief Externally-provided alignment.
614 uint64_t ExternalAlign
;
616 /// \brief Externally-provided field offsets.
617 llvm::DenseMap
<const FieldDecl
*, uint64_t> ExternalFieldOffsets
;
619 /// \brief Externally-provided direct, non-virtual base offsets.
620 llvm::DenseMap
<const CXXRecordDecl
*, CharUnits
> ExternalBaseOffsets
;
622 /// \brief Externally-provided virtual base offsets.
623 llvm::DenseMap
<const CXXRecordDecl
*, CharUnits
> ExternalVirtualBaseOffsets
;
625 RecordLayoutBuilder(const ASTContext
&Context
,
626 EmptySubobjectMap
*EmptySubobjects
)
627 : Context(Context
), EmptySubobjects(EmptySubobjects
), Size(0),
628 Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()),
629 ExternalLayout(false), InferAlignment(false),
630 Packed(false), IsUnion(false), IsMac68kAlign(false), IsMsStruct(false),
631 UnfilledBitsInLastUnit(0), LastBitfieldTypeSize(0),
632 MaxFieldAlignment(CharUnits::Zero()),
633 DataSize(0), NonVirtualSize(CharUnits::Zero()),
634 NonVirtualAlignment(CharUnits::One()),
635 PrimaryBase(nullptr), PrimaryBaseIsVirtual(false),
637 FirstNearlyEmptyVBase(nullptr) {}
639 void Layout(const RecordDecl
*D
);
640 void Layout(const CXXRecordDecl
*D
);
641 void Layout(const ObjCInterfaceDecl
*D
);
643 void LayoutFields(const RecordDecl
*D
);
644 void LayoutField(const FieldDecl
*D
, bool InsertExtraPadding
);
645 void LayoutWideBitField(uint64_t FieldSize
, uint64_t TypeSize
,
646 bool FieldPacked
, const FieldDecl
*D
);
647 void LayoutBitField(const FieldDecl
*D
);
649 TargetCXXABI
getCXXABI() const {
650 return Context
.getTargetInfo().getCXXABI();
653 /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects.
654 llvm::SpecificBumpPtrAllocator
<BaseSubobjectInfo
> BaseSubobjectInfoAllocator
;
656 typedef llvm::DenseMap
<const CXXRecordDecl
*, BaseSubobjectInfo
*>
657 BaseSubobjectInfoMapTy
;
659 /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases
660 /// of the class we're laying out to their base subobject info.
661 BaseSubobjectInfoMapTy VirtualBaseInfo
;
663 /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the
664 /// class we're laying out to their base subobject info.
665 BaseSubobjectInfoMapTy NonVirtualBaseInfo
;
667 /// ComputeBaseSubobjectInfo - Compute the base subobject information for the
668 /// bases of the given class.
669 void ComputeBaseSubobjectInfo(const CXXRecordDecl
*RD
);
671 /// ComputeBaseSubobjectInfo - Compute the base subobject information for a
672 /// single class and all of its base classes.
673 BaseSubobjectInfo
*ComputeBaseSubobjectInfo(const CXXRecordDecl
*RD
,
675 BaseSubobjectInfo
*Derived
);
677 /// DeterminePrimaryBase - Determine the primary base of the given class.
678 void DeterminePrimaryBase(const CXXRecordDecl
*RD
);
680 void SelectPrimaryVBase(const CXXRecordDecl
*RD
);
682 void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign
);
684 /// LayoutNonVirtualBases - Determines the primary base class (if any) and
685 /// lays it out. Will then proceed to lay out all non-virtual base clasess.
686 void LayoutNonVirtualBases(const CXXRecordDecl
*RD
);
688 /// LayoutNonVirtualBase - Lays out a single non-virtual base.
689 void LayoutNonVirtualBase(const BaseSubobjectInfo
*Base
);
691 void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo
*Info
,
694 /// LayoutVirtualBases - Lays out all the virtual bases.
695 void LayoutVirtualBases(const CXXRecordDecl
*RD
,
696 const CXXRecordDecl
*MostDerivedClass
);
698 /// LayoutVirtualBase - Lays out a single virtual base.
699 void LayoutVirtualBase(const BaseSubobjectInfo
*Base
);
701 /// LayoutBase - Will lay out a base and return the offset where it was
702 /// placed, in chars.
703 CharUnits
LayoutBase(const BaseSubobjectInfo
*Base
);
705 /// InitializeLayout - Initialize record layout for the given record decl.
706 void InitializeLayout(const Decl
*D
);
708 /// FinishLayout - Finalize record layout. Adjust record size based on the
710 void FinishLayout(const NamedDecl
*D
);
712 void UpdateAlignment(CharUnits NewAlignment
, CharUnits UnpackedNewAlignment
);
713 void UpdateAlignment(CharUnits NewAlignment
) {
714 UpdateAlignment(NewAlignment
, NewAlignment
);
717 /// \brief Retrieve the externally-supplied field offset for the given
720 /// \param Field The field whose offset is being queried.
721 /// \param ComputedOffset The offset that we've computed for this field.
722 uint64_t updateExternalFieldOffset(const FieldDecl
*Field
,
723 uint64_t ComputedOffset
);
725 void CheckFieldPadding(uint64_t Offset
, uint64_t UnpaddedOffset
,
726 uint64_t UnpackedOffset
, unsigned UnpackedAlign
,
727 bool isPacked
, const FieldDecl
*D
);
729 DiagnosticBuilder
Diag(SourceLocation Loc
, unsigned DiagID
);
731 CharUnits
getSize() const {
732 assert(Size
% Context
.getCharWidth() == 0);
733 return Context
.toCharUnitsFromBits(Size
);
735 uint64_t getSizeInBits() const { return Size
; }
737 void setSize(CharUnits NewSize
) { Size
= Context
.toBits(NewSize
); }
738 void setSize(uint64_t NewSize
) { Size
= NewSize
; }
740 CharUnits
getAligment() const { return Alignment
; }
742 CharUnits
getDataSize() const {
743 assert(DataSize
% Context
.getCharWidth() == 0);
744 return Context
.toCharUnitsFromBits(DataSize
);
746 uint64_t getDataSizeInBits() const { return DataSize
; }
748 void setDataSize(CharUnits NewSize
) { DataSize
= Context
.toBits(NewSize
); }
749 void setDataSize(uint64_t NewSize
) { DataSize
= NewSize
; }
751 RecordLayoutBuilder(const RecordLayoutBuilder
&) LLVM_DELETED_FUNCTION
;
752 void operator=(const RecordLayoutBuilder
&) LLVM_DELETED_FUNCTION
;
754 } // end anonymous namespace
757 RecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl
*RD
) {
758 for (const auto &I
: RD
->bases()) {
759 assert(!I
.getType()->isDependentType() &&
760 "Cannot layout class with dependent bases.");
762 const CXXRecordDecl
*Base
= I
.getType()->getAsCXXRecordDecl();
764 // Check if this is a nearly empty virtual base.
765 if (I
.isVirtual() && Context
.isNearlyEmpty(Base
)) {
766 // If it's not an indirect primary base, then we've found our primary
768 if (!IndirectPrimaryBases
.count(Base
)) {
770 PrimaryBaseIsVirtual
= true;
774 // Is this the first nearly empty virtual base?
775 if (!FirstNearlyEmptyVBase
)
776 FirstNearlyEmptyVBase
= Base
;
779 SelectPrimaryVBase(Base
);
785 /// DeterminePrimaryBase - Determine the primary base of the given class.
786 void RecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl
*RD
) {
787 // If the class isn't dynamic, it won't have a primary base.
788 if (!RD
->isDynamicClass())
791 // Compute all the primary virtual bases for all of our direct and
792 // indirect bases, and record all their primary virtual base classes.
793 RD
->getIndirectPrimaryBases(IndirectPrimaryBases
);
795 // If the record has a dynamic base class, attempt to choose a primary base
796 // class. It is the first (in direct base class order) non-virtual dynamic
797 // base class, if one exists.
798 for (const auto &I
: RD
->bases()) {
799 // Ignore virtual bases.
803 const CXXRecordDecl
*Base
= I
.getType()->getAsCXXRecordDecl();
805 if (Base
->isDynamicClass()) {
808 PrimaryBaseIsVirtual
= false;
813 // Under the Itanium ABI, if there is no non-virtual primary base class,
814 // try to compute the primary virtual base. The primary virtual base is
815 // the first nearly empty virtual base that is not an indirect primary
816 // virtual base class, if one exists.
817 if (RD
->getNumVBases() != 0) {
818 SelectPrimaryVBase(RD
);
823 // Otherwise, it is the first indirect primary base class, if one exists.
824 if (FirstNearlyEmptyVBase
) {
825 PrimaryBase
= FirstNearlyEmptyVBase
;
826 PrimaryBaseIsVirtual
= true;
830 assert(!PrimaryBase
&& "Should not get here with a primary base!");
834 RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl
*RD
,
836 BaseSubobjectInfo
*Derived
) {
837 BaseSubobjectInfo
*Info
;
840 // Check if we already have info about this virtual base.
841 BaseSubobjectInfo
*&InfoSlot
= VirtualBaseInfo
[RD
];
843 assert(InfoSlot
->Class
== RD
&& "Wrong class for virtual base info!");
847 // We don't, create it.
848 InfoSlot
= new (BaseSubobjectInfoAllocator
.Allocate()) BaseSubobjectInfo
;
851 Info
= new (BaseSubobjectInfoAllocator
.Allocate()) BaseSubobjectInfo
;
855 Info
->IsVirtual
= IsVirtual
;
856 Info
->Derived
= nullptr;
857 Info
->PrimaryVirtualBaseInfo
= nullptr;
859 const CXXRecordDecl
*PrimaryVirtualBase
= nullptr;
860 BaseSubobjectInfo
*PrimaryVirtualBaseInfo
= nullptr;
862 // Check if this base has a primary virtual base.
863 if (RD
->getNumVBases()) {
864 const ASTRecordLayout
&Layout
= Context
.getASTRecordLayout(RD
);
865 if (Layout
.isPrimaryBaseVirtual()) {
866 // This base does have a primary virtual base.
867 PrimaryVirtualBase
= Layout
.getPrimaryBase();
868 assert(PrimaryVirtualBase
&& "Didn't have a primary virtual base!");
870 // Now check if we have base subobject info about this primary base.
871 PrimaryVirtualBaseInfo
= VirtualBaseInfo
.lookup(PrimaryVirtualBase
);
873 if (PrimaryVirtualBaseInfo
) {
874 if (PrimaryVirtualBaseInfo
->Derived
) {
875 // We did have info about this primary base, and it turns out that it
876 // has already been claimed as a primary virtual base for another
878 PrimaryVirtualBase
= nullptr;
880 // We can claim this base as our primary base.
881 Info
->PrimaryVirtualBaseInfo
= PrimaryVirtualBaseInfo
;
882 PrimaryVirtualBaseInfo
->Derived
= Info
;
888 // Now go through all direct bases.
889 for (const auto &I
: RD
->bases()) {
890 bool IsVirtual
= I
.isVirtual();
892 const CXXRecordDecl
*BaseDecl
= I
.getType()->getAsCXXRecordDecl();
894 Info
->Bases
.push_back(ComputeBaseSubobjectInfo(BaseDecl
, IsVirtual
, Info
));
897 if (PrimaryVirtualBase
&& !PrimaryVirtualBaseInfo
) {
898 // Traversing the bases must have created the base info for our primary
900 PrimaryVirtualBaseInfo
= VirtualBaseInfo
.lookup(PrimaryVirtualBase
);
901 assert(PrimaryVirtualBaseInfo
&&
902 "Did not create a primary virtual base!");
904 // Claim the primary virtual base as our primary virtual base.
905 Info
->PrimaryVirtualBaseInfo
= PrimaryVirtualBaseInfo
;
906 PrimaryVirtualBaseInfo
->Derived
= Info
;
912 void RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl
*RD
) {
913 for (const auto &I
: RD
->bases()) {
914 bool IsVirtual
= I
.isVirtual();
916 const CXXRecordDecl
*BaseDecl
= I
.getType()->getAsCXXRecordDecl();
918 // Compute the base subobject info for this base.
919 BaseSubobjectInfo
*Info
= ComputeBaseSubobjectInfo(BaseDecl
, IsVirtual
,
923 // ComputeBaseInfo has already added this base for us.
924 assert(VirtualBaseInfo
.count(BaseDecl
) &&
925 "Did not add virtual base!");
927 // Add the base info to the map of non-virtual bases.
928 assert(!NonVirtualBaseInfo
.count(BaseDecl
) &&
929 "Non-virtual base already exists!");
930 NonVirtualBaseInfo
.insert(std::make_pair(BaseDecl
, Info
));
936 RecordLayoutBuilder::EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign
) {
937 CharUnits BaseAlign
= (Packed
) ? CharUnits::One() : UnpackedBaseAlign
;
939 // The maximum field alignment overrides base align.
940 if (!MaxFieldAlignment
.isZero()) {
941 BaseAlign
= std::min(BaseAlign
, MaxFieldAlignment
);
942 UnpackedBaseAlign
= std::min(UnpackedBaseAlign
, MaxFieldAlignment
);
945 // Round up the current record size to pointer alignment.
946 setSize(getSize().RoundUpToAlignment(BaseAlign
));
947 setDataSize(getSize());
949 // Update the alignment.
950 UpdateAlignment(BaseAlign
, UnpackedBaseAlign
);
954 RecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl
*RD
) {
955 // Then, determine the primary base class.
956 DeterminePrimaryBase(RD
);
958 // Compute base subobject info.
959 ComputeBaseSubobjectInfo(RD
);
961 // If we have a primary base class, lay it out.
963 if (PrimaryBaseIsVirtual
) {
964 // If the primary virtual base was a primary virtual base of some other
965 // base class we'll have to steal it.
966 BaseSubobjectInfo
*PrimaryBaseInfo
= VirtualBaseInfo
.lookup(PrimaryBase
);
967 PrimaryBaseInfo
->Derived
= nullptr;
969 // We have a virtual primary base, insert it as an indirect primary base.
970 IndirectPrimaryBases
.insert(PrimaryBase
);
972 assert(!VisitedVirtualBases
.count(PrimaryBase
) &&
973 "vbase already visited!");
974 VisitedVirtualBases
.insert(PrimaryBase
);
976 LayoutVirtualBase(PrimaryBaseInfo
);
978 BaseSubobjectInfo
*PrimaryBaseInfo
=
979 NonVirtualBaseInfo
.lookup(PrimaryBase
);
980 assert(PrimaryBaseInfo
&&
981 "Did not find base info for non-virtual primary base!");
983 LayoutNonVirtualBase(PrimaryBaseInfo
);
986 // If this class needs a vtable/vf-table and didn't get one from a
987 // primary base, add it in now.
988 } else if (RD
->isDynamicClass()) {
989 assert(DataSize
== 0 && "Vtable pointer must be at offset zero!");
991 Context
.toCharUnitsFromBits(Context
.getTargetInfo().getPointerWidth(0));
993 Context
.toCharUnitsFromBits(Context
.getTargetInfo().getPointerAlign(0));
994 EnsureVTablePointerAlignment(PtrAlign
);
996 setSize(getSize() + PtrWidth
);
997 setDataSize(getSize());
1000 // Now lay out the non-virtual bases.
1001 for (const auto &I
: RD
->bases()) {
1003 // Ignore virtual bases.
1007 const CXXRecordDecl
*BaseDecl
= I
.getType()->getAsCXXRecordDecl();
1009 // Skip the primary base, because we've already laid it out. The
1010 // !PrimaryBaseIsVirtual check is required because we might have a
1011 // non-virtual base of the same type as a primary virtual base.
1012 if (BaseDecl
== PrimaryBase
&& !PrimaryBaseIsVirtual
)
1015 // Lay out the base.
1016 BaseSubobjectInfo
*BaseInfo
= NonVirtualBaseInfo
.lookup(BaseDecl
);
1017 assert(BaseInfo
&& "Did not find base info for non-virtual base!");
1019 LayoutNonVirtualBase(BaseInfo
);
1023 void RecordLayoutBuilder::LayoutNonVirtualBase(const BaseSubobjectInfo
*Base
) {
1025 CharUnits Offset
= LayoutBase(Base
);
1027 // Add its base class offset.
1028 assert(!Bases
.count(Base
->Class
) && "base offset already exists!");
1029 Bases
.insert(std::make_pair(Base
->Class
, Offset
));
1031 AddPrimaryVirtualBaseOffsets(Base
, Offset
);
1035 RecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo
*Info
,
1037 // This base isn't interesting, it has no virtual bases.
1038 if (!Info
->Class
->getNumVBases())
1041 // First, check if we have a virtual primary base to add offsets for.
1042 if (Info
->PrimaryVirtualBaseInfo
) {
1043 assert(Info
->PrimaryVirtualBaseInfo
->IsVirtual
&&
1044 "Primary virtual base is not virtual!");
1045 if (Info
->PrimaryVirtualBaseInfo
->Derived
== Info
) {
1047 assert(!VBases
.count(Info
->PrimaryVirtualBaseInfo
->Class
) &&
1048 "primary vbase offset already exists!");
1049 VBases
.insert(std::make_pair(Info
->PrimaryVirtualBaseInfo
->Class
,
1050 ASTRecordLayout::VBaseInfo(Offset
, false)));
1052 // Traverse the primary virtual base.
1053 AddPrimaryVirtualBaseOffsets(Info
->PrimaryVirtualBaseInfo
, Offset
);
1057 // Now go through all direct non-virtual bases.
1058 const ASTRecordLayout
&Layout
= Context
.getASTRecordLayout(Info
->Class
);
1059 for (const BaseSubobjectInfo
*Base
: Info
->Bases
) {
1060 if (Base
->IsVirtual
)
1063 CharUnits BaseOffset
= Offset
+ Layout
.getBaseClassOffset(Base
->Class
);
1064 AddPrimaryVirtualBaseOffsets(Base
, BaseOffset
);
1069 RecordLayoutBuilder::LayoutVirtualBases(const CXXRecordDecl
*RD
,
1070 const CXXRecordDecl
*MostDerivedClass
) {
1071 const CXXRecordDecl
*PrimaryBase
;
1072 bool PrimaryBaseIsVirtual
;
1074 if (MostDerivedClass
== RD
) {
1075 PrimaryBase
= this->PrimaryBase
;
1076 PrimaryBaseIsVirtual
= this->PrimaryBaseIsVirtual
;
1078 const ASTRecordLayout
&Layout
= Context
.getASTRecordLayout(RD
);
1079 PrimaryBase
= Layout
.getPrimaryBase();
1080 PrimaryBaseIsVirtual
= Layout
.isPrimaryBaseVirtual();
1083 for (const CXXBaseSpecifier
&Base
: RD
->bases()) {
1084 assert(!Base
.getType()->isDependentType() &&
1085 "Cannot layout class with dependent bases.");
1087 const CXXRecordDecl
*BaseDecl
= Base
.getType()->getAsCXXRecordDecl();
1089 if (Base
.isVirtual()) {
1090 if (PrimaryBase
!= BaseDecl
|| !PrimaryBaseIsVirtual
) {
1091 bool IndirectPrimaryBase
= IndirectPrimaryBases
.count(BaseDecl
);
1093 // Only lay out the virtual base if it's not an indirect primary base.
1094 if (!IndirectPrimaryBase
) {
1095 // Only visit virtual bases once.
1096 if (!VisitedVirtualBases
.insert(BaseDecl
).second
)
1099 const BaseSubobjectInfo
*BaseInfo
= VirtualBaseInfo
.lookup(BaseDecl
);
1100 assert(BaseInfo
&& "Did not find virtual base info!");
1101 LayoutVirtualBase(BaseInfo
);
1106 if (!BaseDecl
->getNumVBases()) {
1107 // This base isn't interesting since it doesn't have any virtual bases.
1111 LayoutVirtualBases(BaseDecl
, MostDerivedClass
);
1115 void RecordLayoutBuilder::LayoutVirtualBase(const BaseSubobjectInfo
*Base
) {
1116 assert(!Base
->Derived
&& "Trying to lay out a primary virtual base!");
1119 CharUnits Offset
= LayoutBase(Base
);
1121 // Add its base class offset.
1122 assert(!VBases
.count(Base
->Class
) && "vbase offset already exists!");
1123 VBases
.insert(std::make_pair(Base
->Class
,
1124 ASTRecordLayout::VBaseInfo(Offset
, false)));
1126 AddPrimaryVirtualBaseOffsets(Base
, Offset
);
1129 CharUnits
RecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo
*Base
) {
1130 const ASTRecordLayout
&Layout
= Context
.getASTRecordLayout(Base
->Class
);
1135 // Query the external layout to see if it provides an offset.
1136 bool HasExternalLayout
= false;
1137 if (ExternalLayout
) {
1138 llvm::DenseMap
<const CXXRecordDecl
*, CharUnits
>::iterator Known
;
1139 if (Base
->IsVirtual
) {
1140 Known
= ExternalVirtualBaseOffsets
.find(Base
->Class
);
1141 if (Known
!= ExternalVirtualBaseOffsets
.end()) {
1142 Offset
= Known
->second
;
1143 HasExternalLayout
= true;
1146 Known
= ExternalBaseOffsets
.find(Base
->Class
);
1147 if (Known
!= ExternalBaseOffsets
.end()) {
1148 Offset
= Known
->second
;
1149 HasExternalLayout
= true;
1154 CharUnits UnpackedBaseAlign
= Layout
.getNonVirtualAlignment();
1155 CharUnits BaseAlign
= (Packed
) ? CharUnits::One() : UnpackedBaseAlign
;
1157 // If we have an empty base class, try to place it at offset 0.
1158 if (Base
->Class
->isEmpty() &&
1159 (!HasExternalLayout
|| Offset
== CharUnits::Zero()) &&
1160 EmptySubobjects
->CanPlaceBaseAtOffset(Base
, CharUnits::Zero())) {
1161 setSize(std::max(getSize(), Layout
.getSize()));
1162 UpdateAlignment(BaseAlign
, UnpackedBaseAlign
);
1164 return CharUnits::Zero();
1167 // The maximum field alignment overrides base align.
1168 if (!MaxFieldAlignment
.isZero()) {
1169 BaseAlign
= std::min(BaseAlign
, MaxFieldAlignment
);
1170 UnpackedBaseAlign
= std::min(UnpackedBaseAlign
, MaxFieldAlignment
);
1173 if (!HasExternalLayout
) {
1174 // Round up the current record size to the base's alignment boundary.
1175 Offset
= getDataSize().RoundUpToAlignment(BaseAlign
);
1177 // Try to place the base.
1178 while (!EmptySubobjects
->CanPlaceBaseAtOffset(Base
, Offset
))
1179 Offset
+= BaseAlign
;
1181 bool Allowed
= EmptySubobjects
->CanPlaceBaseAtOffset(Base
, Offset
);
1183 assert(Allowed
&& "Base subobject externally placed at overlapping offset");
1185 if (InferAlignment
&& Offset
< getDataSize().RoundUpToAlignment(BaseAlign
)){
1186 // The externally-supplied base offset is before the base offset we
1187 // computed. Assume that the structure is packed.
1188 Alignment
= CharUnits::One();
1189 InferAlignment
= false;
1193 if (!Base
->Class
->isEmpty()) {
1194 // Update the data size.
1195 setDataSize(Offset
+ Layout
.getNonVirtualSize());
1197 setSize(std::max(getSize(), getDataSize()));
1199 setSize(std::max(getSize(), Offset
+ Layout
.getSize()));
1201 // Remember max struct/class alignment.
1202 UpdateAlignment(BaseAlign
, UnpackedBaseAlign
);
1207 void RecordLayoutBuilder::InitializeLayout(const Decl
*D
) {
1208 if (const RecordDecl
*RD
= dyn_cast
<RecordDecl
>(D
)) {
1209 IsUnion
= RD
->isUnion();
1210 IsMsStruct
= RD
->isMsStruct(Context
);
1213 Packed
= D
->hasAttr
<PackedAttr
>();
1215 // Honor the default struct packing maximum alignment flag.
1216 if (unsigned DefaultMaxFieldAlignment
= Context
.getLangOpts().PackStruct
) {
1217 MaxFieldAlignment
= CharUnits::fromQuantity(DefaultMaxFieldAlignment
);
1220 // mac68k alignment supersedes maximum field alignment and attribute aligned,
1221 // and forces all structures to have 2-byte alignment. The IBM docs on it
1222 // allude to additional (more complicated) semantics, especially with regard
1223 // to bit-fields, but gcc appears not to follow that.
1224 if (D
->hasAttr
<AlignMac68kAttr
>()) {
1225 IsMac68kAlign
= true;
1226 MaxFieldAlignment
= CharUnits::fromQuantity(2);
1227 Alignment
= CharUnits::fromQuantity(2);
1229 if (const MaxFieldAlignmentAttr
*MFAA
= D
->getAttr
<MaxFieldAlignmentAttr
>())
1230 MaxFieldAlignment
= Context
.toCharUnitsFromBits(MFAA
->getAlignment());
1232 if (unsigned MaxAlign
= D
->getMaxAlignment())
1233 UpdateAlignment(Context
.toCharUnitsFromBits(MaxAlign
));
1236 // If there is an external AST source, ask it for the various offsets.
1237 if (const RecordDecl
*RD
= dyn_cast
<RecordDecl
>(D
))
1238 if (ExternalASTSource
*External
= Context
.getExternalSource()) {
1239 ExternalLayout
= External
->layoutRecordType(RD
,
1242 ExternalFieldOffsets
,
1243 ExternalBaseOffsets
,
1244 ExternalVirtualBaseOffsets
);
1246 // Update based on external alignment.
1247 if (ExternalLayout
) {
1248 if (ExternalAlign
> 0) {
1249 Alignment
= Context
.toCharUnitsFromBits(ExternalAlign
);
1251 // The external source didn't have alignment information; infer it.
1252 InferAlignment
= true;
1258 void RecordLayoutBuilder::Layout(const RecordDecl
*D
) {
1259 InitializeLayout(D
);
1262 // Finally, round the size of the total struct up to the alignment of the
1267 void RecordLayoutBuilder::Layout(const CXXRecordDecl
*RD
) {
1268 InitializeLayout(RD
);
1270 // Lay out the vtable and the non-virtual bases.
1271 LayoutNonVirtualBases(RD
);
1275 NonVirtualSize
= Context
.toCharUnitsFromBits(
1276 llvm::RoundUpToAlignment(getSizeInBits(),
1277 Context
.getTargetInfo().getCharAlign()));
1278 NonVirtualAlignment
= Alignment
;
1280 // Lay out the virtual bases and add the primary virtual base offsets.
1281 LayoutVirtualBases(RD
, RD
);
1283 // Finally, round the size of the total struct up to the alignment
1284 // of the struct itself.
1288 // Check that we have base offsets for all bases.
1289 for (const CXXBaseSpecifier
&Base
: RD
->bases()) {
1290 if (Base
.isVirtual())
1293 const CXXRecordDecl
*BaseDecl
= Base
.getType()->getAsCXXRecordDecl();
1295 assert(Bases
.count(BaseDecl
) && "Did not find base offset!");
1298 // And all virtual bases.
1299 for (const CXXBaseSpecifier
&Base
: RD
->vbases()) {
1300 const CXXRecordDecl
*BaseDecl
= Base
.getType()->getAsCXXRecordDecl();
1302 assert(VBases
.count(BaseDecl
) && "Did not find base offset!");
1307 void RecordLayoutBuilder::Layout(const ObjCInterfaceDecl
*D
) {
1308 if (ObjCInterfaceDecl
*SD
= D
->getSuperClass()) {
1309 const ASTRecordLayout
&SL
= Context
.getASTObjCInterfaceLayout(SD
);
1311 UpdateAlignment(SL
.getAlignment());
1313 // We start laying out ivars not at the end of the superclass
1314 // structure, but at the next byte following the last field.
1315 setSize(SL
.getDataSize());
1316 setDataSize(getSize());
1319 InitializeLayout(D
);
1320 // Layout each ivar sequentially.
1321 for (const ObjCIvarDecl
*IVD
= D
->all_declared_ivar_begin(); IVD
;
1322 IVD
= IVD
->getNextIvar())
1323 LayoutField(IVD
, false);
1325 // Finally, round the size of the total struct up to the alignment of the
1330 void RecordLayoutBuilder::LayoutFields(const RecordDecl
*D
) {
1331 // Layout each field, for now, just sequentially, respecting alignment. In
1332 // the future, this will need to be tweakable by targets.
1333 bool InsertExtraPadding
= D
->mayInsertExtraPadding(/*EmitRemark=*/true);
1334 bool HasFlexibleArrayMember
= D
->hasFlexibleArrayMember();
1335 for (auto I
= D
->field_begin(), End
= D
->field_end(); I
!= End
; ++I
) {
1339 InsertExtraPadding
&& (Next
!= End
|| !HasFlexibleArrayMember
));
1343 // Rounds the specified size to have it a multiple of the char size.
1345 roundUpSizeToCharAlignment(uint64_t Size
,
1346 const ASTContext
&Context
) {
1347 uint64_t CharAlignment
= Context
.getTargetInfo().getCharAlign();
1348 return llvm::RoundUpToAlignment(Size
, CharAlignment
);
1351 void RecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize
,
1354 const FieldDecl
*D
) {
1355 assert(Context
.getLangOpts().CPlusPlus
&&
1356 "Can only have wide bit-fields in C++!");
1358 // Itanium C++ ABI 2.4:
1359 // If sizeof(T)*8 < n, let T' be the largest integral POD type with
1360 // sizeof(T')*8 <= n.
1362 QualType IntegralPODTypes
[] = {
1363 Context
.UnsignedCharTy
, Context
.UnsignedShortTy
, Context
.UnsignedIntTy
,
1364 Context
.UnsignedLongTy
, Context
.UnsignedLongLongTy
1368 for (const QualType
&QT
: IntegralPODTypes
) {
1369 uint64_t Size
= Context
.getTypeSize(QT
);
1371 if (Size
> FieldSize
)
1376 assert(!Type
.isNull() && "Did not find a type!");
1378 CharUnits TypeAlign
= Context
.getTypeAlignInChars(Type
);
1380 // We're not going to use any of the unfilled bits in the last byte.
1381 UnfilledBitsInLastUnit
= 0;
1382 LastBitfieldTypeSize
= 0;
1384 uint64_t FieldOffset
;
1385 uint64_t UnpaddedFieldOffset
= getDataSizeInBits() - UnfilledBitsInLastUnit
;
1388 uint64_t RoundedFieldSize
= roundUpSizeToCharAlignment(FieldSize
,
1390 setDataSize(std::max(getDataSizeInBits(), RoundedFieldSize
));
1393 // The bitfield is allocated starting at the next offset aligned
1394 // appropriately for T', with length n bits.
1395 FieldOffset
= llvm::RoundUpToAlignment(getDataSizeInBits(),
1396 Context
.toBits(TypeAlign
));
1398 uint64_t NewSizeInBits
= FieldOffset
+ FieldSize
;
1400 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits
,
1401 Context
.getTargetInfo().getCharAlign()));
1402 UnfilledBitsInLastUnit
= getDataSizeInBits() - NewSizeInBits
;
1405 // Place this field at the current location.
1406 FieldOffsets
.push_back(FieldOffset
);
1408 CheckFieldPadding(FieldOffset
, UnpaddedFieldOffset
, FieldOffset
,
1409 Context
.toBits(TypeAlign
), FieldPacked
, D
);
1412 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1414 // Remember max struct/class alignment.
1415 UpdateAlignment(TypeAlign
);
1418 void RecordLayoutBuilder::LayoutBitField(const FieldDecl
*D
) {
1419 bool FieldPacked
= Packed
|| D
->hasAttr
<PackedAttr
>();
1420 uint64_t FieldSize
= D
->getBitWidthValue(Context
);
1421 TypeInfo FieldInfo
= Context
.getTypeInfo(D
->getType());
1422 uint64_t TypeSize
= FieldInfo
.Width
;
1423 unsigned FieldAlign
= FieldInfo
.Align
;
1425 // UnfilledBitsInLastUnit is the difference between the end of the
1426 // last allocated bitfield (i.e. the first bit offset available for
1427 // bitfields) and the end of the current data size in bits (i.e. the
1428 // first bit offset available for non-bitfields). The current data
1429 // size in bits is always a multiple of the char size; additionally,
1430 // for ms_struct records it's also a multiple of the
1431 // LastBitfieldTypeSize (if set).
1433 // The struct-layout algorithm is dictated by the platform ABI,
1434 // which in principle could use almost any rules it likes. In
1435 // practice, UNIXy targets tend to inherit the algorithm described
1436 // in the System V generic ABI. The basic bitfield layout rule in
1437 // System V is to place bitfields at the next available bit offset
1438 // where the entire bitfield would fit in an aligned storage unit of
1439 // the declared type; it's okay if an earlier or later non-bitfield
1440 // is allocated in the same storage unit. However, some targets
1441 // (those that !useBitFieldTypeAlignment(), e.g. ARM APCS) don't
1442 // require this storage unit to be aligned, and therefore always put
1443 // the bitfield at the next available bit offset.
1445 // ms_struct basically requests a complete replacement of the
1446 // platform ABI's struct-layout algorithm, with the high-level goal
1447 // of duplicating MSVC's layout. For non-bitfields, this follows
1448 // the the standard algorithm. The basic bitfield layout rule is to
1449 // allocate an entire unit of the bitfield's declared type
1450 // (e.g. 'unsigned long'), then parcel it up among successive
1451 // bitfields whose declared types have the same size, making a new
1452 // unit as soon as the last can no longer store the whole value.
1453 // Since it completely replaces the platform ABI's algorithm,
1454 // settings like !useBitFieldTypeAlignment() do not apply.
1456 // A zero-width bitfield forces the use of a new storage unit for
1457 // later bitfields. In general, this occurs by rounding up the
1458 // current size of the struct as if the algorithm were about to
1459 // place a non-bitfield of the field's formal type. Usually this
1460 // does not change the alignment of the struct itself, but it does
1461 // on some targets (those that useZeroLengthBitfieldAlignment(),
1462 // e.g. ARM). In ms_struct layout, zero-width bitfields are
1463 // ignored unless they follow a non-zero-width bitfield.
1465 // A field alignment restriction (e.g. from #pragma pack) or
1466 // specification (e.g. from __attribute__((aligned))) changes the
1467 // formal alignment of the field. For System V, this alters the
1468 // required alignment of the notional storage unit that must contain
1469 // the bitfield. For ms_struct, this only affects the placement of
1470 // new storage units. In both cases, the effect of #pragma pack is
1471 // ignored on zero-width bitfields.
1473 // On System V, a packed field (e.g. from #pragma pack or
1474 // __attribute__((packed))) always uses the next available bit
1477 // In an ms_struct struct, the alignment of a fundamental type is
1478 // always equal to its size. This is necessary in order to mimic
1479 // the i386 alignment rules on targets which might not fully align
1480 // all types (e.g. Darwin PPC32, where alignof(long long) == 4).
1482 // First, some simple bookkeeping to perform for ms_struct structs.
1484 // The field alignment for integer types is always the size.
1485 FieldAlign
= TypeSize
;
1487 // If the previous field was not a bitfield, or was a bitfield
1488 // with a different storage unit size, we're done with that
1490 if (LastBitfieldTypeSize
!= TypeSize
) {
1491 // Also, ignore zero-length bitfields after non-bitfields.
1492 if (!LastBitfieldTypeSize
&& !FieldSize
)
1495 UnfilledBitsInLastUnit
= 0;
1496 LastBitfieldTypeSize
= 0;
1500 // If the field is wider than its declared type, it follows
1501 // different rules in all cases.
1502 if (FieldSize
> TypeSize
) {
1503 LayoutWideBitField(FieldSize
, TypeSize
, FieldPacked
, D
);
1507 // Compute the next available bit offset.
1508 uint64_t FieldOffset
=
1509 IsUnion
? 0 : (getDataSizeInBits() - UnfilledBitsInLastUnit
);
1511 // Handle targets that don't honor bitfield type alignment.
1512 if (!IsMsStruct
&& !Context
.getTargetInfo().useBitFieldTypeAlignment()) {
1513 // Some such targets do honor it on zero-width bitfields.
1514 if (FieldSize
== 0 &&
1515 Context
.getTargetInfo().useZeroLengthBitfieldAlignment()) {
1516 // The alignment to round up to is the max of the field's natural
1517 // alignment and a target-specific fixed value (sometimes zero).
1518 unsigned ZeroLengthBitfieldBoundary
=
1519 Context
.getTargetInfo().getZeroLengthBitfieldBoundary();
1520 FieldAlign
= std::max(FieldAlign
, ZeroLengthBitfieldBoundary
);
1522 // If that doesn't apply, just ignore the field alignment.
1528 // Remember the alignment we would have used if the field were not packed.
1529 unsigned UnpackedFieldAlign
= FieldAlign
;
1531 // Ignore the field alignment if the field is packed unless it has zero-size.
1532 if (!IsMsStruct
&& FieldPacked
&& FieldSize
!= 0)
1535 // But, if there's an 'aligned' attribute on the field, honor that.
1536 if (unsigned ExplicitFieldAlign
= D
->getMaxAlignment()) {
1537 FieldAlign
= std::max(FieldAlign
, ExplicitFieldAlign
);
1538 UnpackedFieldAlign
= std::max(UnpackedFieldAlign
, ExplicitFieldAlign
);
1541 // But, if there's a #pragma pack in play, that takes precedent over
1542 // even the 'aligned' attribute, for non-zero-width bitfields.
1543 if (!MaxFieldAlignment
.isZero() && FieldSize
) {
1544 unsigned MaxFieldAlignmentInBits
= Context
.toBits(MaxFieldAlignment
);
1545 FieldAlign
= std::min(FieldAlign
, MaxFieldAlignmentInBits
);
1546 UnpackedFieldAlign
= std::min(UnpackedFieldAlign
, MaxFieldAlignmentInBits
);
1549 // For purposes of diagnostics, we're going to simultaneously
1550 // compute the field offsets that we would have used if we weren't
1551 // adding any alignment padding or if the field weren't packed.
1552 uint64_t UnpaddedFieldOffset
= FieldOffset
;
1553 uint64_t UnpackedFieldOffset
= FieldOffset
;
1555 // Check if we need to add padding to fit the bitfield within an
1556 // allocation unit with the right size and alignment. The rules are
1557 // somewhat different here for ms_struct structs.
1559 // If it's not a zero-width bitfield, and we can fit the bitfield
1560 // into the active storage unit (and we haven't already decided to
1561 // start a new storage unit), just do so, regardless of any other
1562 // other consideration. Otherwise, round up to the right alignment.
1563 if (FieldSize
== 0 || FieldSize
> UnfilledBitsInLastUnit
) {
1564 FieldOffset
= llvm::RoundUpToAlignment(FieldOffset
, FieldAlign
);
1565 UnpackedFieldOffset
= llvm::RoundUpToAlignment(UnpackedFieldOffset
,
1566 UnpackedFieldAlign
);
1567 UnfilledBitsInLastUnit
= 0;
1571 // #pragma pack, with any value, suppresses the insertion of padding.
1572 bool AllowPadding
= MaxFieldAlignment
.isZero();
1574 // Compute the real offset.
1575 if (FieldSize
== 0 ||
1577 (FieldOffset
& (FieldAlign
-1)) + FieldSize
> TypeSize
)) {
1578 FieldOffset
= llvm::RoundUpToAlignment(FieldOffset
, FieldAlign
);
1581 // Repeat the computation for diagnostic purposes.
1582 if (FieldSize
== 0 ||
1584 (UnpackedFieldOffset
& (UnpackedFieldAlign
-1)) + FieldSize
> TypeSize
))
1585 UnpackedFieldOffset
= llvm::RoundUpToAlignment(UnpackedFieldOffset
,
1586 UnpackedFieldAlign
);
1589 // If we're using external layout, give the external layout a chance
1590 // to override this information.
1592 FieldOffset
= updateExternalFieldOffset(D
, FieldOffset
);
1594 // Okay, place the bitfield at the calculated offset.
1595 FieldOffsets
.push_back(FieldOffset
);
1599 // Anonymous members don't affect the overall record alignment,
1600 // except on targets where they do.
1602 !Context
.getTargetInfo().useZeroLengthBitfieldAlignment() &&
1603 !D
->getIdentifier())
1604 FieldAlign
= UnpackedFieldAlign
= 1;
1606 // Diagnose differences in layout due to padding or packing.
1607 if (!ExternalLayout
)
1608 CheckFieldPadding(FieldOffset
, UnpaddedFieldOffset
, UnpackedFieldOffset
,
1609 UnpackedFieldAlign
, FieldPacked
, D
);
1611 // Update DataSize to include the last byte containing (part of) the bitfield.
1613 // For unions, this is just a max operation, as usual.
1615 uint64_t RoundedFieldSize
= roundUpSizeToCharAlignment(FieldSize
,
1617 setDataSize(std::max(getDataSizeInBits(), RoundedFieldSize
));
1618 // For non-zero-width bitfields in ms_struct structs, allocate a new
1619 // storage unit if necessary.
1620 } else if (IsMsStruct
&& FieldSize
) {
1621 // We should have cleared UnfilledBitsInLastUnit in every case
1622 // where we changed storage units.
1623 if (!UnfilledBitsInLastUnit
) {
1624 setDataSize(FieldOffset
+ TypeSize
);
1625 UnfilledBitsInLastUnit
= TypeSize
;
1627 UnfilledBitsInLastUnit
-= FieldSize
;
1628 LastBitfieldTypeSize
= TypeSize
;
1630 // Otherwise, bump the data size up to include the bitfield,
1631 // including padding up to char alignment, and then remember how
1632 // bits we didn't use.
1634 uint64_t NewSizeInBits
= FieldOffset
+ FieldSize
;
1635 uint64_t CharAlignment
= Context
.getTargetInfo().getCharAlign();
1636 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits
, CharAlignment
));
1637 UnfilledBitsInLastUnit
= getDataSizeInBits() - NewSizeInBits
;
1639 // The only time we can get here for an ms_struct is if this is a
1640 // zero-width bitfield, which doesn't count as anything for the
1641 // purposes of unfilled bits.
1642 LastBitfieldTypeSize
= 0;
1646 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1648 // Remember max struct/class alignment.
1649 UpdateAlignment(Context
.toCharUnitsFromBits(FieldAlign
),
1650 Context
.toCharUnitsFromBits(UnpackedFieldAlign
));
1653 void RecordLayoutBuilder::LayoutField(const FieldDecl
*D
,
1654 bool InsertExtraPadding
) {
1655 if (D
->isBitField()) {
1660 uint64_t UnpaddedFieldOffset
= getDataSizeInBits() - UnfilledBitsInLastUnit
;
1662 // Reset the unfilled bits.
1663 UnfilledBitsInLastUnit
= 0;
1664 LastBitfieldTypeSize
= 0;
1666 bool FieldPacked
= Packed
|| D
->hasAttr
<PackedAttr
>();
1667 CharUnits FieldOffset
=
1668 IsUnion
? CharUnits::Zero() : getDataSize();
1669 CharUnits FieldSize
;
1670 CharUnits FieldAlign
;
1672 if (D
->getType()->isIncompleteArrayType()) {
1673 // This is a flexible array member; we can't directly
1674 // query getTypeInfo about these, so we figure it out here.
1675 // Flexible array members don't have any size, but they
1676 // have to be aligned appropriately for their element type.
1677 FieldSize
= CharUnits::Zero();
1678 const ArrayType
* ATy
= Context
.getAsArrayType(D
->getType());
1679 FieldAlign
= Context
.getTypeAlignInChars(ATy
->getElementType());
1680 } else if (const ReferenceType
*RT
= D
->getType()->getAs
<ReferenceType
>()) {
1681 unsigned AS
= RT
->getPointeeType().getAddressSpace();
1683 Context
.toCharUnitsFromBits(Context
.getTargetInfo().getPointerWidth(AS
));
1685 Context
.toCharUnitsFromBits(Context
.getTargetInfo().getPointerAlign(AS
));
1687 std::pair
<CharUnits
, CharUnits
> FieldInfo
=
1688 Context
.getTypeInfoInChars(D
->getType());
1689 FieldSize
= FieldInfo
.first
;
1690 FieldAlign
= FieldInfo
.second
;
1693 // If MS bitfield layout is required, figure out what type is being
1694 // laid out and align the field to the width of that type.
1696 // Resolve all typedefs down to their base type and round up the field
1697 // alignment if necessary.
1698 QualType T
= Context
.getBaseElementType(D
->getType());
1699 if (const BuiltinType
*BTy
= T
->getAs
<BuiltinType
>()) {
1700 CharUnits TypeSize
= Context
.getTypeSizeInChars(BTy
);
1701 if (TypeSize
> FieldAlign
)
1702 FieldAlign
= TypeSize
;
1707 // The align if the field is not packed. This is to check if the attribute
1708 // was unnecessary (-Wpacked).
1709 CharUnits UnpackedFieldAlign
= FieldAlign
;
1710 CharUnits UnpackedFieldOffset
= FieldOffset
;
1713 FieldAlign
= CharUnits::One();
1714 CharUnits MaxAlignmentInChars
=
1715 Context
.toCharUnitsFromBits(D
->getMaxAlignment());
1716 FieldAlign
= std::max(FieldAlign
, MaxAlignmentInChars
);
1717 UnpackedFieldAlign
= std::max(UnpackedFieldAlign
, MaxAlignmentInChars
);
1719 // The maximum field alignment overrides the aligned attribute.
1720 if (!MaxFieldAlignment
.isZero()) {
1721 FieldAlign
= std::min(FieldAlign
, MaxFieldAlignment
);
1722 UnpackedFieldAlign
= std::min(UnpackedFieldAlign
, MaxFieldAlignment
);
1725 // Round up the current record size to the field's alignment boundary.
1726 FieldOffset
= FieldOffset
.RoundUpToAlignment(FieldAlign
);
1727 UnpackedFieldOffset
=
1728 UnpackedFieldOffset
.RoundUpToAlignment(UnpackedFieldAlign
);
1730 if (ExternalLayout
) {
1731 FieldOffset
= Context
.toCharUnitsFromBits(
1732 updateExternalFieldOffset(D
, Context
.toBits(FieldOffset
)));
1734 if (!IsUnion
&& EmptySubobjects
) {
1735 // Record the fact that we're placing a field at this offset.
1736 bool Allowed
= EmptySubobjects
->CanPlaceFieldAtOffset(D
, FieldOffset
);
1738 assert(Allowed
&& "Externally-placed field cannot be placed here");
1741 if (!IsUnion
&& EmptySubobjects
) {
1742 // Check if we can place the field at this offset.
1743 while (!EmptySubobjects
->CanPlaceFieldAtOffset(D
, FieldOffset
)) {
1744 // We couldn't place the field at the offset. Try again at a new offset.
1745 FieldOffset
+= FieldAlign
;
1750 // Place this field at the current location.
1751 FieldOffsets
.push_back(Context
.toBits(FieldOffset
));
1753 if (!ExternalLayout
)
1754 CheckFieldPadding(Context
.toBits(FieldOffset
), UnpaddedFieldOffset
,
1755 Context
.toBits(UnpackedFieldOffset
),
1756 Context
.toBits(UnpackedFieldAlign
), FieldPacked
, D
);
1758 if (InsertExtraPadding
) {
1759 CharUnits ASanAlignment
= CharUnits::fromQuantity(8);
1760 CharUnits ExtraSizeForAsan
= ASanAlignment
;
1761 if (FieldSize
% ASanAlignment
)
1763 ASanAlignment
- CharUnits::fromQuantity(FieldSize
% ASanAlignment
);
1764 FieldSize
+= ExtraSizeForAsan
;
1767 // Reserve space for this field.
1768 uint64_t FieldSizeInBits
= Context
.toBits(FieldSize
);
1770 setDataSize(std::max(getDataSizeInBits(), FieldSizeInBits
));
1772 setDataSize(FieldOffset
+ FieldSize
);
1775 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1777 // Remember max struct/class alignment.
1778 UpdateAlignment(FieldAlign
, UnpackedFieldAlign
);
1781 void RecordLayoutBuilder::FinishLayout(const NamedDecl
*D
) {
1782 // In C++, records cannot be of size 0.
1783 if (Context
.getLangOpts().CPlusPlus
&& getSizeInBits() == 0) {
1784 if (const CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(D
)) {
1785 // Compatibility with gcc requires a class (pod or non-pod)
1786 // which is not empty but of size 0; such as having fields of
1787 // array of zero-length, remains of Size 0
1789 setSize(CharUnits::One());
1792 setSize(CharUnits::One());
1795 // Finally, round the size of the record up to the alignment of the
1797 uint64_t UnpaddedSize
= getSizeInBits() - UnfilledBitsInLastUnit
;
1798 uint64_t UnpackedSizeInBits
=
1799 llvm::RoundUpToAlignment(getSizeInBits(),
1800 Context
.toBits(UnpackedAlignment
));
1801 CharUnits UnpackedSize
= Context
.toCharUnitsFromBits(UnpackedSizeInBits
);
1802 uint64_t RoundedSize
1803 = llvm::RoundUpToAlignment(getSizeInBits(), Context
.toBits(Alignment
));
1805 if (ExternalLayout
) {
1806 // If we're inferring alignment, and the external size is smaller than
1807 // our size after we've rounded up to alignment, conservatively set the
1809 if (InferAlignment
&& ExternalSize
< RoundedSize
) {
1810 Alignment
= CharUnits::One();
1811 InferAlignment
= false;
1813 setSize(ExternalSize
);
1817 // Set the size to the final size.
1818 setSize(RoundedSize
);
1820 unsigned CharBitNum
= Context
.getTargetInfo().getCharWidth();
1821 if (const RecordDecl
*RD
= dyn_cast
<RecordDecl
>(D
)) {
1822 // Warn if padding was introduced to the struct/class/union.
1823 if (getSizeInBits() > UnpaddedSize
) {
1824 unsigned PadSize
= getSizeInBits() - UnpaddedSize
;
1826 if (PadSize
% CharBitNum
== 0) {
1827 PadSize
= PadSize
/ CharBitNum
;
1830 Diag(RD
->getLocation(), diag::warn_padded_struct_size
)
1831 << Context
.getTypeDeclType(RD
)
1833 << (InBits
? 1 : 0) /*(byte|bit)*/ << (PadSize
> 1); // plural or not
1836 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
1837 // bother since there won't be alignment issues.
1838 if (Packed
&& UnpackedAlignment
> CharUnits::One() &&
1839 getSize() == UnpackedSize
)
1840 Diag(D
->getLocation(), diag::warn_unnecessary_packed
)
1841 << Context
.getTypeDeclType(RD
);
1845 void RecordLayoutBuilder::UpdateAlignment(CharUnits NewAlignment
,
1846 CharUnits UnpackedNewAlignment
) {
1847 // The alignment is not modified when using 'mac68k' alignment or when
1848 // we have an externally-supplied layout that also provides overall alignment.
1849 if (IsMac68kAlign
|| (ExternalLayout
&& !InferAlignment
))
1852 if (NewAlignment
> Alignment
) {
1853 assert(llvm::isPowerOf2_32(NewAlignment
.getQuantity() &&
1854 "Alignment not a power of 2"));
1855 Alignment
= NewAlignment
;
1858 if (UnpackedNewAlignment
> UnpackedAlignment
) {
1859 assert(llvm::isPowerOf2_32(UnpackedNewAlignment
.getQuantity() &&
1860 "Alignment not a power of 2"));
1861 UnpackedAlignment
= UnpackedNewAlignment
;
1866 RecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl
*Field
,
1867 uint64_t ComputedOffset
) {
1868 assert(ExternalFieldOffsets
.find(Field
) != ExternalFieldOffsets
.end() &&
1869 "Field does not have an external offset");
1871 uint64_t ExternalFieldOffset
= ExternalFieldOffsets
[Field
];
1873 if (InferAlignment
&& ExternalFieldOffset
< ComputedOffset
) {
1874 // The externally-supplied field offset is before the field offset we
1875 // computed. Assume that the structure is packed.
1876 Alignment
= CharUnits::One();
1877 InferAlignment
= false;
1880 // Use the externally-supplied field offset.
1881 return ExternalFieldOffset
;
1884 /// \brief Get diagnostic %select index for tag kind for
1885 /// field padding diagnostic message.
1886 /// WARNING: Indexes apply to particular diagnostics only!
1888 /// \returns diagnostic %select index.
1889 static unsigned getPaddingDiagFromTagKind(TagTypeKind Tag
) {
1891 case TTK_Struct
: return 0;
1892 case TTK_Interface
: return 1;
1893 case TTK_Class
: return 2;
1894 default: llvm_unreachable("Invalid tag kind for field padding diagnostic!");
1898 void RecordLayoutBuilder::CheckFieldPadding(uint64_t Offset
,
1899 uint64_t UnpaddedOffset
,
1900 uint64_t UnpackedOffset
,
1901 unsigned UnpackedAlign
,
1903 const FieldDecl
*D
) {
1904 // We let objc ivars without warning, objc interfaces generally are not used
1905 // for padding tricks.
1906 if (isa
<ObjCIvarDecl
>(D
))
1909 // Don't warn about structs created without a SourceLocation. This can
1910 // be done by clients of the AST, such as codegen.
1911 if (D
->getLocation().isInvalid())
1914 unsigned CharBitNum
= Context
.getTargetInfo().getCharWidth();
1916 // Warn if padding was introduced to the struct/class.
1917 if (!IsUnion
&& Offset
> UnpaddedOffset
) {
1918 unsigned PadSize
= Offset
- UnpaddedOffset
;
1920 if (PadSize
% CharBitNum
== 0) {
1921 PadSize
= PadSize
/ CharBitNum
;
1924 if (D
->getIdentifier())
1925 Diag(D
->getLocation(), diag::warn_padded_struct_field
)
1926 << getPaddingDiagFromTagKind(D
->getParent()->getTagKind())
1927 << Context
.getTypeDeclType(D
->getParent())
1929 << (InBits
? 1 : 0) /*(byte|bit)*/ << (PadSize
> 1) // plural or not
1930 << D
->getIdentifier();
1932 Diag(D
->getLocation(), diag::warn_padded_struct_anon_field
)
1933 << getPaddingDiagFromTagKind(D
->getParent()->getTagKind())
1934 << Context
.getTypeDeclType(D
->getParent())
1936 << (InBits
? 1 : 0) /*(byte|bit)*/ << (PadSize
> 1); // plural or not
1939 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
1940 // bother since there won't be alignment issues.
1941 if (isPacked
&& UnpackedAlign
> CharBitNum
&& Offset
== UnpackedOffset
)
1942 Diag(D
->getLocation(), diag::warn_unnecessary_packed
)
1943 << D
->getIdentifier();
1946 static const CXXMethodDecl
*computeKeyFunction(ASTContext
&Context
,
1947 const CXXRecordDecl
*RD
) {
1948 // If a class isn't polymorphic it doesn't have a key function.
1949 if (!RD
->isPolymorphic())
1952 // A class that is not externally visible doesn't have a key function. (Or
1953 // at least, there's no point to assigning a key function to such a class;
1954 // this doesn't affect the ABI.)
1955 if (!RD
->isExternallyVisible())
1958 // Template instantiations don't have key functions per Itanium C++ ABI 5.2.6.
1959 // Same behavior as GCC.
1960 TemplateSpecializationKind TSK
= RD
->getTemplateSpecializationKind();
1961 if (TSK
== TSK_ImplicitInstantiation
||
1962 TSK
== TSK_ExplicitInstantiationDeclaration
||
1963 TSK
== TSK_ExplicitInstantiationDefinition
)
1966 bool allowInlineFunctions
=
1967 Context
.getTargetInfo().getCXXABI().canKeyFunctionBeInline();
1969 for (const CXXMethodDecl
*MD
: RD
->methods()) {
1970 if (!MD
->isVirtual())
1976 // Ignore implicit member functions, they are always marked as inline, but
1977 // they don't have a body until they're defined.
1978 if (MD
->isImplicit())
1981 if (MD
->isInlineSpecified())
1984 if (MD
->hasInlineBody())
1987 // Ignore inline deleted or defaulted functions.
1988 if (!MD
->isUserProvided())
1991 // In certain ABIs, ignore functions with out-of-line inline definitions.
1992 if (!allowInlineFunctions
) {
1993 const FunctionDecl
*Def
;
1994 if (MD
->hasBody(Def
) && Def
->isInlineSpecified())
2006 RecordLayoutBuilder::Diag(SourceLocation Loc
, unsigned DiagID
) {
2007 return Context
.getDiagnostics().Report(Loc
, DiagID
);
2010 /// Does the target C++ ABI require us to skip over the tail-padding
2011 /// of the given class (considering it as a base class) when allocating
2013 static bool mustSkipTailPadding(TargetCXXABI ABI
, const CXXRecordDecl
*RD
) {
2014 switch (ABI
.getTailPaddingUseRules()) {
2015 case TargetCXXABI::AlwaysUseTailPadding
:
2018 case TargetCXXABI::UseTailPaddingUnlessPOD03
:
2019 // FIXME: To the extent that this is meant to cover the Itanium ABI
2020 // rules, we should implement the restrictions about over-sized
2023 // http://mentorembedded.github.com/cxx-abi/abi.html#POD :
2024 // In general, a type is considered a POD for the purposes of
2025 // layout if it is a POD type (in the sense of ISO C++
2026 // [basic.types]). However, a POD-struct or POD-union (in the
2027 // sense of ISO C++ [class]) with a bitfield member whose
2028 // declared width is wider than the declared type of the
2029 // bitfield is not a POD for the purpose of layout. Similarly,
2030 // an array type is not a POD for the purpose of layout if the
2031 // element type of the array is not a POD for the purpose of
2034 // Where references to the ISO C++ are made in this paragraph,
2035 // the Technical Corrigendum 1 version of the standard is
2039 case TargetCXXABI::UseTailPaddingUnlessPOD11
:
2040 // This is equivalent to RD->getTypeForDecl().isCXX11PODType(),
2041 // but with a lot of abstraction penalty stripped off. This does
2042 // assume that these properties are set correctly even in C++98
2043 // mode; fortunately, that is true because we want to assign
2044 // consistently semantics to the type-traits intrinsics (or at
2045 // least as many of them as possible).
2046 return RD
->isTrivial() && RD
->isStandardLayout();
2049 llvm_unreachable("bad tail-padding use kind");
2052 static bool isMsLayout(const RecordDecl
* D
) {
2053 return D
->getASTContext().getTargetInfo().getCXXABI().isMicrosoft();
2056 // This section contains an implementation of struct layout that is, up to the
2057 // included tests, compatible with cl.exe (2013). The layout produced is
2058 // significantly different than those produced by the Itanium ABI. Here we note
2059 // the most important differences.
2061 // * The alignment of bitfields in unions is ignored when computing the
2062 // alignment of the union.
2063 // * The existence of zero-width bitfield that occurs after anything other than
2064 // a non-zero length bitfield is ignored.
2065 // * There is no explicit primary base for the purposes of layout. All bases
2066 // with vfptrs are laid out first, followed by all bases without vfptrs.
2067 // * The Itanium equivalent vtable pointers are split into a vfptr (virtual
2068 // function pointer) and a vbptr (virtual base pointer). They can each be
2069 // shared with a, non-virtual bases. These bases need not be the same. vfptrs
2070 // always occur at offset 0. vbptrs can occur at an arbitrary offset and are
2071 // placed after the lexiographically last non-virtual base. This placement
2072 // is always before fields but can be in the middle of the non-virtual bases
2073 // due to the two-pass layout scheme for non-virtual-bases.
2074 // * Virtual bases sometimes require a 'vtordisp' field that is laid out before
2075 // the virtual base and is used in conjunction with virtual overrides during
2076 // construction and destruction. This is always a 4 byte value and is used as
2077 // an alternative to constructor vtables.
2078 // * vtordisps are allocated in a block of memory with size and alignment equal
2079 // to the alignment of the completed structure (before applying __declspec(
2080 // align())). The vtordisp always occur at the end of the allocation block,
2081 // immediately prior to the virtual base.
2082 // * vfptrs are injected after all bases and fields have been laid out. In
2083 // order to guarantee proper alignment of all fields, the vfptr injection
2084 // pushes all bases and fields back by the alignment imposed by those bases
2085 // and fields. This can potentially add a significant amount of padding.
2086 // vfptrs are always injected at offset 0.
2087 // * vbptrs are injected after all bases and fields have been laid out. In
2088 // order to guarantee proper alignment of all fields, the vfptr injection
2089 // pushes all bases and fields back by the alignment imposed by those bases
2090 // and fields. This can potentially add a significant amount of padding.
2091 // vbptrs are injected immediately after the last non-virtual base as
2092 // lexiographically ordered in the code. If this site isn't pointer aligned
2093 // the vbptr is placed at the next properly aligned location. Enough padding
2094 // is added to guarantee a fit.
2095 // * The last zero sized non-virtual base can be placed at the end of the
2096 // struct (potentially aliasing another object), or may alias with the first
2097 // field, even if they are of the same type.
2098 // * The last zero size virtual base may be placed at the end of the struct
2099 // potentially aliasing another object.
2100 // * The ABI attempts to avoid aliasing of zero sized bases by adding padding
2101 // between bases or vbases with specific properties. The criteria for
2102 // additional padding between two bases is that the first base is zero sized
2103 // or ends with a zero sized subobject and the second base is zero sized or
2104 // trails with a zero sized base or field (sharing of vfptrs can reorder the
2105 // layout of the so the leading base is not always the first one declared).
2106 // This rule does take into account fields that are not records, so padding
2107 // will occur even if the last field is, e.g. an int. The padding added for
2108 // bases is 1 byte. The padding added between vbases depends on the alignment
2109 // of the object but is at least 4 bytes (in both 32 and 64 bit modes).
2110 // * There is no concept of non-virtual alignment, non-virtual alignment and
2111 // alignment are always identical.
2112 // * There is a distinction between alignment and required alignment.
2113 // __declspec(align) changes the required alignment of a struct. This
2114 // alignment is _always_ obeyed, even in the presence of #pragma pack. A
2115 // record inherits required alignment from all of its fields and bases.
2116 // * __declspec(align) on bitfields has the effect of changing the bitfield's
2117 // alignment instead of its required alignment. This is the only known way
2118 // to make the alignment of a struct bigger than 8. Interestingly enough
2119 // this alignment is also immune to the effects of #pragma pack and can be
2120 // used to create structures with large alignment under #pragma pack.
2121 // However, because it does not impact required alignment, such a structure,
2122 // when used as a field or base, will not be aligned if #pragma pack is
2123 // still active at the time of use.
2125 // Known incompatibilities:
2126 // * all: #pragma pack between fields in a record
2127 // * 2010 and back: If the last field in a record is a bitfield, every object
2128 // laid out after the record will have extra padding inserted before it. The
2129 // extra padding will have size equal to the size of the storage class of the
2130 // bitfield. 0 sized bitfields don't exhibit this behavior and the extra
2131 // padding can be avoided by adding a 0 sized bitfield after the non-zero-
2133 // * 2012 and back: In 64-bit mode, if the alignment of a record is 16 or
2134 // greater due to __declspec(align()) then a second layout phase occurs after
2135 // The locations of the vf and vb pointers are known. This layout phase
2136 // suffers from the "last field is a bitfield" bug in 2010 and results in
2137 // _every_ field getting padding put in front of it, potentially including the
2138 // vfptr, leaving the vfprt at a non-zero location which results in a fault if
2139 // anything tries to read the vftbl. The second layout phase also treats
2140 // bitfields as separate entities and gives them each storage rather than
2141 // packing them. Additionally, because this phase appears to perform a
2142 // (an unstable) sort on the members before laying them out and because merged
2143 // bitfields have the same address, the bitfields end up in whatever order
2144 // the sort left them in, a behavior we could never hope to replicate.
2147 struct MicrosoftRecordLayoutBuilder
{
2148 struct ElementInfo
{
2150 CharUnits Alignment
;
2152 typedef llvm::DenseMap
<const CXXRecordDecl
*, CharUnits
> BaseOffsetsMapTy
;
2153 MicrosoftRecordLayoutBuilder(const ASTContext
&Context
) : Context(Context
) {}
2155 MicrosoftRecordLayoutBuilder(const MicrosoftRecordLayoutBuilder
&)
2156 LLVM_DELETED_FUNCTION
;
2157 void operator=(const MicrosoftRecordLayoutBuilder
&) LLVM_DELETED_FUNCTION
;
2159 void layout(const RecordDecl
*RD
);
2160 void cxxLayout(const CXXRecordDecl
*RD
);
2161 /// \brief Initializes size and alignment and honors some flags.
2162 void initializeLayout(const RecordDecl
*RD
);
2163 /// \brief Initialized C++ layout, compute alignment and virtual alignment and
2164 /// existence of vfptrs and vbptrs. Alignment is needed before the vfptr is
2166 void initializeCXXLayout(const CXXRecordDecl
*RD
);
2167 void layoutNonVirtualBases(const CXXRecordDecl
*RD
);
2168 void layoutNonVirtualBase(const CXXRecordDecl
*BaseDecl
,
2169 const ASTRecordLayout
&BaseLayout
,
2170 const ASTRecordLayout
*&PreviousBaseLayout
);
2171 void injectVFPtr(const CXXRecordDecl
*RD
);
2172 void injectVBPtr(const CXXRecordDecl
*RD
);
2173 /// \brief Lays out the fields of the record. Also rounds size up to
2175 void layoutFields(const RecordDecl
*RD
);
2176 void layoutField(const FieldDecl
*FD
);
2177 void layoutBitField(const FieldDecl
*FD
);
2178 /// \brief Lays out a single zero-width bit-field in the record and handles
2179 /// special cases associated with zero-width bit-fields.
2180 void layoutZeroWidthBitField(const FieldDecl
*FD
);
2181 void layoutVirtualBases(const CXXRecordDecl
*RD
);
2182 void finalizeLayout(const RecordDecl
*RD
);
2183 /// \brief Gets the size and alignment of a base taking pragma pack and
2184 /// __declspec(align) into account.
2185 ElementInfo
getAdjustedElementInfo(const ASTRecordLayout
&Layout
);
2186 /// \brief Gets the size and alignment of a field taking pragma pack and
2187 /// __declspec(align) into account. It also updates RequiredAlignment as a
2188 /// side effect because it is most convenient to do so here.
2189 ElementInfo
getAdjustedElementInfo(const FieldDecl
*FD
);
2190 /// \brief Places a field at an offset in CharUnits.
2191 void placeFieldAtOffset(CharUnits FieldOffset
) {
2192 FieldOffsets
.push_back(Context
.toBits(FieldOffset
));
2194 /// \brief Places a bitfield at a bit offset.
2195 void placeFieldAtBitOffset(uint64_t FieldOffset
) {
2196 FieldOffsets
.push_back(FieldOffset
);
2198 /// \brief Compute the set of virtual bases for which vtordisps are required.
2199 void computeVtorDispSet(
2200 llvm::SmallPtrSetImpl
<const CXXRecordDecl
*> &HasVtorDispSet
,
2201 const CXXRecordDecl
*RD
) const;
2202 const ASTContext
&Context
;
2203 /// \brief The size of the record being laid out.
2205 /// \brief The non-virtual size of the record layout.
2206 CharUnits NonVirtualSize
;
2207 /// \brief The data size of the record layout.
2209 /// \brief The current alignment of the record layout.
2210 CharUnits Alignment
;
2211 /// \brief The maximum allowed field alignment. This is set by #pragma pack.
2212 CharUnits MaxFieldAlignment
;
2213 /// \brief The alignment that this record must obey. This is imposed by
2214 /// __declspec(align()) on the record itself or one of its fields or bases.
2215 CharUnits RequiredAlignment
;
2216 /// \brief The size of the allocation of the currently active bitfield.
2217 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield
2219 CharUnits CurrentBitfieldSize
;
2220 /// \brief Offset to the virtual base table pointer (if one exists).
2221 CharUnits VBPtrOffset
;
2222 /// \brief Minimum record size possible.
2223 CharUnits MinEmptyStructSize
;
2224 /// \brief The size and alignment info of a pointer.
2225 ElementInfo PointerInfo
;
2226 /// \brief The primary base class (if one exists).
2227 const CXXRecordDecl
*PrimaryBase
;
2228 /// \brief The class we share our vb-pointer with.
2229 const CXXRecordDecl
*SharedVBPtrBase
;
2230 /// \brief The collection of field offsets.
2231 SmallVector
<uint64_t, 16> FieldOffsets
;
2232 /// \brief Base classes and their offsets in the record.
2233 BaseOffsetsMapTy Bases
;
2234 /// \brief virtual base classes and their offsets in the record.
2235 ASTRecordLayout::VBaseOffsetsMapTy VBases
;
2236 /// \brief The number of remaining bits in our last bitfield allocation.
2237 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield is
2239 unsigned RemainingBitsInField
;
2241 /// \brief True if the last field laid out was a bitfield and was not 0
2243 bool LastFieldIsNonZeroWidthBitfield
: 1;
2244 /// \brief True if the class has its own vftable pointer.
2245 bool HasOwnVFPtr
: 1;
2246 /// \brief True if the class has a vbtable pointer.
2248 /// \brief True if the last sub-object within the type is zero sized or the
2249 /// object itself is zero sized. This *does not* count members that are not
2250 /// records. Only used for MS-ABI.
2251 bool EndsWithZeroSizedObject
: 1;
2252 /// \brief True if this class is zero sized or first base is zero sized or
2253 /// has this property. Only used for MS-ABI.
2254 bool LeadsWithZeroSizedBase
: 1;
2258 MicrosoftRecordLayoutBuilder::ElementInfo
2259 MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
2260 const ASTRecordLayout
&Layout
) {
2262 Info
.Alignment
= Layout
.getAlignment();
2263 // Respect pragma pack.
2264 if (!MaxFieldAlignment
.isZero())
2265 Info
.Alignment
= std::min(Info
.Alignment
, MaxFieldAlignment
);
2266 // Track zero-sized subobjects here where it's already available.
2267 EndsWithZeroSizedObject
= Layout
.hasZeroSizedSubObject();
2268 // Respect required alignment, this is necessary because we may have adjusted
2269 // the alignment in the case of pragam pack. Note that the required alignment
2270 // doesn't actually apply to the struct alignment at this point.
2271 Alignment
= std::max(Alignment
, Info
.Alignment
);
2272 RequiredAlignment
= std::max(RequiredAlignment
, Layout
.getRequiredAlignment());
2273 Info
.Alignment
= std::max(Info
.Alignment
, Layout
.getRequiredAlignment());
2274 Info
.Size
= Layout
.getNonVirtualSize();
2278 MicrosoftRecordLayoutBuilder::ElementInfo
2279 MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
2280 const FieldDecl
*FD
) {
2281 // Get the alignment of the field type's natural alignment, ignore any
2282 // alignment attributes.
2284 std::tie(Info
.Size
, Info
.Alignment
) =
2285 Context
.getTypeInfoInChars(FD
->getType()->getUnqualifiedDesugaredType());
2286 // Respect align attributes on the field.
2287 CharUnits FieldRequiredAlignment
=
2288 Context
.toCharUnitsFromBits(FD
->getMaxAlignment());
2289 // Respect align attributes on the type.
2290 if (Context
.isAlignmentRequired(FD
->getType()))
2291 FieldRequiredAlignment
= std::max(
2292 Context
.getTypeAlignInChars(FD
->getType()), FieldRequiredAlignment
);
2293 // Respect attributes applied to subobjects of the field.
2294 if (FD
->isBitField())
2295 // For some reason __declspec align impacts alignment rather than required
2296 // alignment when it is applied to bitfields.
2297 Info
.Alignment
= std::max(Info
.Alignment
, FieldRequiredAlignment
);
2300 FD
->getType()->getBaseElementTypeUnsafe()->getAs
<RecordType
>()) {
2301 auto const &Layout
= Context
.getASTRecordLayout(RT
->getDecl());
2302 EndsWithZeroSizedObject
= Layout
.hasZeroSizedSubObject();
2303 FieldRequiredAlignment
= std::max(FieldRequiredAlignment
,
2304 Layout
.getRequiredAlignment());
2306 // Capture required alignment as a side-effect.
2307 RequiredAlignment
= std::max(RequiredAlignment
, FieldRequiredAlignment
);
2309 // Respect pragma pack, attribute pack and declspec align
2310 if (!MaxFieldAlignment
.isZero())
2311 Info
.Alignment
= std::min(Info
.Alignment
, MaxFieldAlignment
);
2312 if (FD
->hasAttr
<PackedAttr
>())
2313 Info
.Alignment
= CharUnits::One();
2314 Info
.Alignment
= std::max(Info
.Alignment
, FieldRequiredAlignment
);
2318 void MicrosoftRecordLayoutBuilder::layout(const RecordDecl
*RD
) {
2319 // For C record layout, zero-sized records always have size 4.
2320 MinEmptyStructSize
= CharUnits::fromQuantity(4);
2321 initializeLayout(RD
);
2323 DataSize
= Size
= Size
.RoundUpToAlignment(Alignment
);
2324 RequiredAlignment
= std::max(
2325 RequiredAlignment
, Context
.toCharUnitsFromBits(RD
->getMaxAlignment()));
2329 void MicrosoftRecordLayoutBuilder::cxxLayout(const CXXRecordDecl
*RD
) {
2330 // The C++ standard says that empty structs have size 1.
2331 MinEmptyStructSize
= CharUnits::One();
2332 initializeLayout(RD
);
2333 initializeCXXLayout(RD
);
2334 layoutNonVirtualBases(RD
);
2338 if (HasOwnVFPtr
|| (HasVBPtr
&& !SharedVBPtrBase
))
2339 Alignment
= std::max(Alignment
, PointerInfo
.Alignment
);
2340 auto RoundingAlignment
= Alignment
;
2341 if (!MaxFieldAlignment
.isZero())
2342 RoundingAlignment
= std::min(RoundingAlignment
, MaxFieldAlignment
);
2343 NonVirtualSize
= Size
= Size
.RoundUpToAlignment(RoundingAlignment
);
2344 RequiredAlignment
= std::max(
2345 RequiredAlignment
, Context
.toCharUnitsFromBits(RD
->getMaxAlignment()));
2346 layoutVirtualBases(RD
);
2350 void MicrosoftRecordLayoutBuilder::initializeLayout(const RecordDecl
*RD
) {
2351 IsUnion
= RD
->isUnion();
2352 Size
= CharUnits::Zero();
2353 Alignment
= CharUnits::One();
2354 // In 64-bit mode we always perform an alignment step after laying out vbases.
2355 // In 32-bit mode we do not. The check to see if we need to perform alignment
2356 // checks the RequiredAlignment field and performs alignment if it isn't 0.
2357 RequiredAlignment
= Context
.getTargetInfo().getPointerWidth(0) == 64 ?
2358 CharUnits::One() : CharUnits::Zero();
2359 // Compute the maximum field alignment.
2360 MaxFieldAlignment
= CharUnits::Zero();
2361 // Honor the default struct packing maximum alignment flag.
2362 if (unsigned DefaultMaxFieldAlignment
= Context
.getLangOpts().PackStruct
)
2363 MaxFieldAlignment
= CharUnits::fromQuantity(DefaultMaxFieldAlignment
);
2364 // Honor the packing attribute. The MS-ABI ignores pragma pack if its larger
2365 // than the pointer size.
2366 if (const MaxFieldAlignmentAttr
*MFAA
= RD
->getAttr
<MaxFieldAlignmentAttr
>()){
2367 unsigned PackedAlignment
= MFAA
->getAlignment();
2368 if (PackedAlignment
<= Context
.getTargetInfo().getPointerWidth(0))
2369 MaxFieldAlignment
= Context
.toCharUnitsFromBits(PackedAlignment
);
2371 // Packed attribute forces max field alignment to be 1.
2372 if (RD
->hasAttr
<PackedAttr
>())
2373 MaxFieldAlignment
= CharUnits::One();
2377 MicrosoftRecordLayoutBuilder::initializeCXXLayout(const CXXRecordDecl
*RD
) {
2378 EndsWithZeroSizedObject
= false;
2379 LeadsWithZeroSizedBase
= false;
2380 HasOwnVFPtr
= false;
2382 PrimaryBase
= nullptr;
2383 SharedVBPtrBase
= nullptr;
2384 // Calculate pointer size and alignment. These are used for vfptr and vbprt
2387 Context
.toCharUnitsFromBits(Context
.getTargetInfo().getPointerWidth(0));
2388 PointerInfo
.Alignment
= PointerInfo
.Size
;
2389 // Respect pragma pack.
2390 if (!MaxFieldAlignment
.isZero())
2391 PointerInfo
.Alignment
= std::min(PointerInfo
.Alignment
, MaxFieldAlignment
);
2395 MicrosoftRecordLayoutBuilder::layoutNonVirtualBases(const CXXRecordDecl
*RD
) {
2396 // The MS-ABI lays out all bases that contain leading vfptrs before it lays
2397 // out any bases that do not contain vfptrs. We implement this as two passes
2398 // over the bases. This approach guarantees that the primary base is laid out
2399 // first. We use these passes to calculate some additional aggregated
2400 // information about the bases, such as reqruied alignment and the presence of
2401 // zero sized members.
2402 const ASTRecordLayout
*PreviousBaseLayout
= nullptr;
2403 // Iterate through the bases and lay out the non-virtual ones.
2404 for (const CXXBaseSpecifier
&Base
: RD
->bases()) {
2405 const CXXRecordDecl
*BaseDecl
= Base
.getType()->getAsCXXRecordDecl();
2406 const ASTRecordLayout
&BaseLayout
= Context
.getASTRecordLayout(BaseDecl
);
2407 // Mark and skip virtual bases.
2408 if (Base
.isVirtual()) {
2412 // Check fo a base to share a VBPtr with.
2413 if (!SharedVBPtrBase
&& BaseLayout
.hasVBPtr()) {
2414 SharedVBPtrBase
= BaseDecl
;
2417 // Only lay out bases with extendable VFPtrs on the first pass.
2418 if (!BaseLayout
.hasExtendableVFPtr())
2420 // If we don't have a primary base, this one qualifies.
2422 PrimaryBase
= BaseDecl
;
2423 LeadsWithZeroSizedBase
= BaseLayout
.leadsWithZeroSizedBase();
2425 // Lay out the base.
2426 layoutNonVirtualBase(BaseDecl
, BaseLayout
, PreviousBaseLayout
);
2428 // Figure out if we need a fresh VFPtr for this class.
2429 if (!PrimaryBase
&& RD
->isDynamicClass())
2430 for (CXXRecordDecl::method_iterator i
= RD
->method_begin(),
2431 e
= RD
->method_end();
2432 !HasOwnVFPtr
&& i
!= e
; ++i
)
2433 HasOwnVFPtr
= i
->isVirtual() && i
->size_overridden_methods() == 0;
2434 // If we don't have a primary base then we have a leading object that could
2435 // itself lead with a zero-sized object, something we track.
2436 bool CheckLeadingLayout
= !PrimaryBase
;
2437 // Iterate through the bases and lay out the non-virtual ones.
2438 for (const CXXBaseSpecifier
&Base
: RD
->bases()) {
2439 if (Base
.isVirtual())
2441 const CXXRecordDecl
*BaseDecl
= Base
.getType()->getAsCXXRecordDecl();
2442 const ASTRecordLayout
&BaseLayout
= Context
.getASTRecordLayout(BaseDecl
);
2443 // Only lay out bases without extendable VFPtrs on the second pass.
2444 if (BaseLayout
.hasExtendableVFPtr()) {
2445 VBPtrOffset
= Bases
[BaseDecl
] + BaseLayout
.getNonVirtualSize();
2448 // If this is the first layout, check to see if it leads with a zero sized
2449 // object. If it does, so do we.
2450 if (CheckLeadingLayout
) {
2451 CheckLeadingLayout
= false;
2452 LeadsWithZeroSizedBase
= BaseLayout
.leadsWithZeroSizedBase();
2454 // Lay out the base.
2455 layoutNonVirtualBase(BaseDecl
, BaseLayout
, PreviousBaseLayout
);
2456 VBPtrOffset
= Bases
[BaseDecl
] + BaseLayout
.getNonVirtualSize();
2458 // Set our VBPtroffset if we know it at this point.
2460 VBPtrOffset
= CharUnits::fromQuantity(-1);
2461 else if (SharedVBPtrBase
) {
2462 const ASTRecordLayout
&Layout
= Context
.getASTRecordLayout(SharedVBPtrBase
);
2463 VBPtrOffset
= Bases
[SharedVBPtrBase
] + Layout
.getVBPtrOffset();
2467 void MicrosoftRecordLayoutBuilder::layoutNonVirtualBase(
2468 const CXXRecordDecl
*BaseDecl
,
2469 const ASTRecordLayout
&BaseLayout
,
2470 const ASTRecordLayout
*&PreviousBaseLayout
) {
2471 // Insert padding between two bases if the left first one is zero sized or
2472 // contains a zero sized subobject and the right is zero sized or one leads
2473 // with a zero sized base.
2474 if (PreviousBaseLayout
&& PreviousBaseLayout
->hasZeroSizedSubObject() &&
2475 BaseLayout
.leadsWithZeroSizedBase())
2477 ElementInfo Info
= getAdjustedElementInfo(BaseLayout
);
2478 CharUnits BaseOffset
= Size
.RoundUpToAlignment(Info
.Alignment
);
2479 Bases
.insert(std::make_pair(BaseDecl
, BaseOffset
));
2480 Size
= BaseOffset
+ BaseLayout
.getNonVirtualSize();
2481 PreviousBaseLayout
= &BaseLayout
;
2484 void MicrosoftRecordLayoutBuilder::layoutFields(const RecordDecl
*RD
) {
2485 LastFieldIsNonZeroWidthBitfield
= false;
2486 for (const FieldDecl
*Field
: RD
->fields())
2490 void MicrosoftRecordLayoutBuilder::layoutField(const FieldDecl
*FD
) {
2491 if (FD
->isBitField()) {
2495 LastFieldIsNonZeroWidthBitfield
= false;
2496 ElementInfo Info
= getAdjustedElementInfo(FD
);
2497 Alignment
= std::max(Alignment
, Info
.Alignment
);
2499 placeFieldAtOffset(CharUnits::Zero());
2500 Size
= std::max(Size
, Info
.Size
);
2502 CharUnits FieldOffset
= Size
.RoundUpToAlignment(Info
.Alignment
);
2503 placeFieldAtOffset(FieldOffset
);
2504 Size
= FieldOffset
+ Info
.Size
;
2508 void MicrosoftRecordLayoutBuilder::layoutBitField(const FieldDecl
*FD
) {
2509 unsigned Width
= FD
->getBitWidthValue(Context
);
2511 layoutZeroWidthBitField(FD
);
2514 ElementInfo Info
= getAdjustedElementInfo(FD
);
2515 // Clamp the bitfield to a containable size for the sake of being able
2516 // to lay them out. Sema will throw an error.
2517 if (Width
> Context
.toBits(Info
.Size
))
2518 Width
= Context
.toBits(Info
.Size
);
2519 // Check to see if this bitfield fits into an existing allocation. Note:
2520 // MSVC refuses to pack bitfields of formal types with different sizes
2521 // into the same allocation.
2522 if (!IsUnion
&& LastFieldIsNonZeroWidthBitfield
&&
2523 CurrentBitfieldSize
== Info
.Size
&& Width
<= RemainingBitsInField
) {
2524 placeFieldAtBitOffset(Context
.toBits(Size
) - RemainingBitsInField
);
2525 RemainingBitsInField
-= Width
;
2528 LastFieldIsNonZeroWidthBitfield
= true;
2529 CurrentBitfieldSize
= Info
.Size
;
2531 placeFieldAtOffset(CharUnits::Zero());
2532 Size
= std::max(Size
, Info
.Size
);
2533 // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
2535 // Allocate a new block of memory and place the bitfield in it.
2536 CharUnits FieldOffset
= Size
.RoundUpToAlignment(Info
.Alignment
);
2537 placeFieldAtOffset(FieldOffset
);
2538 Size
= FieldOffset
+ Info
.Size
;
2539 Alignment
= std::max(Alignment
, Info
.Alignment
);
2540 RemainingBitsInField
= Context
.toBits(Info
.Size
) - Width
;
2545 MicrosoftRecordLayoutBuilder::layoutZeroWidthBitField(const FieldDecl
*FD
) {
2546 // Zero-width bitfields are ignored unless they follow a non-zero-width
2548 if (!LastFieldIsNonZeroWidthBitfield
) {
2549 placeFieldAtOffset(IsUnion
? CharUnits::Zero() : Size
);
2550 // TODO: Add a Sema warning that MS ignores alignment for zero
2551 // sized bitfields that occur after zero-size bitfields or non-bitfields.
2554 LastFieldIsNonZeroWidthBitfield
= false;
2555 ElementInfo Info
= getAdjustedElementInfo(FD
);
2557 placeFieldAtOffset(CharUnits::Zero());
2558 Size
= std::max(Size
, Info
.Size
);
2559 // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
2561 // Round up the current record size to the field's alignment boundary.
2562 CharUnits FieldOffset
= Size
.RoundUpToAlignment(Info
.Alignment
);
2563 placeFieldAtOffset(FieldOffset
);
2565 Alignment
= std::max(Alignment
, Info
.Alignment
);
2569 void MicrosoftRecordLayoutBuilder::injectVBPtr(const CXXRecordDecl
*RD
) {
2570 if (!HasVBPtr
|| SharedVBPtrBase
)
2572 // Inject the VBPointer at the injection site.
2573 CharUnits InjectionSite
= VBPtrOffset
;
2574 // But before we do, make sure it's properly aligned.
2575 VBPtrOffset
= VBPtrOffset
.RoundUpToAlignment(PointerInfo
.Alignment
);
2576 // Determine where the first field should be laid out after the vbptr.
2577 CharUnits FieldStart
= VBPtrOffset
+ PointerInfo
.Size
;
2578 // Make sure that the amount we push the fields back by is a multiple of the
2580 CharUnits Offset
= (FieldStart
- InjectionSite
).RoundUpToAlignment(
2581 std::max(RequiredAlignment
, Alignment
));
2582 // Increase the size of the object and push back all fields by the offset
2585 for (uint64_t &FieldOffset
: FieldOffsets
)
2586 FieldOffset
+= Context
.toBits(Offset
);
2587 for (BaseOffsetsMapTy::value_type
&Base
: Bases
)
2588 if (Base
.second
>= InjectionSite
)
2589 Base
.second
+= Offset
;
2592 void MicrosoftRecordLayoutBuilder::injectVFPtr(const CXXRecordDecl
*RD
) {
2595 // Make sure that the amount we push the struct back by is a multiple of the
2597 CharUnits Offset
= PointerInfo
.Size
.RoundUpToAlignment(
2598 std::max(RequiredAlignment
, Alignment
));
2599 // Increase the size of the object and push back all fields, the vbptr and all
2600 // bases by the offset amount.
2602 for (uint64_t &FieldOffset
: FieldOffsets
)
2603 FieldOffset
+= Context
.toBits(Offset
);
2605 VBPtrOffset
+= Offset
;
2606 for (BaseOffsetsMapTy::value_type
&Base
: Bases
)
2607 Base
.second
+= Offset
;
2610 void MicrosoftRecordLayoutBuilder::layoutVirtualBases(const CXXRecordDecl
*RD
) {
2613 // Vtordisps are always 4 bytes (even in 64-bit mode)
2614 CharUnits VtorDispSize
= CharUnits::fromQuantity(4);
2615 CharUnits VtorDispAlignment
= VtorDispSize
;
2616 // vtordisps respect pragma pack.
2617 if (!MaxFieldAlignment
.isZero())
2618 VtorDispAlignment
= std::min(VtorDispAlignment
, MaxFieldAlignment
);
2619 // The alignment of the vtordisp is at least the required alignment of the
2620 // entire record. This requirement may be present to support vtordisp
2622 for (const CXXBaseSpecifier
&VBase
: RD
->vbases()) {
2623 const CXXRecordDecl
*BaseDecl
= VBase
.getType()->getAsCXXRecordDecl();
2624 const ASTRecordLayout
&BaseLayout
= Context
.getASTRecordLayout(BaseDecl
);
2626 std::max(RequiredAlignment
, BaseLayout
.getRequiredAlignment());
2628 VtorDispAlignment
= std::max(VtorDispAlignment
, RequiredAlignment
);
2629 // Compute the vtordisp set.
2630 llvm::SmallPtrSet
<const CXXRecordDecl
*, 2> HasVtorDispSet
;
2631 computeVtorDispSet(HasVtorDispSet
, RD
);
2632 // Iterate through the virtual bases and lay them out.
2633 const ASTRecordLayout
*PreviousBaseLayout
= nullptr;
2634 for (const CXXBaseSpecifier
&VBase
: RD
->vbases()) {
2635 const CXXRecordDecl
*BaseDecl
= VBase
.getType()->getAsCXXRecordDecl();
2636 const ASTRecordLayout
&BaseLayout
= Context
.getASTRecordLayout(BaseDecl
);
2637 bool HasVtordisp
= HasVtorDispSet
.count(BaseDecl
) > 0;
2638 // Insert padding between two bases if the left first one is zero sized or
2639 // contains a zero sized subobject and the right is zero sized or one leads
2640 // with a zero sized base. The padding between virtual bases is 4
2641 // bytes (in both 32 and 64 bits modes) and always involves rounding up to
2642 // the required alignment, we don't know why.
2643 if ((PreviousBaseLayout
&& PreviousBaseLayout
->hasZeroSizedSubObject() &&
2644 BaseLayout
.leadsWithZeroSizedBase()) || HasVtordisp
) {
2645 Size
= Size
.RoundUpToAlignment(VtorDispAlignment
) + VtorDispSize
;
2646 Alignment
= std::max(VtorDispAlignment
, Alignment
);
2648 // Insert the virtual base.
2649 ElementInfo Info
= getAdjustedElementInfo(BaseLayout
);
2650 CharUnits BaseOffset
= Size
.RoundUpToAlignment(Info
.Alignment
);
2651 VBases
.insert(std::make_pair(BaseDecl
,
2652 ASTRecordLayout::VBaseInfo(BaseOffset
, HasVtordisp
)));
2653 Size
= BaseOffset
+ BaseLayout
.getNonVirtualSize();
2654 PreviousBaseLayout
= &BaseLayout
;
2658 void MicrosoftRecordLayoutBuilder::finalizeLayout(const RecordDecl
*RD
) {
2659 // Respect required alignment. Note that in 32-bit mode Required alignment
2660 // may be 0 and cause size not to be updated.
2662 if (!RequiredAlignment
.isZero()) {
2663 Alignment
= std::max(Alignment
, RequiredAlignment
);
2664 auto RoundingAlignment
= Alignment
;
2665 if (!MaxFieldAlignment
.isZero())
2666 RoundingAlignment
= std::min(RoundingAlignment
, MaxFieldAlignment
);
2667 RoundingAlignment
= std::max(RoundingAlignment
, RequiredAlignment
);
2668 Size
= Size
.RoundUpToAlignment(RoundingAlignment
);
2670 if (Size
.isZero()) {
2671 EndsWithZeroSizedObject
= true;
2672 LeadsWithZeroSizedBase
= true;
2673 // Zero-sized structures have size equal to their alignment if a
2674 // __declspec(align) came into play.
2675 if (RequiredAlignment
>= MinEmptyStructSize
)
2678 Size
= MinEmptyStructSize
;
2682 // Recursively walks the non-virtual bases of a class and determines if any of
2683 // them are in the bases with overridden methods set.
2685 RequiresVtordisp(const llvm::SmallPtrSetImpl
<const CXXRecordDecl
*> &
2686 BasesWithOverriddenMethods
,
2687 const CXXRecordDecl
*RD
) {
2688 if (BasesWithOverriddenMethods
.count(RD
))
2690 // If any of a virtual bases non-virtual bases (recursively) requires a
2691 // vtordisp than so does this virtual base.
2692 for (const CXXBaseSpecifier
&Base
: RD
->bases())
2693 if (!Base
.isVirtual() &&
2694 RequiresVtordisp(BasesWithOverriddenMethods
,
2695 Base
.getType()->getAsCXXRecordDecl()))
2700 void MicrosoftRecordLayoutBuilder::computeVtorDispSet(
2701 llvm::SmallPtrSetImpl
<const CXXRecordDecl
*> &HasVtordispSet
,
2702 const CXXRecordDecl
*RD
) const {
2703 // /vd2 or #pragma vtordisp(2): Always use vtordisps for virtual bases with
2705 if (RD
->getMSVtorDispMode() == MSVtorDispAttr::ForVFTable
) {
2706 for (const CXXBaseSpecifier
&Base
: RD
->vbases()) {
2707 const CXXRecordDecl
*BaseDecl
= Base
.getType()->getAsCXXRecordDecl();
2708 const ASTRecordLayout
&Layout
= Context
.getASTRecordLayout(BaseDecl
);
2709 if (Layout
.hasExtendableVFPtr())
2710 HasVtordispSet
.insert(BaseDecl
);
2715 // If any of our bases need a vtordisp for this type, so do we. Check our
2716 // direct bases for vtordisp requirements.
2717 for (const CXXBaseSpecifier
&Base
: RD
->bases()) {
2718 const CXXRecordDecl
*BaseDecl
= Base
.getType()->getAsCXXRecordDecl();
2719 const ASTRecordLayout
&Layout
= Context
.getASTRecordLayout(BaseDecl
);
2720 for (const auto &bi
: Layout
.getVBaseOffsetsMap())
2721 if (bi
.second
.hasVtorDisp())
2722 HasVtordispSet
.insert(bi
.first
);
2724 // We don't introduce any additional vtordisps if either:
2725 // * A user declared constructor or destructor aren't declared.
2726 // * #pragma vtordisp(0) or the /vd0 flag are in use.
2727 if ((!RD
->hasUserDeclaredConstructor() && !RD
->hasUserDeclaredDestructor()) ||
2728 RD
->getMSVtorDispMode() == MSVtorDispAttr::Never
)
2730 // /vd1 or #pragma vtordisp(1): Try to guess based on whether we think it's
2731 // possible for a partially constructed object with virtual base overrides to
2732 // escape a non-trivial constructor.
2733 assert(RD
->getMSVtorDispMode() == MSVtorDispAttr::ForVBaseOverride
);
2734 // Compute a set of base classes which define methods we override. A virtual
2735 // base in this set will require a vtordisp. A virtual base that transitively
2736 // contains one of these bases as a non-virtual base will also require a
2738 llvm::SmallPtrSet
<const CXXMethodDecl
*, 8> Work
;
2739 llvm::SmallPtrSet
<const CXXRecordDecl
*, 2> BasesWithOverriddenMethods
;
2740 // Seed the working set with our non-destructor, non-pure virtual methods.
2741 for (const CXXMethodDecl
*MD
: RD
->methods())
2742 if (MD
->isVirtual() && !isa
<CXXDestructorDecl
>(MD
) && !MD
->isPure())
2744 while (!Work
.empty()) {
2745 const CXXMethodDecl
*MD
= *Work
.begin();
2746 CXXMethodDecl::method_iterator i
= MD
->begin_overridden_methods(),
2747 e
= MD
->end_overridden_methods();
2748 // If a virtual method has no-overrides it lives in its parent's vtable.
2750 BasesWithOverriddenMethods
.insert(MD
->getParent());
2753 // We've finished processing this element, remove it from the working set.
2756 // For each of our virtual bases, check if it is in the set of overridden
2757 // bases or if it transitively contains a non-virtual base that is.
2758 for (const CXXBaseSpecifier
&Base
: RD
->vbases()) {
2759 const CXXRecordDecl
*BaseDecl
= Base
.getType()->getAsCXXRecordDecl();
2760 if (!HasVtordispSet
.count(BaseDecl
) &&
2761 RequiresVtordisp(BasesWithOverriddenMethods
, BaseDecl
))
2762 HasVtordispSet
.insert(BaseDecl
);
2766 /// \brief Get or compute information about the layout of the specified record
2767 /// (struct/union/class), which indicates its size and field position
2769 const ASTRecordLayout
*
2770 ASTContext::BuildMicrosoftASTRecordLayout(const RecordDecl
*D
) const {
2771 MicrosoftRecordLayoutBuilder
Builder(*this);
2772 if (const CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(D
)) {
2773 Builder
.cxxLayout(RD
);
2774 return new (*this) ASTRecordLayout(
2775 *this, Builder
.Size
, Builder
.Alignment
, Builder
.RequiredAlignment
,
2776 Builder
.HasOwnVFPtr
,
2777 Builder
.HasOwnVFPtr
|| Builder
.PrimaryBase
,
2778 Builder
.VBPtrOffset
, Builder
.NonVirtualSize
, Builder
.FieldOffsets
.data(),
2779 Builder
.FieldOffsets
.size(), Builder
.NonVirtualSize
,
2780 Builder
.Alignment
, CharUnits::Zero(), Builder
.PrimaryBase
,
2781 false, Builder
.SharedVBPtrBase
,
2782 Builder
.EndsWithZeroSizedObject
, Builder
.LeadsWithZeroSizedBase
,
2783 Builder
.Bases
, Builder
.VBases
);
2786 return new (*this) ASTRecordLayout(
2787 *this, Builder
.Size
, Builder
.Alignment
, Builder
.RequiredAlignment
,
2788 Builder
.Size
, Builder
.FieldOffsets
.data(), Builder
.FieldOffsets
.size());
2792 /// getASTRecordLayout - Get or compute information about the layout of the
2793 /// specified record (struct/union/class), which indicates its size and field
2794 /// position information.
2795 const ASTRecordLayout
&
2796 ASTContext::getASTRecordLayout(const RecordDecl
*D
) const {
2797 // These asserts test different things. A record has a definition
2798 // as soon as we begin to parse the definition. That definition is
2799 // not a complete definition (which is what isDefinition() tests)
2800 // until we *finish* parsing the definition.
2802 if (D
->hasExternalLexicalStorage() && !D
->getDefinition())
2803 getExternalSource()->CompleteType(const_cast<RecordDecl
*>(D
));
2805 D
= D
->getDefinition();
2806 assert(D
&& "Cannot get layout of forward declarations!");
2807 assert(!D
->isInvalidDecl() && "Cannot get layout of invalid decl!");
2808 assert(D
->isCompleteDefinition() && "Cannot layout type before complete!");
2810 // Look up this layout, if already laid out, return what we have.
2811 // Note that we can't save a reference to the entry because this function
2813 const ASTRecordLayout
*Entry
= ASTRecordLayouts
[D
];
2814 if (Entry
) return *Entry
;
2816 const ASTRecordLayout
*NewEntry
= nullptr;
2818 if (isMsLayout(D
) && !D
->getASTContext().getExternalSource()) {
2819 NewEntry
= BuildMicrosoftASTRecordLayout(D
);
2820 } else if (const CXXRecordDecl
*RD
= dyn_cast
<CXXRecordDecl
>(D
)) {
2821 EmptySubobjectMap
EmptySubobjects(*this, RD
);
2822 RecordLayoutBuilder
Builder(*this, &EmptySubobjects
);
2825 // In certain situations, we are allowed to lay out objects in the
2826 // tail-padding of base classes. This is ABI-dependent.
2827 // FIXME: this should be stored in the record layout.
2828 bool skipTailPadding
=
2829 mustSkipTailPadding(getTargetInfo().getCXXABI(), cast
<CXXRecordDecl
>(D
));
2831 // FIXME: This should be done in FinalizeLayout.
2832 CharUnits DataSize
=
2833 skipTailPadding
? Builder
.getSize() : Builder
.getDataSize();
2834 CharUnits NonVirtualSize
=
2835 skipTailPadding
? DataSize
: Builder
.NonVirtualSize
;
2837 new (*this) ASTRecordLayout(*this, Builder
.getSize(),
2839 /*RequiredAlignment : used by MS-ABI)*/
2841 Builder
.HasOwnVFPtr
,
2842 RD
->isDynamicClass(),
2843 CharUnits::fromQuantity(-1),
2845 Builder
.FieldOffsets
.data(),
2846 Builder
.FieldOffsets
.size(),
2848 Builder
.NonVirtualAlignment
,
2849 EmptySubobjects
.SizeOfLargestEmptySubobject
,
2850 Builder
.PrimaryBase
,
2851 Builder
.PrimaryBaseIsVirtual
,
2852 nullptr, false, false,
2853 Builder
.Bases
, Builder
.VBases
);
2855 RecordLayoutBuilder
Builder(*this, /*EmptySubobjects=*/nullptr);
2859 new (*this) ASTRecordLayout(*this, Builder
.getSize(),
2861 /*RequiredAlignment : used by MS-ABI)*/
2864 Builder
.FieldOffsets
.data(),
2865 Builder
.FieldOffsets
.size());
2868 ASTRecordLayouts
[D
] = NewEntry
;
2870 if (getLangOpts().DumpRecordLayouts
) {
2871 llvm::outs() << "\n*** Dumping AST Record Layout\n";
2872 DumpRecordLayout(D
, llvm::outs(), getLangOpts().DumpRecordLayoutsSimple
);
2878 const CXXMethodDecl
*ASTContext::getCurrentKeyFunction(const CXXRecordDecl
*RD
) {
2879 if (!getTargetInfo().getCXXABI().hasKeyFunctions())
2882 assert(RD
->getDefinition() && "Cannot get key function for forward decl!");
2883 RD
= cast
<CXXRecordDecl
>(RD
->getDefinition());
2886 // 1) computing the key function might trigger deserialization, which might
2887 // invalidate iterators into KeyFunctions
2888 // 2) 'get' on the LazyDeclPtr might also trigger deserialization and
2889 // invalidate the LazyDeclPtr within the map itself
2890 LazyDeclPtr Entry
= KeyFunctions
[RD
];
2891 const Decl
*Result
=
2892 Entry
? Entry
.get(getExternalSource()) : computeKeyFunction(*this, RD
);
2894 // Store it back if it changed.
2895 if (Entry
.isOffset() || Entry
.isValid() != bool(Result
))
2896 KeyFunctions
[RD
] = const_cast<Decl
*>(Result
);
2898 return cast_or_null
<CXXMethodDecl
>(Result
);
2901 void ASTContext::setNonKeyFunction(const CXXMethodDecl
*Method
) {
2902 assert(Method
== Method
->getFirstDecl() &&
2903 "not working with method declaration from class definition");
2905 // Look up the cache entry. Since we're working with the first
2906 // declaration, its parent must be the class definition, which is
2907 // the correct key for the KeyFunctions hash.
2908 llvm::DenseMap
<const CXXRecordDecl
*, LazyDeclPtr
>::iterator
2909 I
= KeyFunctions
.find(Method
->getParent());
2911 // If it's not cached, there's nothing to do.
2912 if (I
== KeyFunctions
.end()) return;
2914 // If it is cached, check whether it's the target method, and if so,
2915 // remove it from the cache. Note, the call to 'get' might invalidate
2916 // the iterator and the LazyDeclPtr object within the map.
2917 LazyDeclPtr Ptr
= I
->second
;
2918 if (Ptr
.get(getExternalSource()) == Method
) {
2919 // FIXME: remember that we did this for module / chained PCH state?
2920 KeyFunctions
.erase(Method
->getParent());
2924 static uint64_t getFieldOffset(const ASTContext
&C
, const FieldDecl
*FD
) {
2925 const ASTRecordLayout
&Layout
= C
.getASTRecordLayout(FD
->getParent());
2926 return Layout
.getFieldOffset(FD
->getFieldIndex());
2929 uint64_t ASTContext::getFieldOffset(const ValueDecl
*VD
) const {
2930 uint64_t OffsetInBits
;
2931 if (const FieldDecl
*FD
= dyn_cast
<FieldDecl
>(VD
)) {
2932 OffsetInBits
= ::getFieldOffset(*this, FD
);
2934 const IndirectFieldDecl
*IFD
= cast
<IndirectFieldDecl
>(VD
);
2937 for (const NamedDecl
*ND
: IFD
->chain())
2938 OffsetInBits
+= ::getFieldOffset(*this, cast
<FieldDecl
>(ND
));
2941 return OffsetInBits
;
2944 /// getObjCLayout - Get or compute information about the layout of the
2945 /// given interface.
2947 /// \param Impl - If given, also include the layout of the interface's
2948 /// implementation. This may differ by including synthesized ivars.
2949 const ASTRecordLayout
&
2950 ASTContext::getObjCLayout(const ObjCInterfaceDecl
*D
,
2951 const ObjCImplementationDecl
*Impl
) const {
2952 // Retrieve the definition
2953 if (D
->hasExternalLexicalStorage() && !D
->getDefinition())
2954 getExternalSource()->CompleteType(const_cast<ObjCInterfaceDecl
*>(D
));
2955 D
= D
->getDefinition();
2956 assert(D
&& D
->isThisDeclarationADefinition() && "Invalid interface decl!");
2958 // Look up this layout, if already laid out, return what we have.
2959 const ObjCContainerDecl
*Key
=
2960 Impl
? (const ObjCContainerDecl
*) Impl
: (const ObjCContainerDecl
*) D
;
2961 if (const ASTRecordLayout
*Entry
= ObjCLayouts
[Key
])
2964 // Add in synthesized ivar count if laying out an implementation.
2966 unsigned SynthCount
= CountNonClassIvars(D
);
2967 // If there aren't any sythesized ivars then reuse the interface
2968 // entry. Note we can't cache this because we simply free all
2969 // entries later; however we shouldn't look up implementations
2971 if (SynthCount
== 0)
2972 return getObjCLayout(D
, nullptr);
2975 RecordLayoutBuilder
Builder(*this, /*EmptySubobjects=*/nullptr);
2978 const ASTRecordLayout
*NewEntry
=
2979 new (*this) ASTRecordLayout(*this, Builder
.getSize(),
2981 /*RequiredAlignment : used by MS-ABI)*/
2983 Builder
.getDataSize(),
2984 Builder
.FieldOffsets
.data(),
2985 Builder
.FieldOffsets
.size());
2987 ObjCLayouts
[Key
] = NewEntry
;
2992 static void PrintOffset(raw_ostream
&OS
,
2993 CharUnits Offset
, unsigned IndentLevel
) {
2994 OS
<< llvm::format("%4" PRId64
" | ", (int64_t)Offset
.getQuantity());
2995 OS
.indent(IndentLevel
* 2);
2998 static void PrintIndentNoOffset(raw_ostream
&OS
, unsigned IndentLevel
) {
3000 OS
.indent(IndentLevel
* 2);
3003 static void DumpCXXRecordLayout(raw_ostream
&OS
,
3004 const CXXRecordDecl
*RD
, const ASTContext
&C
,
3006 unsigned IndentLevel
,
3007 const char* Description
,
3008 bool IncludeVirtualBases
) {
3009 const ASTRecordLayout
&Layout
= C
.getASTRecordLayout(RD
);
3011 PrintOffset(OS
, Offset
, IndentLevel
);
3012 OS
<< C
.getTypeDeclType(const_cast<CXXRecordDecl
*>(RD
)).getAsString();
3014 OS
<< ' ' << Description
;
3021 const CXXRecordDecl
*PrimaryBase
= Layout
.getPrimaryBase();
3022 bool HasOwnVFPtr
= Layout
.hasOwnVFPtr();
3023 bool HasOwnVBPtr
= Layout
.hasOwnVBPtr();
3026 if (RD
->isDynamicClass() && !PrimaryBase
&& !isMsLayout(RD
)) {
3027 PrintOffset(OS
, Offset
, IndentLevel
);
3028 OS
<< '(' << *RD
<< " vtable pointer)\n";
3029 } else if (HasOwnVFPtr
) {
3030 PrintOffset(OS
, Offset
, IndentLevel
);
3031 // vfptr (for Microsoft C++ ABI)
3032 OS
<< '(' << *RD
<< " vftable pointer)\n";
3036 SmallVector
<const CXXRecordDecl
*, 4> Bases
;
3037 for (const CXXBaseSpecifier
&Base
: RD
->bases()) {
3038 assert(!Base
.getType()->isDependentType() &&
3039 "Cannot layout class with dependent bases.");
3040 if (!Base
.isVirtual())
3041 Bases
.push_back(Base
.getType()->getAsCXXRecordDecl());
3044 // Sort nvbases by offset.
3045 std::stable_sort(Bases
.begin(), Bases
.end(),
3046 [&](const CXXRecordDecl
*L
, const CXXRecordDecl
*R
) {
3047 return Layout
.getBaseClassOffset(L
) < Layout
.getBaseClassOffset(R
);
3050 // Dump (non-virtual) bases
3051 for (const CXXRecordDecl
*Base
: Bases
) {
3052 CharUnits BaseOffset
= Offset
+ Layout
.getBaseClassOffset(Base
);
3053 DumpCXXRecordLayout(OS
, Base
, C
, BaseOffset
, IndentLevel
,
3054 Base
== PrimaryBase
? "(primary base)" : "(base)",
3055 /*IncludeVirtualBases=*/false);
3058 // vbptr (for Microsoft C++ ABI)
3060 PrintOffset(OS
, Offset
+ Layout
.getVBPtrOffset(), IndentLevel
);
3061 OS
<< '(' << *RD
<< " vbtable pointer)\n";
3065 uint64_t FieldNo
= 0;
3066 for (CXXRecordDecl::field_iterator I
= RD
->field_begin(),
3067 E
= RD
->field_end(); I
!= E
; ++I
, ++FieldNo
) {
3068 const FieldDecl
&Field
= **I
;
3069 CharUnits FieldOffset
= Offset
+
3070 C
.toCharUnitsFromBits(Layout
.getFieldOffset(FieldNo
));
3072 if (const CXXRecordDecl
*D
= Field
.getType()->getAsCXXRecordDecl()) {
3073 DumpCXXRecordLayout(OS
, D
, C
, FieldOffset
, IndentLevel
,
3074 Field
.getName().data(),
3075 /*IncludeVirtualBases=*/true);
3079 PrintOffset(OS
, FieldOffset
, IndentLevel
);
3080 OS
<< Field
.getType().getAsString() << ' ' << Field
<< '\n';
3083 if (!IncludeVirtualBases
)
3086 // Dump virtual bases.
3087 const ASTRecordLayout::VBaseOffsetsMapTy
&vtordisps
=
3088 Layout
.getVBaseOffsetsMap();
3089 for (const CXXBaseSpecifier
&Base
: RD
->vbases()) {
3090 assert(Base
.isVirtual() && "Found non-virtual class!");
3091 const CXXRecordDecl
*VBase
= Base
.getType()->getAsCXXRecordDecl();
3093 CharUnits VBaseOffset
= Offset
+ Layout
.getVBaseClassOffset(VBase
);
3095 if (vtordisps
.find(VBase
)->second
.hasVtorDisp()) {
3096 PrintOffset(OS
, VBaseOffset
- CharUnits::fromQuantity(4), IndentLevel
);
3097 OS
<< "(vtordisp for vbase " << *VBase
<< ")\n";
3100 DumpCXXRecordLayout(OS
, VBase
, C
, VBaseOffset
, IndentLevel
,
3101 VBase
== PrimaryBase
?
3102 "(primary virtual base)" : "(virtual base)",
3103 /*IncludeVirtualBases=*/false);
3106 PrintIndentNoOffset(OS
, IndentLevel
- 1);
3107 OS
<< "[sizeof=" << Layout
.getSize().getQuantity();
3108 if (!isMsLayout(RD
))
3109 OS
<< ", dsize=" << Layout
.getDataSize().getQuantity();
3110 OS
<< ", align=" << Layout
.getAlignment().getQuantity() << '\n';
3112 PrintIndentNoOffset(OS
, IndentLevel
- 1);
3113 OS
<< " nvsize=" << Layout
.getNonVirtualSize().getQuantity();
3114 OS
<< ", nvalign=" << Layout
.getNonVirtualAlignment().getQuantity() << "]\n";
3117 void ASTContext::DumpRecordLayout(const RecordDecl
*RD
,
3119 bool Simple
) const {
3120 const ASTRecordLayout
&Info
= getASTRecordLayout(RD
);
3122 if (const CXXRecordDecl
*CXXRD
= dyn_cast
<CXXRecordDecl
>(RD
))
3124 return DumpCXXRecordLayout(OS
, CXXRD
, *this, CharUnits(), 0, nullptr,
3125 /*IncludeVirtualBases=*/true);
3127 OS
<< "Type: " << getTypeDeclType(RD
).getAsString() << "\n";
3133 OS
<< "<ASTRecordLayout\n";
3134 OS
<< " Size:" << toBits(Info
.getSize()) << "\n";
3135 if (!isMsLayout(RD
))
3136 OS
<< " DataSize:" << toBits(Info
.getDataSize()) << "\n";
3137 OS
<< " Alignment:" << toBits(Info
.getAlignment()) << "\n";
3138 OS
<< " FieldOffsets: [";
3139 for (unsigned i
= 0, e
= Info
.getFieldCount(); i
!= e
; ++i
) {
3141 OS
<< Info
.getFieldOffset(i
);