blob: 390c8e049c308b0aadfe4b5e44444133d695436c [file] [log] [blame]
Anders Carlsson35a36eb2010-05-26 05:41:04 +00001//=== RecordLayoutBuilder.cpp - Helper class for building record layouts ---==//
Anders Carlsson79474332009-07-18 20:20:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Chandler Carruth3a022472012-12-04 09:13:33 +000010#include "clang/AST/RecordLayout.h"
Benjamin Kramer2ef30312012-07-04 18:45:14 +000011#include "clang/AST/ASTContext.h"
Anders Carlsson79474332009-07-18 20:20:21 +000012#include "clang/AST/Attr.h"
Anders Carlsson5adde292010-11-24 22:55:48 +000013#include "clang/AST/CXXInheritance.h"
Anders Carlsson79474332009-07-18 20:20:21 +000014#include "clang/AST/Decl.h"
Anders Carlsson6d9f6f32009-07-19 00:18:47 +000015#include "clang/AST/DeclCXX.h"
Anders Carlsson4f516282009-07-18 20:50:59 +000016#include "clang/AST/DeclObjC.h"
Anders Carlsson79474332009-07-18 20:20:21 +000017#include "clang/AST/Expr.h"
Anders Carlsson79474332009-07-18 20:20:21 +000018#include "clang/Basic/TargetInfo.h"
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +000019#include "clang/Sema/SemaDiagnostic.h"
Daniel Dunbaraa423af2010-04-08 02:59:49 +000020#include "llvm/ADT/SmallSet.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000021#include "llvm/Support/Format.h"
22#include "llvm/Support/MathExtras.h"
Anders Carlsson79474332009-07-18 20:20:21 +000023
24using namespace clang;
25
Benjamin Kramerc7656cd2010-05-26 09:58:31 +000026namespace {
Anders Carlssonf58de112010-05-26 15:32:58 +000027
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000028/// BaseSubobjectInfo - Represents a single base subobject in a complete class.
29/// For a class hierarchy like
30///
31/// class A { };
32/// class B : A { };
33/// class C : A, B { };
34///
35/// The BaseSubobjectInfo graph for C will have three BaseSubobjectInfo
36/// instances, one for B and two for A.
37///
38/// If a base is virtual, it will only have one BaseSubobjectInfo allocated.
39struct BaseSubobjectInfo {
40 /// Class - The class for this base info.
Anders Carlsson056818f2010-05-28 21:13:31 +000041 const CXXRecordDecl *Class;
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000042
43 /// IsVirtual - Whether the BaseInfo represents a virtual base or not.
Anders Carlsson056818f2010-05-28 21:13:31 +000044 bool IsVirtual;
45
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000046 /// Bases - Information about the base subobjects.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000047 SmallVector<BaseSubobjectInfo*, 4> Bases;
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000048
Anders Carlssone3c24c72010-05-29 17:35:14 +000049 /// PrimaryVirtualBaseInfo - Holds the base info for the primary virtual base
50 /// of this base info (if one exists).
51 BaseSubobjectInfo *PrimaryVirtualBaseInfo;
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000052
53 // FIXME: Document.
54 const BaseSubobjectInfo *Derived;
Anders Carlsson056818f2010-05-28 21:13:31 +000055};
56
Reid Kleckner8b6d0342015-02-25 19:17:45 +000057/// \brief Externally provided layout. Typically used when the AST source, such
58/// as DWARF, lacks all the information that was available at compile time, such
59/// as alignment attributes on fields and pragmas in effect.
60struct ExternalLayout {
61 ExternalLayout() : Size(0), Align(0) {}
62
63 /// \brief Overall record size in bits.
64 uint64_t Size;
65
66 /// \brief Overall record alignment in bits.
67 uint64_t Align;
68
69 /// \brief Record field offsets in bits.
70 llvm::DenseMap<const FieldDecl *, uint64_t> FieldOffsets;
71
72 /// \brief Direct, non-virtual base offsets.
73 llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsets;
74
75 /// \brief Virtual base offsets.
76 llvm::DenseMap<const CXXRecordDecl *, CharUnits> VirtualBaseOffsets;
77
78 /// Get the offset of the given field. The external source must provide
79 /// entries for all fields in the record.
80 uint64_t getExternalFieldOffset(const FieldDecl *FD) {
81 assert(FieldOffsets.count(FD) &&
82 "Field does not have an external offset");
83 return FieldOffsets[FD];
84 }
85
86 bool getExternalNVBaseOffset(const CXXRecordDecl *RD, CharUnits &BaseOffset) {
87 auto Known = BaseOffsets.find(RD);
88 if (Known == BaseOffsets.end())
89 return false;
90 BaseOffset = Known->second;
91 return true;
92 }
93
94 bool getExternalVBaseOffset(const CXXRecordDecl *RD, CharUnits &BaseOffset) {
95 auto Known = VirtualBaseOffsets.find(RD);
96 if (Known == VirtualBaseOffsets.end())
97 return false;
98 BaseOffset = Known->second;
99 return true;
100 }
101};
102
Anders Carlssonf58de112010-05-26 15:32:58 +0000103/// EmptySubobjectMap - Keeps track of which empty subobjects exist at different
104/// offsets while laying out a C++ class.
105class EmptySubobjectMap {
Jay Foad39c79802011-01-12 09:06:06 +0000106 const ASTContext &Context;
Anders Carlsson233e2722010-10-31 21:54:55 +0000107 uint64_t CharWidth;
108
Anders Carlssonf58de112010-05-26 15:32:58 +0000109 /// Class - The class whose empty entries we're keeping track of.
110 const CXXRecordDecl *Class;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000111
Anders Carlsson439edd12010-05-27 05:41:06 +0000112 /// EmptyClassOffsets - A map from offsets to empty record decls.
Benjamin Kramer834652a2014-05-03 18:44:26 +0000113 typedef llvm::TinyPtrVector<const CXXRecordDecl *> ClassVectorTy;
Anders Carlssonf8f756d2010-10-31 21:22:43 +0000114 typedef llvm::DenseMap<CharUnits, ClassVectorTy> EmptyClassOffsetsMapTy;
Anders Carlsson439edd12010-05-27 05:41:06 +0000115 EmptyClassOffsetsMapTy EmptyClassOffsets;
116
Anders Carlssoncc5de092010-06-08 15:56:03 +0000117 /// MaxEmptyClassOffset - The highest offset known to contain an empty
118 /// base subobject.
Anders Carlsson725190f2010-10-31 21:39:24 +0000119 CharUnits MaxEmptyClassOffset;
Anders Carlssoncc5de092010-06-08 15:56:03 +0000120
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000121 /// ComputeEmptySubobjectSizes - Compute the size of the largest base or
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000122 /// member subobject that is empty.
123 void ComputeEmptySubobjectSizes();
Anders Carlsson439edd12010-05-27 05:41:06 +0000124
Anders Carlsson725190f2010-10-31 21:39:24 +0000125 void AddSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000126
Anders Carlssona7f3cdb2010-05-28 21:24:37 +0000127 void UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000128 CharUnits Offset, bool PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +0000129
Anders Carlssondb319762010-05-27 18:20:57 +0000130 void UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
131 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000132 CharUnits Offset);
133 void UpdateEmptyFieldSubobjects(const FieldDecl *FD, CharUnits Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000134
Anders Carlssoncc5de092010-06-08 15:56:03 +0000135 /// AnyEmptySubobjectsBeyondOffset - Returns whether there are any empty
136 /// subobjects beyond the given offset.
Anders Carlsson725190f2010-10-31 21:39:24 +0000137 bool AnyEmptySubobjectsBeyondOffset(CharUnits Offset) const {
Anders Carlssoncc5de092010-06-08 15:56:03 +0000138 return Offset <= MaxEmptyClassOffset;
139 }
140
Anders Carlsson233e2722010-10-31 21:54:55 +0000141 CharUnits
142 getFieldOffset(const ASTRecordLayout &Layout, unsigned FieldNo) const {
143 uint64_t FieldOffset = Layout.getFieldOffset(FieldNo);
144 assert(FieldOffset % CharWidth == 0 &&
145 "Field offset not at char boundary!");
146
Ken Dyck7c4026b2011-01-24 01:28:50 +0000147 return Context.toCharUnitsFromBits(FieldOffset);
Anders Carlssonf8f756d2010-10-31 21:22:43 +0000148 }
Anders Carlssonf8f756d2010-10-31 21:22:43 +0000149
Charles Davisc2c576a2010-08-19 00:55:19 +0000150protected:
Anders Carlsson725190f2010-10-31 21:39:24 +0000151 bool CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
152 CharUnits Offset) const;
Charles Davisc2c576a2010-08-19 00:55:19 +0000153
154 bool CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000155 CharUnits Offset);
Charles Davisc2c576a2010-08-19 00:55:19 +0000156
157 bool CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
158 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000159 CharUnits Offset) const;
Charles Davisc2c576a2010-08-19 00:55:19 +0000160 bool CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
Anders Carlsson233e2722010-10-31 21:54:55 +0000161 CharUnits Offset) const;
Charles Davisc2c576a2010-08-19 00:55:19 +0000162
Anders Carlssonf58de112010-05-26 15:32:58 +0000163public:
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000164 /// This holds the size of the largest empty subobject (either a base
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000165 /// or a member). Will be zero if the record being built doesn't contain
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000166 /// any empty classes.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000167 CharUnits SizeOfLargestEmptySubobject;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000168
Jay Foad39c79802011-01-12 09:06:06 +0000169 EmptySubobjectMap(const ASTContext &Context, const CXXRecordDecl *Class)
Anders Carlsson28466ab2010-10-31 22:13:23 +0000170 : Context(Context), CharWidth(Context.getCharWidth()), Class(Class) {
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000171 ComputeEmptySubobjectSizes();
172 }
173
174 /// CanPlaceBaseAtOffset - Return whether the given base class can be placed
175 /// at the given offset.
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000176 /// Returns false if placing the record will result in two components
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000177 /// (direct or indirect) of the same type having the same offset.
Anders Carlssoncc5de092010-06-08 15:56:03 +0000178 bool CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000179 CharUnits Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000180
181 /// CanPlaceFieldAtOffset - Return whether a field can be placed at the given
182 /// offset.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000183 bool CanPlaceFieldAtOffset(const FieldDecl *FD, CharUnits Offset);
Anders Carlssonf58de112010-05-26 15:32:58 +0000184};
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000185
186void EmptySubobjectMap::ComputeEmptySubobjectSizes() {
187 // Check the bases.
David Majnemerc964b4b2014-07-16 06:04:00 +0000188 for (const CXXBaseSpecifier &Base : Class->bases()) {
189 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000190
Anders Carlsson28466ab2010-10-31 22:13:23 +0000191 CharUnits EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000192 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
193 if (BaseDecl->isEmpty()) {
194 // If the class decl is empty, get its size.
Ken Dyckc8ae5502011-02-09 01:59:34 +0000195 EmptySize = Layout.getSize();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000196 } else {
197 // Otherwise, we get the largest empty subobject for the decl.
198 EmptySize = Layout.getSizeOfLargestEmptySubobject();
199 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000200
Anders Carlsson28466ab2010-10-31 22:13:23 +0000201 if (EmptySize > SizeOfLargestEmptySubobject)
202 SizeOfLargestEmptySubobject = EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000203 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000204
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000205 // Check the fields.
David Majnemerc964b4b2014-07-16 06:04:00 +0000206 for (const FieldDecl *FD : Class->fields()) {
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000207 const RecordType *RT =
David Majnemerc964b4b2014-07-16 06:04:00 +0000208 Context.getBaseElementType(FD->getType())->getAs<RecordType>();
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000209
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000210 // We only care about record types.
211 if (!RT)
212 continue;
213
Anders Carlsson28466ab2010-10-31 22:13:23 +0000214 CharUnits EmptySize;
Reid Klecknercd612ab2014-04-11 16:57:42 +0000215 const CXXRecordDecl *MemberDecl = RT->getAsCXXRecordDecl();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000216 const ASTRecordLayout &Layout = Context.getASTRecordLayout(MemberDecl);
217 if (MemberDecl->isEmpty()) {
218 // If the class decl is empty, get its size.
Ken Dyckc8ae5502011-02-09 01:59:34 +0000219 EmptySize = Layout.getSize();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000220 } else {
221 // Otherwise, we get the largest empty subobject for the decl.
222 EmptySize = Layout.getSizeOfLargestEmptySubobject();
223 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000224
Anders Carlsson28466ab2010-10-31 22:13:23 +0000225 if (EmptySize > SizeOfLargestEmptySubobject)
226 SizeOfLargestEmptySubobject = EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000227 }
228}
229
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000230bool
Anders Carlssondb319762010-05-27 18:20:57 +0000231EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
Anders Carlsson725190f2010-10-31 21:39:24 +0000232 CharUnits Offset) const {
Anders Carlssondb319762010-05-27 18:20:57 +0000233 // We only need to check empty bases.
234 if (!RD->isEmpty())
235 return true;
236
Anders Carlsson725190f2010-10-31 21:39:24 +0000237 EmptyClassOffsetsMapTy::const_iterator I = EmptyClassOffsets.find(Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000238 if (I == EmptyClassOffsets.end())
239 return true;
David Majnemerc964b4b2014-07-16 06:04:00 +0000240
241 const ClassVectorTy &Classes = I->second;
Anders Carlssondb319762010-05-27 18:20:57 +0000242 if (std::find(Classes.begin(), Classes.end(), RD) == Classes.end())
243 return true;
244
245 // There is already an empty class of the same type at this offset.
246 return false;
247}
248
249void EmptySubobjectMap::AddSubobjectAtOffset(const CXXRecordDecl *RD,
Anders Carlsson725190f2010-10-31 21:39:24 +0000250 CharUnits Offset) {
Anders Carlssondb319762010-05-27 18:20:57 +0000251 // We only care about empty bases.
252 if (!RD->isEmpty())
253 return;
254
Reid Kleckner369f3162013-05-14 20:30:42 +0000255 // If we have empty structures inside a union, we can assign both
Rafael Espindola7bcde192010-12-29 23:02:58 +0000256 // the same offset. Just avoid pushing them twice in the list.
David Majnemerc964b4b2014-07-16 06:04:00 +0000257 ClassVectorTy &Classes = EmptyClassOffsets[Offset];
Rafael Espindola7bcde192010-12-29 23:02:58 +0000258 if (std::find(Classes.begin(), Classes.end(), RD) != Classes.end())
259 return;
260
Anders Carlssondb319762010-05-27 18:20:57 +0000261 Classes.push_back(RD);
Anders Carlssoncc5de092010-06-08 15:56:03 +0000262
263 // Update the empty class offset.
Anders Carlsson725190f2010-10-31 21:39:24 +0000264 if (Offset > MaxEmptyClassOffset)
265 MaxEmptyClassOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000266}
267
268bool
Anders Carlsson28466ab2010-10-31 22:13:23 +0000269EmptySubobjectMap::CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
270 CharUnits Offset) {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000271 // We don't have to keep looking past the maximum offset that's known to
272 // contain an empty class.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000273 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000274 return true;
275
Anders Carlsson28466ab2010-10-31 22:13:23 +0000276 if (!CanPlaceSubobjectAtOffset(Info->Class, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000277 return false;
278
Anders Carlsson439edd12010-05-27 05:41:06 +0000279 // Traverse all non-virtual bases.
Anders Carlssona7774a62010-05-29 21:10:24 +0000280 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
David Majnemerc964b4b2014-07-16 06:04:00 +0000281 for (const BaseSubobjectInfo *Base : Info->Bases) {
Anders Carlsson439edd12010-05-27 05:41:06 +0000282 if (Base->IsVirtual)
283 continue;
284
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000285 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlsson439edd12010-05-27 05:41:06 +0000286
287 if (!CanPlaceBaseSubobjectAtOffset(Base, BaseOffset))
288 return false;
289 }
290
Anders Carlssone3c24c72010-05-29 17:35:14 +0000291 if (Info->PrimaryVirtualBaseInfo) {
292 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
Anders Carlsson439edd12010-05-27 05:41:06 +0000293
294 if (Info == PrimaryVirtualBaseInfo->Derived) {
295 if (!CanPlaceBaseSubobjectAtOffset(PrimaryVirtualBaseInfo, Offset))
296 return false;
297 }
298 }
299
Anders Carlssondb319762010-05-27 18:20:57 +0000300 // Traverse all member variables.
301 unsigned FieldNo = 0;
302 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
303 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000304 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000305 continue;
David Majnemerc964b4b2014-07-16 06:04:00 +0000306
Anders Carlsson28466ab2010-10-31 22:13:23 +0000307 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
David Blaikie40ed2972012-06-06 20:45:41 +0000308 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000309 return false;
310 }
David Majnemerc964b4b2014-07-16 06:04:00 +0000311
Anders Carlsson439edd12010-05-27 05:41:06 +0000312 return true;
313}
314
Anders Carlssona7f3cdb2010-05-28 21:24:37 +0000315void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000316 CharUnits Offset,
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000317 bool PlacingEmptyBase) {
318 if (!PlacingEmptyBase && Offset >= SizeOfLargestEmptySubobject) {
319 // We know that the only empty subobjects that can conflict with empty
320 // subobject of non-empty bases, are empty bases that can be placed at
321 // offset zero. Because of this, we only need to keep track of empty base
322 // subobjects with offsets less than the size of the largest empty
323 // subobject for our class.
324 return;
325 }
326
Anders Carlsson28466ab2010-10-31 22:13:23 +0000327 AddSubobjectAtOffset(Info->Class, Offset);
Anders Carlssona7774a62010-05-29 21:10:24 +0000328
Anders Carlsson439edd12010-05-27 05:41:06 +0000329 // Traverse all non-virtual bases.
Anders Carlssona7774a62010-05-29 21:10:24 +0000330 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
David Majnemerc964b4b2014-07-16 06:04:00 +0000331 for (const BaseSubobjectInfo *Base : Info->Bases) {
Anders Carlsson439edd12010-05-27 05:41:06 +0000332 if (Base->IsVirtual)
333 continue;
Anders Carlssona7774a62010-05-29 21:10:24 +0000334
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000335 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000336 UpdateEmptyBaseSubobjects(Base, BaseOffset, PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +0000337 }
338
Anders Carlssone3c24c72010-05-29 17:35:14 +0000339 if (Info->PrimaryVirtualBaseInfo) {
340 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
Anders Carlsson439edd12010-05-27 05:41:06 +0000341
342 if (Info == PrimaryVirtualBaseInfo->Derived)
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000343 UpdateEmptyBaseSubobjects(PrimaryVirtualBaseInfo, Offset,
344 PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +0000345 }
Anders Carlssondb319762010-05-27 18:20:57 +0000346
Anders Carlssondb319762010-05-27 18:20:57 +0000347 // Traverse all member variables.
348 unsigned FieldNo = 0;
349 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
350 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000351 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000352 continue;
Anders Carlssona7774a62010-05-29 21:10:24 +0000353
Anders Carlsson28466ab2010-10-31 22:13:23 +0000354 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
David Blaikie40ed2972012-06-06 20:45:41 +0000355 UpdateEmptyFieldSubobjects(*I, FieldOffset);
Anders Carlssondb319762010-05-27 18:20:57 +0000356 }
Anders Carlsson439edd12010-05-27 05:41:06 +0000357}
358
Anders Carlssona60b86a2010-05-29 20:49:49 +0000359bool EmptySubobjectMap::CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000360 CharUnits Offset) {
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000361 // If we know this class doesn't have any empty subobjects we don't need to
362 // bother checking.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000363 if (SizeOfLargestEmptySubobject.isZero())
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000364 return true;
365
Anders Carlsson439edd12010-05-27 05:41:06 +0000366 if (!CanPlaceBaseSubobjectAtOffset(Info, Offset))
367 return false;
Anders Carlssondb319762010-05-27 18:20:57 +0000368
369 // We are able to place the base at this offset. Make sure to update the
370 // empty base subobject map.
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000371 UpdateEmptyBaseSubobjects(Info, Offset, Info->Class->isEmpty());
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000372 return true;
373}
374
Anders Carlssondb319762010-05-27 18:20:57 +0000375bool
376EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
377 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000378 CharUnits Offset) const {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000379 // We don't have to keep looking past the maximum offset that's known to
380 // contain an empty class.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000381 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000382 return true;
383
Anders Carlsson28466ab2010-10-31 22:13:23 +0000384 if (!CanPlaceSubobjectAtOffset(RD, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000385 return false;
386
387 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
388
389 // Traverse all non-virtual bases.
David Majnemerc964b4b2014-07-16 06:04:00 +0000390 for (const CXXBaseSpecifier &Base : RD->bases()) {
391 if (Base.isVirtual())
Anders Carlssondb319762010-05-27 18:20:57 +0000392 continue;
393
David Majnemerc964b4b2014-07-16 06:04:00 +0000394 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Anders Carlssondb319762010-05-27 18:20:57 +0000395
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000396 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
Anders Carlssondb319762010-05-27 18:20:57 +0000397 if (!CanPlaceFieldSubobjectAtOffset(BaseDecl, Class, BaseOffset))
398 return false;
399 }
400
Anders Carlsson44687202010-06-08 19:09:24 +0000401 if (RD == Class) {
402 // This is the most derived class, traverse virtual bases as well.
David Majnemerc964b4b2014-07-16 06:04:00 +0000403 for (const CXXBaseSpecifier &Base : RD->vbases()) {
404 const CXXRecordDecl *VBaseDecl = Base.getType()->getAsCXXRecordDecl();
Reid Klecknercd612ab2014-04-11 16:57:42 +0000405
Anders Carlsson3f018712010-10-31 23:45:59 +0000406 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
Anders Carlsson44687202010-06-08 19:09:24 +0000407 if (!CanPlaceFieldSubobjectAtOffset(VBaseDecl, Class, VBaseOffset))
408 return false;
409 }
410 }
411
Anders Carlssondb319762010-05-27 18:20:57 +0000412 // Traverse all member variables.
413 unsigned FieldNo = 0;
414 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
415 I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000416 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000417 continue;
418
Anders Carlsson28466ab2010-10-31 22:13:23 +0000419 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
Anders Carlssondb319762010-05-27 18:20:57 +0000420
David Blaikie40ed2972012-06-06 20:45:41 +0000421 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000422 return false;
423 }
424
425 return true;
426}
427
Anders Carlsson233e2722010-10-31 21:54:55 +0000428bool
429EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
430 CharUnits Offset) const {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000431 // We don't have to keep looking past the maximum offset that's known to
432 // contain an empty class.
Anders Carlsson233e2722010-10-31 21:54:55 +0000433 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000434 return true;
435
Anders Carlssondb319762010-05-27 18:20:57 +0000436 QualType T = FD->getType();
Reid Klecknercd612ab2014-04-11 16:57:42 +0000437 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Anders Carlsson28466ab2010-10-31 22:13:23 +0000438 return CanPlaceFieldSubobjectAtOffset(RD, RD, Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000439
440 // If we have an array type we need to look at every element.
441 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
442 QualType ElemTy = Context.getBaseElementType(AT);
443 const RecordType *RT = ElemTy->getAs<RecordType>();
444 if (!RT)
445 return true;
Reid Klecknercd612ab2014-04-11 16:57:42 +0000446
447 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
Anders Carlssondb319762010-05-27 18:20:57 +0000448 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
449
450 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
Anders Carlsson233e2722010-10-31 21:54:55 +0000451 CharUnits ElementOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000452 for (uint64_t I = 0; I != NumElements; ++I) {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000453 // We don't have to keep looking past the maximum offset that's known to
454 // contain an empty class.
Anders Carlsson233e2722010-10-31 21:54:55 +0000455 if (!AnyEmptySubobjectsBeyondOffset(ElementOffset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000456 return true;
457
Anders Carlsson28466ab2010-10-31 22:13:23 +0000458 if (!CanPlaceFieldSubobjectAtOffset(RD, RD, ElementOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000459 return false;
460
Ken Dyckc8ae5502011-02-09 01:59:34 +0000461 ElementOffset += Layout.getSize();
Anders Carlssondb319762010-05-27 18:20:57 +0000462 }
463 }
464
465 return true;
466}
467
468bool
Anders Carlsson28466ab2010-10-31 22:13:23 +0000469EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl *FD,
470 CharUnits Offset) {
471 if (!CanPlaceFieldSubobjectAtOffset(FD, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000472 return false;
473
474 // We are able to place the member variable at this offset.
475 // Make sure to update the empty base subobject map.
476 UpdateEmptyFieldSubobjects(FD, Offset);
477 return true;
478}
479
480void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
481 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000482 CharUnits Offset) {
Anders Carlssonae111dc2010-06-13 17:49:16 +0000483 // We know that the only empty subobjects that can conflict with empty
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000484 // field subobjects are subobjects of empty bases that can be placed at offset
Anders Carlssonae111dc2010-06-13 17:49:16 +0000485 // zero. Because of this, we only need to keep track of empty field
486 // subobjects with offsets less than the size of the largest empty
487 // subobject for our class.
488 if (Offset >= SizeOfLargestEmptySubobject)
489 return;
490
Anders Carlsson28466ab2010-10-31 22:13:23 +0000491 AddSubobjectAtOffset(RD, Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000492
493 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
494
495 // Traverse all non-virtual bases.
David Majnemerc964b4b2014-07-16 06:04:00 +0000496 for (const CXXBaseSpecifier &Base : RD->bases()) {
497 if (Base.isVirtual())
Anders Carlssondb319762010-05-27 18:20:57 +0000498 continue;
499
David Majnemerc964b4b2014-07-16 06:04:00 +0000500 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Anders Carlssondb319762010-05-27 18:20:57 +0000501
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000502 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
Anders Carlssondb319762010-05-27 18:20:57 +0000503 UpdateEmptyFieldSubobjects(BaseDecl, Class, BaseOffset);
504 }
505
Anders Carlsson44687202010-06-08 19:09:24 +0000506 if (RD == Class) {
507 // This is the most derived class, traverse virtual bases as well.
David Majnemerc964b4b2014-07-16 06:04:00 +0000508 for (const CXXBaseSpecifier &Base : RD->vbases()) {
509 const CXXRecordDecl *VBaseDecl = Base.getType()->getAsCXXRecordDecl();
Reid Klecknercd612ab2014-04-11 16:57:42 +0000510
Anders Carlsson3f018712010-10-31 23:45:59 +0000511 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
Anders Carlsson44687202010-06-08 19:09:24 +0000512 UpdateEmptyFieldSubobjects(VBaseDecl, Class, VBaseOffset);
513 }
514 }
515
Anders Carlssondb319762010-05-27 18:20:57 +0000516 // Traverse all member variables.
517 unsigned FieldNo = 0;
518 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
519 I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000520 if (I->isBitField())
Anders Carlsson09814d32010-11-01 15:14:51 +0000521 continue;
522
Anders Carlsson28466ab2010-10-31 22:13:23 +0000523 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
Anders Carlssondb319762010-05-27 18:20:57 +0000524
David Blaikie40ed2972012-06-06 20:45:41 +0000525 UpdateEmptyFieldSubobjects(*I, FieldOffset);
Anders Carlssondb319762010-05-27 18:20:57 +0000526 }
527}
528
529void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const FieldDecl *FD,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000530 CharUnits Offset) {
Anders Carlssondb319762010-05-27 18:20:57 +0000531 QualType T = FD->getType();
Reid Klecknercd612ab2014-04-11 16:57:42 +0000532 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
Anders Carlssondb319762010-05-27 18:20:57 +0000533 UpdateEmptyFieldSubobjects(RD, RD, Offset);
534 return;
535 }
536
537 // If we have an array type we need to update every element.
538 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
539 QualType ElemTy = Context.getBaseElementType(AT);
540 const RecordType *RT = ElemTy->getAs<RecordType>();
541 if (!RT)
542 return;
Reid Klecknercd612ab2014-04-11 16:57:42 +0000543
544 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
Anders Carlssondb319762010-05-27 18:20:57 +0000545 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
546
547 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
Anders Carlsson28466ab2010-10-31 22:13:23 +0000548 CharUnits ElementOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000549
550 for (uint64_t I = 0; I != NumElements; ++I) {
Anders Carlssonae111dc2010-06-13 17:49:16 +0000551 // We know that the only empty subobjects that can conflict with empty
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000552 // field subobjects are subobjects of empty bases that can be placed at
Anders Carlssonae111dc2010-06-13 17:49:16 +0000553 // offset zero. Because of this, we only need to keep track of empty field
554 // subobjects with offsets less than the size of the largest empty
555 // subobject for our class.
556 if (ElementOffset >= SizeOfLargestEmptySubobject)
557 return;
558
Anders Carlssondb319762010-05-27 18:20:57 +0000559 UpdateEmptyFieldSubobjects(RD, RD, ElementOffset);
Ken Dyckc8ae5502011-02-09 01:59:34 +0000560 ElementOffset += Layout.getSize();
Anders Carlssondb319762010-05-27 18:20:57 +0000561 }
562 }
563}
564
John McCalle42a3362012-05-01 08:55:32 +0000565typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> ClassSetTy;
566
David Majnemer3b1c9902015-07-25 20:18:14 +0000567class ItaniumRecordLayoutBuilder {
Charles Davisc2c576a2010-08-19 00:55:19 +0000568protected:
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000569 // FIXME: Remove this and make the appropriate fields public.
570 friend class clang::ASTContext;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000571
Jay Foad39c79802011-01-12 09:06:06 +0000572 const ASTContext &Context;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000573
Anders Carlssonf58de112010-05-26 15:32:58 +0000574 EmptySubobjectMap *EmptySubobjects;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000575
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000576 /// Size - The current size of the record layout.
577 uint64_t Size;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000578
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000579 /// Alignment - The current alignment of the record layout.
Ken Dyck4731d5b2011-02-16 02:05:21 +0000580 CharUnits Alignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000581
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000582 /// \brief The alignment if attribute packed is not used.
Ken Dyck1300b3b2011-02-16 02:11:31 +0000583 CharUnits UnpackedAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000584
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000585 SmallVector<uint64_t, 16> FieldOffsets;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000586
Douglas Gregore9fc3772012-01-26 07:55:45 +0000587 /// \brief Whether the external AST source has provided a layout for this
588 /// record.
Reid Kleckner8b6d0342015-02-25 19:17:45 +0000589 unsigned UseExternalLayout : 1;
Douglas Gregor44ba7892012-01-28 00:53:29 +0000590
591 /// \brief Whether we need to infer alignment, even when we have an
592 /// externally-provided layout.
593 unsigned InferAlignment : 1;
Douglas Gregore9fc3772012-01-26 07:55:45 +0000594
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000595 /// Packed - Whether the record is packed or not.
Daniel Dunbar6da10982010-05-27 05:45:51 +0000596 unsigned Packed : 1;
597
598 unsigned IsUnion : 1;
599
600 unsigned IsMac68kAlign : 1;
Fariborz Jahanianbcb23a12011-04-26 23:52:16 +0000601
602 unsigned IsMsStruct : 1;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000603
Eli Friedman2782dac2013-06-26 20:50:34 +0000604 /// UnfilledBitsInLastUnit - If the last field laid out was a bitfield,
605 /// this contains the number of bits in the last unit that can be used for
606 /// an adjacent bitfield if necessary. The unit in question is usually
607 /// a byte, but larger units are used if IsMsStruct.
608 unsigned char UnfilledBitsInLastUnit;
609 /// LastBitfieldTypeSize - If IsMsStruct, represents the size of the type
610 /// of the previous field if it was a bitfield.
611 unsigned char LastBitfieldTypeSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000612
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000613 /// MaxFieldAlignment - The maximum allowed field alignment. This is set by
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000614 /// #pragma pack.
Ken Dyck02ced6f2011-02-17 01:49:42 +0000615 CharUnits MaxFieldAlignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000616
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000617 /// DataSize - The data size of the record being laid out.
618 uint64_t DataSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000619
Ken Dyckaf1c83f2011-02-16 01:52:01 +0000620 CharUnits NonVirtualSize;
Ken Dycka2d3dda2011-02-16 01:43:15 +0000621 CharUnits NonVirtualAlignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000622
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000623 /// PrimaryBase - the primary base class (if one exists) of the class
624 /// we're laying out.
625 const CXXRecordDecl *PrimaryBase;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000626
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000627 /// PrimaryBaseIsVirtual - Whether the primary base of the class we're laying
628 /// out is virtual.
629 bool PrimaryBaseIsVirtual;
630
John McCalle42a3362012-05-01 08:55:32 +0000631 /// HasOwnVFPtr - Whether the class provides its own vtable/vftbl
632 /// pointer, as opposed to inheriting one from a primary base class.
633 bool HasOwnVFPtr;
Eli Friedman43114f92011-10-21 22:49:56 +0000634
Yan Wangd79f3f62017-08-01 21:41:39 +0000635 /// \brief the flag of field offset changing due to packed attribute.
636 bool HasPackedField;
637
Anders Carlsson22f57202010-10-31 21:01:46 +0000638 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000639
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000640 /// Bases - base classes and their offsets in the record.
641 BaseOffsetsMapTy Bases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000642
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000643 // VBases - virtual base classes and their offsets in the record.
John McCalle42a3362012-05-01 08:55:32 +0000644 ASTRecordLayout::VBaseOffsetsMapTy VBases;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000645
646 /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are
647 /// primary base classes for some other direct or indirect base class.
Anders Carlsson5adde292010-11-24 22:55:48 +0000648 CXXIndirectPrimaryBaseSet IndirectPrimaryBases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000649
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000650 /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in
651 /// inheritance graph order. Used for determining the primary base class.
652 const CXXRecordDecl *FirstNearlyEmptyVBase;
653
654 /// VisitedVirtualBases - A set of all the visited virtual bases, used to
655 /// avoid visiting virtual bases more than once.
656 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000657
Reid Kleckner8b6d0342015-02-25 19:17:45 +0000658 /// Valid if UseExternalLayout is true.
659 ExternalLayout External;
Douglas Gregore9fc3772012-01-26 07:55:45 +0000660
David Majnemer3b1c9902015-07-25 20:18:14 +0000661 ItaniumRecordLayoutBuilder(const ASTContext &Context,
662 EmptySubobjectMap *EmptySubobjects)
663 : Context(Context), EmptySubobjects(EmptySubobjects), Size(0),
664 Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()),
665 UseExternalLayout(false), InferAlignment(false), Packed(false),
666 IsUnion(false), IsMac68kAlign(false), IsMsStruct(false),
667 UnfilledBitsInLastUnit(0), LastBitfieldTypeSize(0),
668 MaxFieldAlignment(CharUnits::Zero()), DataSize(0),
669 NonVirtualSize(CharUnits::Zero()),
670 NonVirtualAlignment(CharUnits::One()), PrimaryBase(nullptr),
671 PrimaryBaseIsVirtual(false), HasOwnVFPtr(false),
Yan Wangd79f3f62017-08-01 21:41:39 +0000672 HasPackedField(false), FirstNearlyEmptyVBase(nullptr) {}
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000673
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000674 void Layout(const RecordDecl *D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000675 void Layout(const CXXRecordDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000676 void Layout(const ObjCInterfaceDecl *D);
677
678 void LayoutFields(const RecordDecl *D);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000679 void LayoutField(const FieldDecl *D, bool InsertExtraPadding);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000680 void LayoutWideBitField(uint64_t FieldSize, uint64_t TypeSize,
681 bool FieldPacked, const FieldDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000682 void LayoutBitField(const FieldDecl *D);
John McCall0153cd32011-11-08 04:01:03 +0000683
John McCall359b8852013-01-25 22:30:49 +0000684 TargetCXXABI getCXXABI() const {
685 return Context.getTargetInfo().getCXXABI();
686 }
687
Anders Carlssone3c24c72010-05-29 17:35:14 +0000688 /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects.
689 llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator;
690
691 typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *>
692 BaseSubobjectInfoMapTy;
693
694 /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases
695 /// of the class we're laying out to their base subobject info.
696 BaseSubobjectInfoMapTy VirtualBaseInfo;
697
698 /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the
699 /// class we're laying out to their base subobject info.
700 BaseSubobjectInfoMapTy NonVirtualBaseInfo;
701
702 /// ComputeBaseSubobjectInfo - Compute the base subobject information for the
703 /// bases of the given class.
704 void ComputeBaseSubobjectInfo(const CXXRecordDecl *RD);
705
706 /// ComputeBaseSubobjectInfo - Compute the base subobject information for a
707 /// single class and all of its base classes.
708 BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
709 bool IsVirtual,
710 BaseSubobjectInfo *Derived);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000711
712 /// DeterminePrimaryBase - Determine the primary base of the given class.
713 void DeterminePrimaryBase(const CXXRecordDecl *RD);
714
715 void SelectPrimaryVBase(const CXXRecordDecl *RD);
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000716
Eli Friedman43114f92011-10-21 22:49:56 +0000717 void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign);
Charles Davisc2c576a2010-08-19 00:55:19 +0000718
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000719 /// LayoutNonVirtualBases - Determines the primary base class (if any) and
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000720 /// lays it out. Will then proceed to lay out all non-virtual base clasess.
721 void LayoutNonVirtualBases(const CXXRecordDecl *RD);
722
723 /// LayoutNonVirtualBase - Lays out a single non-virtual base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +0000724 void LayoutNonVirtualBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000725
Anders Carlssona2f8e412010-10-31 22:20:42 +0000726 void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
727 CharUnits Offset);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000728
729 /// LayoutVirtualBases - Lays out all the virtual bases.
730 void LayoutVirtualBases(const CXXRecordDecl *RD,
731 const CXXRecordDecl *MostDerivedClass);
732
733 /// LayoutVirtualBase - Lays out a single virtual base.
Warren Hunt55d8e822013-10-23 23:53:07 +0000734 void LayoutVirtualBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000735
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000736 /// LayoutBase - Will lay out a base and return the offset where it was
Anders Carlssona2f8e412010-10-31 22:20:42 +0000737 /// placed, in chars.
738 CharUnits LayoutBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000739
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000740 /// InitializeLayout - Initialize record layout for the given record decl.
Daniel Dunbar6da10982010-05-27 05:45:51 +0000741 void InitializeLayout(const Decl *D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000742
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000743 /// FinishLayout - Finalize record layout. Adjust record size based on the
744 /// alignment.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000745 void FinishLayout(const NamedDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000746
Ken Dyck85ef0432011-02-19 18:58:07 +0000747 void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment);
748 void UpdateAlignment(CharUnits NewAlignment) {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000749 UpdateAlignment(NewAlignment, NewAlignment);
750 }
751
Douglas Gregor44ba7892012-01-28 00:53:29 +0000752 /// \brief Retrieve the externally-supplied field offset for the given
753 /// field.
754 ///
755 /// \param Field The field whose offset is being queried.
756 /// \param ComputedOffset The offset that we've computed for this field.
757 uint64_t updateExternalFieldOffset(const FieldDecl *Field,
758 uint64_t ComputedOffset);
759
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000760 void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset,
761 uint64_t UnpackedOffset, unsigned UnpackedAlign,
762 bool isPacked, const FieldDecl *D);
763
764 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000765
Ken Dyckecfc7552011-02-24 01:13:28 +0000766 CharUnits getSize() const {
Ken Dyck3c215f22011-02-24 01:33:05 +0000767 assert(Size % Context.getCharWidth() == 0);
Ken Dyckecfc7552011-02-24 01:13:28 +0000768 return Context.toCharUnitsFromBits(Size);
769 }
770 uint64_t getSizeInBits() const { return Size; }
771
772 void setSize(CharUnits NewSize) { Size = Context.toBits(NewSize); }
773 void setSize(uint64_t NewSize) { Size = NewSize; }
774
Eli Friedman84d2d3a2011-09-27 19:12:27 +0000775 CharUnits getAligment() const { return Alignment; }
776
Ken Dyckecfc7552011-02-24 01:13:28 +0000777 CharUnits getDataSize() const {
Ken Dyck3c215f22011-02-24 01:33:05 +0000778 assert(DataSize % Context.getCharWidth() == 0);
Ken Dyckecfc7552011-02-24 01:13:28 +0000779 return Context.toCharUnitsFromBits(DataSize);
780 }
781 uint64_t getDataSizeInBits() const { return DataSize; }
782
783 void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); }
784 void setDataSize(uint64_t NewSize) { DataSize = NewSize; }
785
David Majnemer3b1c9902015-07-25 20:18:14 +0000786 ItaniumRecordLayoutBuilder(const ItaniumRecordLayoutBuilder &) = delete;
787 void operator=(const ItaniumRecordLayoutBuilder &) = delete;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000788};
Benjamin Kramerc7656cd2010-05-26 09:58:31 +0000789} // end anonymous namespace
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000790
David Majnemer3b1c9902015-07-25 20:18:14 +0000791void ItaniumRecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000792 for (const auto &I : RD->bases()) {
793 assert(!I.getType()->isDependentType() &&
Sebastian Redl1054fae2009-10-25 17:03:50 +0000794 "Cannot layout class with dependent bases.");
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000795
Reid Klecknercd612ab2014-04-11 16:57:42 +0000796 const CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000797
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000798 // Check if this is a nearly empty virtual base.
Aaron Ballman574705e2014-03-13 15:41:46 +0000799 if (I.isVirtual() && Context.isNearlyEmpty(Base)) {
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000800 // If it's not an indirect primary base, then we've found our primary
801 // base.
Anders Carlsson81430692009-09-22 03:02:06 +0000802 if (!IndirectPrimaryBases.count(Base)) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000803 PrimaryBase = Base;
804 PrimaryBaseIsVirtual = true;
Mike Stump6f3793b2009-08-12 21:50:08 +0000805 return;
806 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000807
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000808 // Is this the first nearly empty virtual base?
809 if (!FirstNearlyEmptyVBase)
810 FirstNearlyEmptyVBase = Base;
Mike Stump6f3793b2009-08-12 21:50:08 +0000811 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000812
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000813 SelectPrimaryVBase(Base);
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000814 if (PrimaryBase)
Zhongxing Xuec345b72010-02-15 04:28:35 +0000815 return;
Mike Stump6f3793b2009-08-12 21:50:08 +0000816 }
817}
818
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000819/// DeterminePrimaryBase - Determine the primary base of the given class.
David Majnemer3b1c9902015-07-25 20:18:14 +0000820void ItaniumRecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) {
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000821 // If the class isn't dynamic, it won't have a primary base.
822 if (!RD->isDynamicClass())
823 return;
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000824
Anders Carlsson81430692009-09-22 03:02:06 +0000825 // Compute all the primary virtual bases for all of our direct and
Mike Stump590a7c72009-08-13 23:26:06 +0000826 // indirect bases, and record all their primary virtual base classes.
Anders Carlsson5adde292010-11-24 22:55:48 +0000827 RD->getIndirectPrimaryBases(IndirectPrimaryBases);
Mike Stump590a7c72009-08-13 23:26:06 +0000828
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000829 // If the record has a dynamic base class, attempt to choose a primary base
830 // class. It is the first (in direct base class order) non-virtual dynamic
Anders Carlsson81430692009-09-22 03:02:06 +0000831 // base class, if one exists.
Aaron Ballman574705e2014-03-13 15:41:46 +0000832 for (const auto &I : RD->bases()) {
Anders Carlsson03ff3792009-11-27 22:05:05 +0000833 // Ignore virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000834 if (I.isVirtual())
Anders Carlsson03ff3792009-11-27 22:05:05 +0000835 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000836
Reid Klecknercd612ab2014-04-11 16:57:42 +0000837 const CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Anders Carlsson03ff3792009-11-27 22:05:05 +0000838
Warren Hunt55d8e822013-10-23 23:53:07 +0000839 if (Base->isDynamicClass()) {
Anders Carlsson03ff3792009-11-27 22:05:05 +0000840 // We found it.
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000841 PrimaryBase = Base;
842 PrimaryBaseIsVirtual = false;
Anders Carlsson03ff3792009-11-27 22:05:05 +0000843 return;
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000844 }
845 }
846
Eli Friedman5e9534b2011-10-18 00:55:28 +0000847 // Under the Itanium ABI, if there is no non-virtual primary base class,
848 // try to compute the primary virtual base. The primary virtual base is
849 // the first nearly empty virtual base that is not an indirect primary
850 // virtual base class, if one exists.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000851 if (RD->getNumVBases() != 0) {
852 SelectPrimaryVBase(RD);
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000853 if (PrimaryBase)
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000854 return;
855 }
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000856
Eli Friedman5e9534b2011-10-18 00:55:28 +0000857 // Otherwise, it is the first indirect primary base class, if one exists.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000858 if (FirstNearlyEmptyVBase) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000859 PrimaryBase = FirstNearlyEmptyVBase;
860 PrimaryBaseIsVirtual = true;
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000861 return;
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000862 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000863
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000864 assert(!PrimaryBase && "Should not get here with a primary base!");
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000865}
866
David Majnemer3b1c9902015-07-25 20:18:14 +0000867BaseSubobjectInfo *ItaniumRecordLayoutBuilder::ComputeBaseSubobjectInfo(
868 const CXXRecordDecl *RD, bool IsVirtual, BaseSubobjectInfo *Derived) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000869 BaseSubobjectInfo *Info;
870
871 if (IsVirtual) {
872 // Check if we already have info about this virtual base.
873 BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD];
874 if (InfoSlot) {
875 assert(InfoSlot->Class == RD && "Wrong class for virtual base info!");
876 return InfoSlot;
877 }
878
879 // We don't, create it.
880 InfoSlot = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
881 Info = InfoSlot;
882 } else {
883 Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
884 }
885
886 Info->Class = RD;
887 Info->IsVirtual = IsVirtual;
Craig Topper36250ad2014-05-12 05:36:57 +0000888 Info->Derived = nullptr;
889 Info->PrimaryVirtualBaseInfo = nullptr;
890
891 const CXXRecordDecl *PrimaryVirtualBase = nullptr;
892 BaseSubobjectInfo *PrimaryVirtualBaseInfo = nullptr;
Anders Carlssone3c24c72010-05-29 17:35:14 +0000893
894 // Check if this base has a primary virtual base.
895 if (RD->getNumVBases()) {
896 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlsson7f95cd12010-11-24 23:12:57 +0000897 if (Layout.isPrimaryBaseVirtual()) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000898 // This base does have a primary virtual base.
899 PrimaryVirtualBase = Layout.getPrimaryBase();
900 assert(PrimaryVirtualBase && "Didn't have a primary virtual base!");
901
902 // Now check if we have base subobject info about this primary base.
903 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
904
905 if (PrimaryVirtualBaseInfo) {
906 if (PrimaryVirtualBaseInfo->Derived) {
907 // We did have info about this primary base, and it turns out that it
908 // has already been claimed as a primary virtual base for another
Craig Topper36250ad2014-05-12 05:36:57 +0000909 // base.
910 PrimaryVirtualBase = nullptr;
Anders Carlssone3c24c72010-05-29 17:35:14 +0000911 } else {
912 // We can claim this base as our primary base.
913 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
914 PrimaryVirtualBaseInfo->Derived = Info;
915 }
916 }
917 }
918 }
919
920 // Now go through all direct bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000921 for (const auto &I : RD->bases()) {
922 bool IsVirtual = I.isVirtual();
Reid Klecknercd612ab2014-04-11 16:57:42 +0000923
924 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
925
Anders Carlssone3c24c72010-05-29 17:35:14 +0000926 Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info));
927 }
928
929 if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) {
930 // Traversing the bases must have created the base info for our primary
931 // virtual base.
932 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
933 assert(PrimaryVirtualBaseInfo &&
934 "Did not create a primary virtual base!");
935
936 // Claim the primary virtual base as our primary virtual base.
937 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
938 PrimaryVirtualBaseInfo->Derived = Info;
939 }
940
941 return Info;
942}
943
David Majnemer3b1c9902015-07-25 20:18:14 +0000944void ItaniumRecordLayoutBuilder::ComputeBaseSubobjectInfo(
945 const CXXRecordDecl *RD) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000946 for (const auto &I : RD->bases()) {
947 bool IsVirtual = I.isVirtual();
Anders Carlssone3c24c72010-05-29 17:35:14 +0000948
Reid Klecknercd612ab2014-04-11 16:57:42 +0000949 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
950
Anders Carlssone3c24c72010-05-29 17:35:14 +0000951 // Compute the base subobject info for this base.
Craig Topper36250ad2014-05-12 05:36:57 +0000952 BaseSubobjectInfo *Info = ComputeBaseSubobjectInfo(BaseDecl, IsVirtual,
953 nullptr);
Anders Carlssone3c24c72010-05-29 17:35:14 +0000954
955 if (IsVirtual) {
956 // ComputeBaseInfo has already added this base for us.
957 assert(VirtualBaseInfo.count(BaseDecl) &&
958 "Did not add virtual base!");
959 } else {
960 // Add the base info to the map of non-virtual bases.
961 assert(!NonVirtualBaseInfo.count(BaseDecl) &&
962 "Non-virtual base already exists!");
963 NonVirtualBaseInfo.insert(std::make_pair(BaseDecl, Info));
964 }
965 }
966}
967
David Majnemer3b1c9902015-07-25 20:18:14 +0000968void ItaniumRecordLayoutBuilder::EnsureVTablePointerAlignment(
969 CharUnits UnpackedBaseAlign) {
Eli Friedman5e9534b2011-10-18 00:55:28 +0000970 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
971
972 // The maximum field alignment overrides base align.
973 if (!MaxFieldAlignment.isZero()) {
974 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
975 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
976 }
977
978 // Round up the current record size to pointer alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +0000979 setSize(getSize().alignTo(BaseAlign));
Eli Friedman43114f92011-10-21 22:49:56 +0000980 setDataSize(getSize());
Eli Friedman5e9534b2011-10-18 00:55:28 +0000981
982 // Update the alignment.
983 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
984}
985
David Majnemer3b1c9902015-07-25 20:18:14 +0000986void ItaniumRecordLayoutBuilder::LayoutNonVirtualBases(
987 const CXXRecordDecl *RD) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000988 // Then, determine the primary base class.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000989 DeterminePrimaryBase(RD);
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000990
Anders Carlssone3c24c72010-05-29 17:35:14 +0000991 // Compute base subobject info.
992 ComputeBaseSubobjectInfo(RD);
993
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000994 // If we have a primary base class, lay it out.
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000995 if (PrimaryBase) {
996 if (PrimaryBaseIsVirtual) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000997 // If the primary virtual base was a primary virtual base of some other
998 // base class we'll have to steal it.
999 BaseSubobjectInfo *PrimaryBaseInfo = VirtualBaseInfo.lookup(PrimaryBase);
Craig Topper36250ad2014-05-12 05:36:57 +00001000 PrimaryBaseInfo->Derived = nullptr;
1001
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001002 // We have a virtual primary base, insert it as an indirect primary base.
Anders Carlssond20e7cd2010-05-26 05:20:58 +00001003 IndirectPrimaryBases.insert(PrimaryBase);
Anders Carlssonfe900962010-03-11 05:42:17 +00001004
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001005 assert(!VisitedVirtualBases.count(PrimaryBase) &&
Anders Carlssond20e7cd2010-05-26 05:20:58 +00001006 "vbase already visited!");
1007 VisitedVirtualBases.insert(PrimaryBase);
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001008
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001009 LayoutVirtualBase(PrimaryBaseInfo);
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001010 } else {
1011 BaseSubobjectInfo *PrimaryBaseInfo =
1012 NonVirtualBaseInfo.lookup(PrimaryBase);
1013 assert(PrimaryBaseInfo &&
1014 "Did not find base info for non-virtual primary base!");
1015
1016 LayoutNonVirtualBase(PrimaryBaseInfo);
1017 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001018
John McCall0153cd32011-11-08 04:01:03 +00001019 // If this class needs a vtable/vf-table and didn't get one from a
1020 // primary base, add it in now.
Warren Hunt55d8e822013-10-23 23:53:07 +00001021 } else if (RD->isDynamicClass()) {
Eli Friedman5e9534b2011-10-18 00:55:28 +00001022 assert(DataSize == 0 && "Vtable pointer must be at offset zero!");
Eli Friedman5e9534b2011-10-18 00:55:28 +00001023 CharUnits PtrWidth =
1024 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Eli Friedman43114f92011-10-21 22:49:56 +00001025 CharUnits PtrAlign =
1026 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
1027 EnsureVTablePointerAlignment(PtrAlign);
John McCalle42a3362012-05-01 08:55:32 +00001028 HasOwnVFPtr = true;
Eli Friedman5e9534b2011-10-18 00:55:28 +00001029 setSize(getSize() + PtrWidth);
1030 setDataSize(getSize());
1031 }
1032
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001033 // Now lay out the non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001034 for (const auto &I : RD->bases()) {
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001035
Benjamin Kramer273670a2013-10-25 07:40:50 +00001036 // Ignore virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001037 if (I.isVirtual())
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001038 continue;
1039
Aaron Ballman574705e2014-03-13 15:41:46 +00001040 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001041
John McCall0153cd32011-11-08 04:01:03 +00001042 // Skip the primary base, because we've already laid it out. The
1043 // !PrimaryBaseIsVirtual check is required because we might have a
1044 // non-virtual base of the same type as a primary virtual base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001045 if (BaseDecl == PrimaryBase && !PrimaryBaseIsVirtual)
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001046 continue;
1047
1048 // Lay out the base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001049 BaseSubobjectInfo *BaseInfo = NonVirtualBaseInfo.lookup(BaseDecl);
1050 assert(BaseInfo && "Did not find base info for non-virtual base!");
1051
1052 LayoutNonVirtualBase(BaseInfo);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001053 }
1054}
1055
David Majnemer3b1c9902015-07-25 20:18:14 +00001056void ItaniumRecordLayoutBuilder::LayoutNonVirtualBase(
1057 const BaseSubobjectInfo *Base) {
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001058 // Layout the base.
Anders Carlssona2f8e412010-10-31 22:20:42 +00001059 CharUnits Offset = LayoutBase(Base);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001060
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001061 // Add its base class offset.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001062 assert(!Bases.count(Base->Class) && "base offset already exists!");
Anders Carlssona2f8e412010-10-31 22:20:42 +00001063 Bases.insert(std::make_pair(Base->Class, Offset));
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001064
1065 AddPrimaryVirtualBaseOffsets(Base, Offset);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001066}
Mike Stump2b84dd32009-11-05 04:02:15 +00001067
David Majnemer3b1c9902015-07-25 20:18:14 +00001068void ItaniumRecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(
1069 const BaseSubobjectInfo *Info, CharUnits Offset) {
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001070 // This base isn't interesting, it has no virtual bases.
1071 if (!Info->Class->getNumVBases())
1072 return;
1073
1074 // First, check if we have a virtual primary base to add offsets for.
1075 if (Info->PrimaryVirtualBaseInfo) {
1076 assert(Info->PrimaryVirtualBaseInfo->IsVirtual &&
1077 "Primary virtual base is not virtual!");
1078 if (Info->PrimaryVirtualBaseInfo->Derived == Info) {
1079 // Add the offset.
1080 assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) &&
1081 "primary vbase offset already exists!");
1082 VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class,
John McCalle42a3362012-05-01 08:55:32 +00001083 ASTRecordLayout::VBaseInfo(Offset, false)));
Anders Carlssonea7b1822010-04-15 16:12:58 +00001084
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001085 // Traverse the primary virtual base.
1086 AddPrimaryVirtualBaseOffsets(Info->PrimaryVirtualBaseInfo, Offset);
1087 }
Anders Carlssonea7b1822010-04-15 16:12:58 +00001088 }
1089
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001090 // Now go through all direct non-virtual bases.
1091 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
David Majnemerc964b4b2014-07-16 06:04:00 +00001092 for (const BaseSubobjectInfo *Base : Info->Bases) {
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001093 if (Base->IsVirtual)
Anders Carlssonea7b1822010-04-15 16:12:58 +00001094 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001095
Anders Carlsson0a14ee92010-11-01 00:21:58 +00001096 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001097 AddPrimaryVirtualBaseOffsets(Base, BaseOffset);
Anders Carlssonea7b1822010-04-15 16:12:58 +00001098 }
1099}
1100
David Majnemer3b1c9902015-07-25 20:18:14 +00001101void ItaniumRecordLayoutBuilder::LayoutVirtualBases(
1102 const CXXRecordDecl *RD, const CXXRecordDecl *MostDerivedClass) {
Anders Carlssonde710c92010-03-11 04:33:54 +00001103 const CXXRecordDecl *PrimaryBase;
Anders Carlsson291279e2010-04-10 18:42:27 +00001104 bool PrimaryBaseIsVirtual;
Anders Carlssonfe900962010-03-11 05:42:17 +00001105
Anders Carlsson291279e2010-04-10 18:42:27 +00001106 if (MostDerivedClass == RD) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +00001107 PrimaryBase = this->PrimaryBase;
1108 PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual;
Anders Carlsson291279e2010-04-10 18:42:27 +00001109 } else {
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001110 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlssonde710c92010-03-11 04:33:54 +00001111 PrimaryBase = Layout.getPrimaryBase();
Anders Carlsson7f95cd12010-11-24 23:12:57 +00001112 PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
Anders Carlsson291279e2010-04-10 18:42:27 +00001113 }
1114
David Majnemerc964b4b2014-07-16 06:04:00 +00001115 for (const CXXBaseSpecifier &Base : RD->bases()) {
1116 assert(!Base.getType()->isDependentType() &&
Sebastian Redl1054fae2009-10-25 17:03:50 +00001117 "Cannot layout class with dependent bases.");
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001118
David Majnemerc964b4b2014-07-16 06:04:00 +00001119 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001120
David Majnemerc964b4b2014-07-16 06:04:00 +00001121 if (Base.isVirtual()) {
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001122 if (PrimaryBase != BaseDecl || !PrimaryBaseIsVirtual) {
1123 bool IndirectPrimaryBase = IndirectPrimaryBases.count(BaseDecl);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001124
Anders Carlsson291279e2010-04-10 18:42:27 +00001125 // Only lay out the virtual base if it's not an indirect primary base.
1126 if (!IndirectPrimaryBase) {
1127 // Only visit virtual bases once.
David Blaikie82e95a32014-11-19 07:49:47 +00001128 if (!VisitedVirtualBases.insert(BaseDecl).second)
Anders Carlsson291279e2010-04-10 18:42:27 +00001129 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001130
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001131 const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1132 assert(BaseInfo && "Did not find virtual base info!");
1133 LayoutVirtualBase(BaseInfo);
Anders Carlsson6a848892010-03-11 04:10:39 +00001134 }
Mike Stump2b84dd32009-11-05 04:02:15 +00001135 }
Mike Stumpc2f591b2009-08-13 22:53:07 +00001136 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001137
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001138 if (!BaseDecl->getNumVBases()) {
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001139 // This base isn't interesting since it doesn't have any virtual bases.
1140 continue;
Mike Stump996576f32009-08-16 19:04:13 +00001141 }
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001142
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001143 LayoutVirtualBases(BaseDecl, MostDerivedClass);
Mike Stump6b2556f2009-08-06 13:41:24 +00001144 }
1145}
1146
David Majnemer3b1c9902015-07-25 20:18:14 +00001147void ItaniumRecordLayoutBuilder::LayoutVirtualBase(
1148 const BaseSubobjectInfo *Base) {
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001149 assert(!Base->Derived && "Trying to lay out a primary virtual base!");
1150
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001151 // Layout the base.
Anders Carlssona2f8e412010-10-31 22:20:42 +00001152 CharUnits Offset = LayoutBase(Base);
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001153
1154 // Add its base class offset.
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001155 assert(!VBases.count(Base->Class) && "vbase offset already exists!");
John McCalle42a3362012-05-01 08:55:32 +00001156 VBases.insert(std::make_pair(Base->Class,
Warren Hunt55d8e822013-10-23 23:53:07 +00001157 ASTRecordLayout::VBaseInfo(Offset, false)));
John McCalle42a3362012-05-01 08:55:32 +00001158
Warren Hunt55d8e822013-10-23 23:53:07 +00001159 AddPrimaryVirtualBaseOffsets(Base, Offset);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001160}
1161
David Majnemer3b1c9902015-07-25 20:18:14 +00001162CharUnits
1163ItaniumRecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) {
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001164 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001165
Douglas Gregore9fc3772012-01-26 07:55:45 +00001166
1167 CharUnits Offset;
1168
1169 // Query the external layout to see if it provides an offset.
1170 bool HasExternalLayout = false;
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001171 if (UseExternalLayout) {
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001172 if (Base->IsVirtual)
1173 HasExternalLayout = External.getExternalNVBaseOffset(Base->Class, Offset);
1174 else
1175 HasExternalLayout = External.getExternalVBaseOffset(Base->Class, Offset);
Douglas Gregore9fc3772012-01-26 07:55:45 +00001176 }
1177
Warren Huntd640d7d2014-01-09 00:30:56 +00001178 CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlignment();
Eli Friedman69d27d22013-07-16 00:21:28 +00001179 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
1180
Anders Carlsson09ffa322010-03-10 22:21:28 +00001181 // If we have an empty base class, try to place it at offset 0.
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001182 if (Base->Class->isEmpty() &&
Douglas Gregore9fc3772012-01-26 07:55:45 +00001183 (!HasExternalLayout || Offset == CharUnits::Zero()) &&
Anders Carlsson28466ab2010-10-31 22:13:23 +00001184 EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) {
Ken Dyck1b4420e2011-02-28 02:01:38 +00001185 setSize(std::max(getSize(), Layout.getSize()));
Eli Friedman69d27d22013-07-16 00:21:28 +00001186 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001187
Anders Carlssona2f8e412010-10-31 22:20:42 +00001188 return CharUnits::Zero();
Anders Carlsson09ffa322010-03-10 22:21:28 +00001189 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001190
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001191 // The maximum field alignment overrides base align.
Ken Dyck02ced6f2011-02-17 01:49:42 +00001192 if (!MaxFieldAlignment.isZero()) {
Ken Dyck85ef0432011-02-19 18:58:07 +00001193 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1194 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001195 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001196
Douglas Gregore9fc3772012-01-26 07:55:45 +00001197 if (!HasExternalLayout) {
1198 // Round up the current record size to the base's alignment boundary.
Rui Ueyama83aa9792016-01-14 21:00:27 +00001199 Offset = getDataSize().alignTo(BaseAlign);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001200
Douglas Gregore9fc3772012-01-26 07:55:45 +00001201 // Try to place the base.
1202 while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset))
1203 Offset += BaseAlign;
1204 } else {
1205 bool Allowed = EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset);
1206 (void)Allowed;
1207 assert(Allowed && "Base subobject externally placed at overlapping offset");
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001208
Rui Ueyama83aa9792016-01-14 21:00:27 +00001209 if (InferAlignment && Offset < getDataSize().alignTo(BaseAlign)) {
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001210 // The externally-supplied base offset is before the base offset we
1211 // computed. Assume that the structure is packed.
1212 Alignment = CharUnits::One();
1213 InferAlignment = false;
1214 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001215 }
1216
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001217 if (!Base->Class->isEmpty()) {
Anders Carlsson09ffa322010-03-10 22:21:28 +00001218 // Update the data size.
Ken Dyck1b4420e2011-02-28 02:01:38 +00001219 setDataSize(Offset + Layout.getNonVirtualSize());
Anders Carlsson09ffa322010-03-10 22:21:28 +00001220
Ken Dyck1b4420e2011-02-28 02:01:38 +00001221 setSize(std::max(getSize(), getDataSize()));
Anders Carlsson09ffa322010-03-10 22:21:28 +00001222 } else
Ken Dyck1b4420e2011-02-28 02:01:38 +00001223 setSize(std::max(getSize(), Offset + Layout.getSize()));
Anders Carlsson09ffa322010-03-10 22:21:28 +00001224
1225 // Remember max struct/class alignment.
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001226 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001227
Ken Dyck1b4420e2011-02-28 02:01:38 +00001228 return Offset;
Anders Carlsson09ffa322010-03-10 22:21:28 +00001229}
1230
David Majnemer3b1c9902015-07-25 20:18:14 +00001231void ItaniumRecordLayoutBuilder::InitializeLayout(const Decl *D) {
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001232 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Daniel Dunbar6da10982010-05-27 05:45:51 +00001233 IsUnion = RD->isUnion();
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001234 IsMsStruct = RD->isMsStruct(Context);
1235 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001236
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001237 Packed = D->hasAttr<PackedAttr>();
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001238
Daniel Dunbar096ed292011-10-05 21:04:55 +00001239 // Honor the default struct packing maximum alignment flag.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001240 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) {
Daniel Dunbar096ed292011-10-05 21:04:55 +00001241 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
1242 }
1243
Daniel Dunbar6da10982010-05-27 05:45:51 +00001244 // mac68k alignment supersedes maximum field alignment and attribute aligned,
1245 // and forces all structures to have 2-byte alignment. The IBM docs on it
1246 // allude to additional (more complicated) semantics, especially with regard
1247 // to bit-fields, but gcc appears not to follow that.
1248 if (D->hasAttr<AlignMac68kAttr>()) {
1249 IsMac68kAlign = true;
Ken Dyck02ced6f2011-02-17 01:49:42 +00001250 MaxFieldAlignment = CharUnits::fromQuantity(2);
Ken Dyck4731d5b2011-02-16 02:05:21 +00001251 Alignment = CharUnits::fromQuantity(2);
Daniel Dunbar6da10982010-05-27 05:45:51 +00001252 } else {
1253 if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>())
Ken Dyck02ced6f2011-02-17 01:49:42 +00001254 MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001255
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001256 if (unsigned MaxAlign = D->getMaxAlignment())
Ken Dyck85ef0432011-02-19 18:58:07 +00001257 UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign));
Daniel Dunbar6da10982010-05-27 05:45:51 +00001258 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001259
1260 // If there is an external AST source, ask it for the various offsets.
1261 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001262 if (ExternalASTSource *Source = Context.getExternalSource()) {
1263 UseExternalLayout = Source->layoutRecordType(
1264 RD, External.Size, External.Align, External.FieldOffsets,
1265 External.BaseOffsets, External.VirtualBaseOffsets);
NAKAMURA Takumi472041f2015-02-25 10:32:20 +00001266
Douglas Gregore9fc3772012-01-26 07:55:45 +00001267 // Update based on external alignment.
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001268 if (UseExternalLayout) {
1269 if (External.Align > 0) {
1270 Alignment = Context.toCharUnitsFromBits(External.Align);
Douglas Gregor44ba7892012-01-28 00:53:29 +00001271 } else {
1272 // The external source didn't have alignment information; infer it.
1273 InferAlignment = true;
1274 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001275 }
1276 }
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001277}
Anders Carlsson6d9f6f32009-07-19 00:18:47 +00001278
David Majnemer3b1c9902015-07-25 20:18:14 +00001279void ItaniumRecordLayoutBuilder::Layout(const RecordDecl *D) {
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001280 InitializeLayout(D);
Anders Carlsson118ce162009-07-18 21:48:39 +00001281 LayoutFields(D);
Mike Stump11289f42009-09-09 15:08:12 +00001282
Anders Carlsson79474332009-07-18 20:20:21 +00001283 // Finally, round the size of the total struct up to the alignment of the
1284 // struct itself.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001285 FinishLayout(D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001286}
1287
David Majnemer3b1c9902015-07-25 20:18:14 +00001288void ItaniumRecordLayoutBuilder::Layout(const CXXRecordDecl *RD) {
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001289 InitializeLayout(RD);
1290
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001291 // Lay out the vtable and the non-virtual bases.
1292 LayoutNonVirtualBases(RD);
1293
1294 LayoutFields(RD);
1295
Ken Dycke7380752011-03-10 01:53:59 +00001296 NonVirtualSize = Context.toCharUnitsFromBits(
Rui Ueyama83aa9792016-01-14 21:00:27 +00001297 llvm::alignTo(getSizeInBits(), Context.getTargetInfo().getCharAlign()));
Ken Dyck4731d5b2011-02-16 02:05:21 +00001298 NonVirtualAlignment = Alignment;
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001299
Warren Hunt55d8e822013-10-23 23:53:07 +00001300 // Lay out the virtual bases and add the primary virtual base offsets.
1301 LayoutVirtualBases(RD, RD);
John McCall0153cd32011-11-08 04:01:03 +00001302
1303 // Finally, round the size of the total struct up to the alignment
Eli Friedman83a12582011-12-01 00:37:01 +00001304 // of the struct itself.
1305 FinishLayout(RD);
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001306
Anders Carlsson5b441d72010-04-10 21:24:48 +00001307#ifndef NDEBUG
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001308 // Check that we have base offsets for all bases.
David Majnemerc964b4b2014-07-16 06:04:00 +00001309 for (const CXXBaseSpecifier &Base : RD->bases()) {
1310 if (Base.isVirtual())
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001311 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001312
David Majnemerc964b4b2014-07-16 06:04:00 +00001313 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001314
1315 assert(Bases.count(BaseDecl) && "Did not find base offset!");
1316 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001317
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001318 // And all virtual bases.
David Majnemerc964b4b2014-07-16 06:04:00 +00001319 for (const CXXBaseSpecifier &Base : RD->vbases()) {
1320 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001321
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001322 assert(VBases.count(BaseDecl) && "Did not find base offset!");
Anders Carlsson5b441d72010-04-10 21:24:48 +00001323 }
1324#endif
Anders Carlsson79474332009-07-18 20:20:21 +00001325}
1326
David Majnemer3b1c9902015-07-25 20:18:14 +00001327void ItaniumRecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) {
Anders Carlsson4f516282009-07-18 20:50:59 +00001328 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001329 const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD);
Anders Carlsson4f516282009-07-18 20:50:59 +00001330
Ken Dyck85ef0432011-02-19 18:58:07 +00001331 UpdateAlignment(SL.getAlignment());
Mike Stump11289f42009-09-09 15:08:12 +00001332
Anders Carlsson4f516282009-07-18 20:50:59 +00001333 // We start laying out ivars not at the end of the superclass
1334 // structure, but at the next byte following the last field.
Ken Dyckecfc7552011-02-24 01:13:28 +00001335 setSize(SL.getDataSize());
Ken Dyck1b4420e2011-02-28 02:01:38 +00001336 setDataSize(getSize());
Anders Carlsson4f516282009-07-18 20:50:59 +00001337 }
Mike Stump11289f42009-09-09 15:08:12 +00001338
Daniel Dunbar6da10982010-05-27 05:45:51 +00001339 InitializeLayout(D);
Anders Carlsson4f516282009-07-18 20:50:59 +00001340 // Layout each ivar sequentially.
Jordy Rosea91768e2011-07-22 02:08:32 +00001341 for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD;
1342 IVD = IVD->getNextIvar())
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001343 LayoutField(IVD, false);
Mike Stump11289f42009-09-09 15:08:12 +00001344
Anders Carlsson4f516282009-07-18 20:50:59 +00001345 // Finally, round the size of the total struct up to the alignment of the
1346 // struct itself.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001347 FinishLayout(D);
Anders Carlsson4f516282009-07-18 20:50:59 +00001348}
1349
David Majnemer3b1c9902015-07-25 20:18:14 +00001350void ItaniumRecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
Anders Carlsson118ce162009-07-18 21:48:39 +00001351 // Layout each field, for now, just sequentially, respecting alignment. In
1352 // the future, this will need to be tweakable by targets.
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001353 bool InsertExtraPadding = D->mayInsertExtraPadding(/*EmitRemark=*/true);
Kostya Serebryany68c29da2014-10-27 19:34:10 +00001354 bool HasFlexibleArrayMember = D->hasFlexibleArrayMember();
1355 for (auto I = D->field_begin(), End = D->field_end(); I != End; ++I) {
1356 auto Next(I);
1357 ++Next;
1358 LayoutField(*I,
1359 InsertExtraPadding && (Next != End || !HasFlexibleArrayMember));
1360 }
Anders Carlsson118ce162009-07-18 21:48:39 +00001361}
1362
Artyom Skrobov5e63acc2014-10-17 10:22:03 +00001363// Rounds the specified size to have it a multiple of the char size.
1364static uint64_t
1365roundUpSizeToCharAlignment(uint64_t Size,
1366 const ASTContext &Context) {
1367 uint64_t CharAlignment = Context.getTargetInfo().getCharAlign();
Rui Ueyama83aa9792016-01-14 21:00:27 +00001368 return llvm::alignTo(Size, CharAlignment);
Artyom Skrobov5e63acc2014-10-17 10:22:03 +00001369}
1370
David Majnemer3b1c9902015-07-25 20:18:14 +00001371void ItaniumRecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize,
1372 uint64_t TypeSize,
1373 bool FieldPacked,
1374 const FieldDecl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001375 assert(Context.getLangOpts().CPlusPlus &&
Anders Carlsson57235162010-04-16 15:57:11 +00001376 "Can only have wide bit-fields in C++!");
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001377
Anders Carlsson57235162010-04-16 15:57:11 +00001378 // Itanium C++ ABI 2.4:
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001379 // If sizeof(T)*8 < n, let T' be the largest integral POD type with
Anders Carlsson57235162010-04-16 15:57:11 +00001380 // sizeof(T')*8 <= n.
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001381
Anders Carlsson57235162010-04-16 15:57:11 +00001382 QualType IntegralPODTypes[] = {
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001383 Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy,
Anders Carlsson57235162010-04-16 15:57:11 +00001384 Context.UnsignedLongTy, Context.UnsignedLongLongTy
1385 };
1386
Anders Carlsson57235162010-04-16 15:57:11 +00001387 QualType Type;
David Majnemerc964b4b2014-07-16 06:04:00 +00001388 for (const QualType &QT : IntegralPODTypes) {
1389 uint64_t Size = Context.getTypeSize(QT);
Anders Carlsson57235162010-04-16 15:57:11 +00001390
1391 if (Size > FieldSize)
1392 break;
1393
David Majnemerc964b4b2014-07-16 06:04:00 +00001394 Type = QT;
Anders Carlsson57235162010-04-16 15:57:11 +00001395 }
1396 assert(!Type.isNull() && "Did not find a type!");
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001397
Ken Dyckdbe37f32011-03-01 01:36:00 +00001398 CharUnits TypeAlign = Context.getTypeAlignInChars(Type);
Anders Carlsson57235162010-04-16 15:57:11 +00001399
1400 // We're not going to use any of the unfilled bits in the last byte.
Eli Friedman2782dac2013-06-26 20:50:34 +00001401 UnfilledBitsInLastUnit = 0;
1402 LastBitfieldTypeSize = 0;
Anders Carlsson57235162010-04-16 15:57:11 +00001403
Anders Carlssonaad5fa82010-04-17 20:21:41 +00001404 uint64_t FieldOffset;
Eli Friedman2782dac2013-06-26 20:50:34 +00001405 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001406
Anders Carlsson57235162010-04-16 15:57:11 +00001407 if (IsUnion) {
Artyom Skrobov5e63acc2014-10-17 10:22:03 +00001408 uint64_t RoundedFieldSize = roundUpSizeToCharAlignment(FieldSize,
1409 Context);
1410 setDataSize(std::max(getDataSizeInBits(), RoundedFieldSize));
Anders Carlssonaad5fa82010-04-17 20:21:41 +00001411 FieldOffset = 0;
Anders Carlsson57235162010-04-16 15:57:11 +00001412 } else {
Chad Rosiere1a6a0e2011-08-05 22:38:04 +00001413 // The bitfield is allocated starting at the next offset aligned
1414 // appropriately for T', with length n bits.
Rui Ueyama83aa9792016-01-14 21:00:27 +00001415 FieldOffset = llvm::alignTo(getDataSizeInBits(), Context.toBits(TypeAlign));
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001416
Anders Carlsson57235162010-04-16 15:57:11 +00001417 uint64_t NewSizeInBits = FieldOffset + FieldSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001418
Rui Ueyama83aa9792016-01-14 21:00:27 +00001419 setDataSize(
1420 llvm::alignTo(NewSizeInBits, Context.getTargetInfo().getCharAlign()));
Eli Friedman2782dac2013-06-26 20:50:34 +00001421 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
Anders Carlsson57235162010-04-16 15:57:11 +00001422 }
1423
1424 // Place this field at the current location.
1425 FieldOffsets.push_back(FieldOffset);
1426
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001427 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset,
Ken Dyckdbe37f32011-03-01 01:36:00 +00001428 Context.toBits(TypeAlign), FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001429
Anders Carlsson57235162010-04-16 15:57:11 +00001430 // Update the size.
Ken Dyckecfc7552011-02-24 01:13:28 +00001431 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001432
Anders Carlsson57235162010-04-16 15:57:11 +00001433 // Remember max struct/class alignment.
Ken Dyckdbe37f32011-03-01 01:36:00 +00001434 UpdateAlignment(TypeAlign);
Anders Carlsson57235162010-04-16 15:57:11 +00001435}
1436
David Majnemer3b1c9902015-07-25 20:18:14 +00001437void ItaniumRecordLayoutBuilder::LayoutBitField(const FieldDecl *D) {
Anders Carlsson07209442009-11-22 17:37:31 +00001438 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
Richard Smithcaf33902011-10-10 18:28:20 +00001439 uint64_t FieldSize = D->getBitWidthValue(Context);
David Majnemer34b57492014-07-30 01:30:47 +00001440 TypeInfo FieldInfo = Context.getTypeInfo(D->getType());
1441 uint64_t TypeSize = FieldInfo.Width;
1442 unsigned FieldAlign = FieldInfo.Align;
Eli Friedman2782dac2013-06-26 20:50:34 +00001443
John McCall30268ca2014-01-29 07:53:44 +00001444 // UnfilledBitsInLastUnit is the difference between the end of the
1445 // last allocated bitfield (i.e. the first bit offset available for
1446 // bitfields) and the end of the current data size in bits (i.e. the
1447 // first bit offset available for non-bitfields). The current data
1448 // size in bits is always a multiple of the char size; additionally,
1449 // for ms_struct records it's also a multiple of the
1450 // LastBitfieldTypeSize (if set).
1451
John McCall76e1818a2014-02-13 00:50:08 +00001452 // The struct-layout algorithm is dictated by the platform ABI,
1453 // which in principle could use almost any rules it likes. In
1454 // practice, UNIXy targets tend to inherit the algorithm described
1455 // in the System V generic ABI. The basic bitfield layout rule in
1456 // System V is to place bitfields at the next available bit offset
1457 // where the entire bitfield would fit in an aligned storage unit of
1458 // the declared type; it's okay if an earlier or later non-bitfield
1459 // is allocated in the same storage unit. However, some targets
1460 // (those that !useBitFieldTypeAlignment(), e.g. ARM APCS) don't
1461 // require this storage unit to be aligned, and therefore always put
1462 // the bitfield at the next available bit offset.
John McCall30268ca2014-01-29 07:53:44 +00001463
John McCall76e1818a2014-02-13 00:50:08 +00001464 // ms_struct basically requests a complete replacement of the
1465 // platform ABI's struct-layout algorithm, with the high-level goal
1466 // of duplicating MSVC's layout. For non-bitfields, this follows
Eric Christopher2c4555a2015-06-19 01:52:53 +00001467 // the standard algorithm. The basic bitfield layout rule is to
John McCall76e1818a2014-02-13 00:50:08 +00001468 // allocate an entire unit of the bitfield's declared type
1469 // (e.g. 'unsigned long'), then parcel it up among successive
1470 // bitfields whose declared types have the same size, making a new
1471 // unit as soon as the last can no longer store the whole value.
1472 // Since it completely replaces the platform ABI's algorithm,
1473 // settings like !useBitFieldTypeAlignment() do not apply.
1474
1475 // A zero-width bitfield forces the use of a new storage unit for
1476 // later bitfields. In general, this occurs by rounding up the
1477 // current size of the struct as if the algorithm were about to
1478 // place a non-bitfield of the field's formal type. Usually this
1479 // does not change the alignment of the struct itself, but it does
1480 // on some targets (those that useZeroLengthBitfieldAlignment(),
1481 // e.g. ARM). In ms_struct layout, zero-width bitfields are
1482 // ignored unless they follow a non-zero-width bitfield.
1483
1484 // A field alignment restriction (e.g. from #pragma pack) or
1485 // specification (e.g. from __attribute__((aligned))) changes the
1486 // formal alignment of the field. For System V, this alters the
1487 // required alignment of the notional storage unit that must contain
1488 // the bitfield. For ms_struct, this only affects the placement of
1489 // new storage units. In both cases, the effect of #pragma pack is
1490 // ignored on zero-width bitfields.
1491
1492 // On System V, a packed field (e.g. from #pragma pack or
1493 // __attribute__((packed))) always uses the next available bit
1494 // offset.
1495
John McCall95833f32014-02-27 20:30:49 +00001496 // In an ms_struct struct, the alignment of a fundamental type is
1497 // always equal to its size. This is necessary in order to mimic
1498 // the i386 alignment rules on targets which might not fully align
1499 // all types (e.g. Darwin PPC32, where alignof(long long) == 4).
John McCall30268ca2014-01-29 07:53:44 +00001500
1501 // First, some simple bookkeeping to perform for ms_struct structs.
Eli Friedman2782dac2013-06-26 20:50:34 +00001502 if (IsMsStruct) {
John McCall30268ca2014-01-29 07:53:44 +00001503 // The field alignment for integer types is always the size.
Fariborz Jahanian7adbed62011-05-09 22:03:17 +00001504 FieldAlign = TypeSize;
John McCall30268ca2014-01-29 07:53:44 +00001505
1506 // If the previous field was not a bitfield, or was a bitfield
Alex Lorenzde07acb2018-01-31 21:59:02 +00001507 // with a different storage unit size, or if this field doesn't fit into
1508 // the current storage unit, we're done with that storage unit.
1509 if (LastBitfieldTypeSize != TypeSize ||
1510 UnfilledBitsInLastUnit < FieldSize) {
John McCall30268ca2014-01-29 07:53:44 +00001511 // Also, ignore zero-length bitfields after non-bitfields.
1512 if (!LastBitfieldTypeSize && !FieldSize)
1513 FieldAlign = 1;
1514
Eli Friedman2782dac2013-06-26 20:50:34 +00001515 UnfilledBitsInLastUnit = 0;
1516 LastBitfieldTypeSize = 0;
1517 }
1518 }
1519
John McCall30268ca2014-01-29 07:53:44 +00001520 // If the field is wider than its declared type, it follows
1521 // different rules in all cases.
Anders Carlsson57235162010-04-16 15:57:11 +00001522 if (FieldSize > TypeSize) {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001523 LayoutWideBitField(FieldSize, TypeSize, FieldPacked, D);
Anders Carlsson57235162010-04-16 15:57:11 +00001524 return;
1525 }
1526
John McCall30268ca2014-01-29 07:53:44 +00001527 // Compute the next available bit offset.
1528 uint64_t FieldOffset =
1529 IsUnion ? 0 : (getDataSizeInBits() - UnfilledBitsInLastUnit);
1530
1531 // Handle targets that don't honor bitfield type alignment.
John McCall76e1818a2014-02-13 00:50:08 +00001532 if (!IsMsStruct && !Context.getTargetInfo().useBitFieldTypeAlignment()) {
John McCall30268ca2014-01-29 07:53:44 +00001533 // Some such targets do honor it on zero-width bitfields.
1534 if (FieldSize == 0 &&
1535 Context.getTargetInfo().useZeroLengthBitfieldAlignment()) {
1536 // The alignment to round up to is the max of the field's natural
1537 // alignment and a target-specific fixed value (sometimes zero).
1538 unsigned ZeroLengthBitfieldBoundary =
1539 Context.getTargetInfo().getZeroLengthBitfieldBoundary();
1540 FieldAlign = std::max(FieldAlign, ZeroLengthBitfieldBoundary);
1541
1542 // If that doesn't apply, just ignore the field alignment.
1543 } else {
1544 FieldAlign = 1;
1545 }
1546 }
1547
1548 // Remember the alignment we would have used if the field were not packed.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001549 unsigned UnpackedFieldAlign = FieldAlign;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001550
Yunzhong Gao5fd0c9d2014-02-13 02:45:10 +00001551 // Ignore the field alignment if the field is packed unless it has zero-size.
1552 if (!IsMsStruct && FieldPacked && FieldSize != 0)
Anders Carlsson07209442009-11-22 17:37:31 +00001553 FieldAlign = 1;
Anders Carlsson07209442009-11-22 17:37:31 +00001554
John McCall30268ca2014-01-29 07:53:44 +00001555 // But, if there's an 'aligned' attribute on the field, honor that.
Alexey Bataev567e30f2016-01-12 09:12:20 +00001556 unsigned ExplicitFieldAlign = D->getMaxAlignment();
1557 if (ExplicitFieldAlign) {
John McCall30268ca2014-01-29 07:53:44 +00001558 FieldAlign = std::max(FieldAlign, ExplicitFieldAlign);
1559 UnpackedFieldAlign = std::max(UnpackedFieldAlign, ExplicitFieldAlign);
1560 }
1561
1562 // But, if there's a #pragma pack in play, that takes precedent over
1563 // even the 'aligned' attribute, for non-zero-width bitfields.
Alexey Bataev455bdd92016-02-19 11:23:28 +00001564 unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment);
John McCall30268ca2014-01-29 07:53:44 +00001565 if (!MaxFieldAlignment.isZero() && FieldSize) {
Ken Dyck02ced6f2011-02-17 01:49:42 +00001566 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
Alexey Bataev455bdd92016-02-19 11:23:28 +00001567 if (FieldPacked)
1568 FieldAlign = UnpackedFieldAlign;
1569 else
1570 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001571 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001572
John McCall0d461692015-08-19 22:42:36 +00001573 // But, ms_struct just ignores all of that in unions, even explicit
1574 // alignment attributes.
1575 if (IsMsStruct && IsUnion) {
1576 FieldAlign = UnpackedFieldAlign = 1;
1577 }
1578
John McCall30268ca2014-01-29 07:53:44 +00001579 // For purposes of diagnostics, we're going to simultaneously
1580 // compute the field offsets that we would have used if we weren't
1581 // adding any alignment padding or if the field weren't packed.
1582 uint64_t UnpaddedFieldOffset = FieldOffset;
1583 uint64_t UnpackedFieldOffset = FieldOffset;
1584
1585 // Check if we need to add padding to fit the bitfield within an
1586 // allocation unit with the right size and alignment. The rules are
1587 // somewhat different here for ms_struct structs.
1588 if (IsMsStruct) {
1589 // If it's not a zero-width bitfield, and we can fit the bitfield
1590 // into the active storage unit (and we haven't already decided to
1591 // start a new storage unit), just do so, regardless of any other
1592 // other consideration. Otherwise, round up to the right alignment.
1593 if (FieldSize == 0 || FieldSize > UnfilledBitsInLastUnit) {
Rui Ueyama83aa9792016-01-14 21:00:27 +00001594 FieldOffset = llvm::alignTo(FieldOffset, FieldAlign);
1595 UnpackedFieldOffset =
1596 llvm::alignTo(UnpackedFieldOffset, UnpackedFieldAlign);
John McCall30268ca2014-01-29 07:53:44 +00001597 UnfilledBitsInLastUnit = 0;
1598 }
1599
1600 } else {
1601 // #pragma pack, with any value, suppresses the insertion of padding.
1602 bool AllowPadding = MaxFieldAlignment.isZero();
1603
1604 // Compute the real offset.
1605 if (FieldSize == 0 ||
1606 (AllowPadding &&
1607 (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)) {
Rui Ueyama83aa9792016-01-14 21:00:27 +00001608 FieldOffset = llvm::alignTo(FieldOffset, FieldAlign);
Sunil Srivastava0ce2f222016-02-05 20:50:02 +00001609 } else if (ExplicitFieldAlign &&
Alexey Bataev455bdd92016-02-19 11:23:28 +00001610 (MaxFieldAlignmentInBits == 0 ||
1611 ExplicitFieldAlign <= MaxFieldAlignmentInBits) &&
Sunil Srivastava0ce2f222016-02-05 20:50:02 +00001612 Context.getTargetInfo().useExplicitBitFieldAlignment()) {
Alexey Bataev567e30f2016-01-12 09:12:20 +00001613 // TODO: figure it out what needs to be done on targets that don't honor
1614 // bit-field type alignment like ARM APCS ABI.
Rui Ueyama83aa9792016-01-14 21:00:27 +00001615 FieldOffset = llvm::alignTo(FieldOffset, ExplicitFieldAlign);
John McCall30268ca2014-01-29 07:53:44 +00001616 }
1617
1618 // Repeat the computation for diagnostic purposes.
1619 if (FieldSize == 0 ||
1620 (AllowPadding &&
1621 (UnpackedFieldOffset & (UnpackedFieldAlign-1)) + FieldSize > TypeSize))
Rui Ueyama83aa9792016-01-14 21:00:27 +00001622 UnpackedFieldOffset =
1623 llvm::alignTo(UnpackedFieldOffset, UnpackedFieldAlign);
Sunil Srivastava0ce2f222016-02-05 20:50:02 +00001624 else if (ExplicitFieldAlign &&
Alexey Bataev455bdd92016-02-19 11:23:28 +00001625 (MaxFieldAlignmentInBits == 0 ||
1626 ExplicitFieldAlign <= MaxFieldAlignmentInBits) &&
Sunil Srivastava0ce2f222016-02-05 20:50:02 +00001627 Context.getTargetInfo().useExplicitBitFieldAlignment())
Rui Ueyama83aa9792016-01-14 21:00:27 +00001628 UnpackedFieldOffset =
1629 llvm::alignTo(UnpackedFieldOffset, ExplicitFieldAlign);
Eli Friedman2782dac2013-06-26 20:50:34 +00001630 }
1631
John McCall30268ca2014-01-29 07:53:44 +00001632 // If we're using external layout, give the external layout a chance
1633 // to override this information.
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001634 if (UseExternalLayout)
Douglas Gregor44ba7892012-01-28 00:53:29 +00001635 FieldOffset = updateExternalFieldOffset(D, FieldOffset);
1636
John McCall30268ca2014-01-29 07:53:44 +00001637 // Okay, place the bitfield at the calculated offset.
Anders Carlsson07209442009-11-22 17:37:31 +00001638 FieldOffsets.push_back(FieldOffset);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001639
John McCall30268ca2014-01-29 07:53:44 +00001640 // Bookkeeping:
1641
1642 // Anonymous members don't affect the overall record alignment,
1643 // except on targets where they do.
1644 if (!IsMsStruct &&
1645 !Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
1646 !D->getIdentifier())
1647 FieldAlign = UnpackedFieldAlign = 1;
1648
1649 // Diagnose differences in layout due to padding or packing.
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001650 if (!UseExternalLayout)
Douglas Gregore9fc3772012-01-26 07:55:45 +00001651 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset,
1652 UnpackedFieldAlign, FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001653
Anders Carlssonba958402009-11-22 19:13:51 +00001654 // Update DataSize to include the last byte containing (part of) the bitfield.
John McCall30268ca2014-01-29 07:53:44 +00001655
1656 // For unions, this is just a max operation, as usual.
Anders Carlssonba958402009-11-22 19:13:51 +00001657 if (IsUnion) {
John McCall0d461692015-08-19 22:42:36 +00001658 // For ms_struct, allocate the entire storage unit --- unless this
1659 // is a zero-width bitfield, in which case just use a size of 1.
1660 uint64_t RoundedFieldSize;
1661 if (IsMsStruct) {
1662 RoundedFieldSize =
1663 (FieldSize ? TypeSize : Context.getTargetInfo().getCharWidth());
1664
1665 // Otherwise, allocate just the number of bytes required to store
1666 // the bitfield.
1667 } else {
1668 RoundedFieldSize = roundUpSizeToCharAlignment(FieldSize, Context);
1669 }
Artyom Skrobov5e63acc2014-10-17 10:22:03 +00001670 setDataSize(std::max(getDataSizeInBits(), RoundedFieldSize));
John McCall0d461692015-08-19 22:42:36 +00001671
John McCall30268ca2014-01-29 07:53:44 +00001672 // For non-zero-width bitfields in ms_struct structs, allocate a new
1673 // storage unit if necessary.
1674 } else if (IsMsStruct && FieldSize) {
1675 // We should have cleared UnfilledBitsInLastUnit in every case
1676 // where we changed storage units.
1677 if (!UnfilledBitsInLastUnit) {
1678 setDataSize(FieldOffset + TypeSize);
1679 UnfilledBitsInLastUnit = TypeSize;
Eli Friedman2782dac2013-06-26 20:50:34 +00001680 }
John McCall30268ca2014-01-29 07:53:44 +00001681 UnfilledBitsInLastUnit -= FieldSize;
1682 LastBitfieldTypeSize = TypeSize;
1683
1684 // Otherwise, bump the data size up to include the bitfield,
1685 // including padding up to char alignment, and then remember how
1686 // bits we didn't use.
1687 } else {
1688 uint64_t NewSizeInBits = FieldOffset + FieldSize;
1689 uint64_t CharAlignment = Context.getTargetInfo().getCharAlign();
Rui Ueyama83aa9792016-01-14 21:00:27 +00001690 setDataSize(llvm::alignTo(NewSizeInBits, CharAlignment));
John McCall30268ca2014-01-29 07:53:44 +00001691 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
1692
1693 // The only time we can get here for an ms_struct is if this is a
1694 // zero-width bitfield, which doesn't count as anything for the
1695 // purposes of unfilled bits.
1696 LastBitfieldTypeSize = 0;
Anders Carlssonba958402009-11-22 19:13:51 +00001697 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001698
Anders Carlssonba958402009-11-22 19:13:51 +00001699 // Update the size.
Ken Dyckecfc7552011-02-24 01:13:28 +00001700 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001701
Anders Carlsson07209442009-11-22 17:37:31 +00001702 // Remember max struct/class alignment.
Ken Dyck85ef0432011-02-19 18:58:07 +00001703 UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign),
1704 Context.toCharUnitsFromBits(UnpackedFieldAlign));
Anders Carlsson07209442009-11-22 17:37:31 +00001705}
1706
David Majnemer3b1c9902015-07-25 20:18:14 +00001707void ItaniumRecordLayoutBuilder::LayoutField(const FieldDecl *D,
1708 bool InsertExtraPadding) {
Anders Carlsson07209442009-11-22 17:37:31 +00001709 if (D->isBitField()) {
1710 LayoutBitField(D);
1711 return;
1712 }
1713
Eli Friedman2782dac2013-06-26 20:50:34 +00001714 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001715
Anders Carlssonba958402009-11-22 19:13:51 +00001716 // Reset the unfilled bits.
Eli Friedman2782dac2013-06-26 20:50:34 +00001717 UnfilledBitsInLastUnit = 0;
1718 LastBitfieldTypeSize = 0;
Anders Carlssonba958402009-11-22 19:13:51 +00001719
Anders Carlsson07209442009-11-22 17:37:31 +00001720 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
Ken Dyck6d90e892011-02-20 02:06:09 +00001721 CharUnits FieldOffset =
Ken Dyckecfc7552011-02-24 01:13:28 +00001722 IsUnion ? CharUnits::Zero() : getDataSize();
Ken Dyck6d90e892011-02-20 02:06:09 +00001723 CharUnits FieldSize;
1724 CharUnits FieldAlign;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001725
Anders Carlsson07209442009-11-22 17:37:31 +00001726 if (D->getType()->isIncompleteArrayType()) {
1727 // This is a flexible array member; we can't directly
1728 // query getTypeInfo about these, so we figure it out here.
1729 // Flexible array members don't have any size, but they
1730 // have to be aligned appropriately for their element type.
Ken Dyck6d90e892011-02-20 02:06:09 +00001731 FieldSize = CharUnits::Zero();
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001732 const ArrayType* ATy = Context.getAsArrayType(D->getType());
Ken Dyck6d90e892011-02-20 02:06:09 +00001733 FieldAlign = Context.getTypeAlignInChars(ATy->getElementType());
Anders Carlsson07209442009-11-22 17:37:31 +00001734 } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) {
Alexander Richardson6d989432017-10-15 18:48:14 +00001735 unsigned AS = Context.getTargetAddressSpace(RT->getPointeeType());
Ken Dyck6d90e892011-02-20 02:06:09 +00001736 FieldSize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001737 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(AS));
Ken Dyck6d90e892011-02-20 02:06:09 +00001738 FieldAlign =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001739 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(AS));
Anders Carlsson79474332009-07-18 20:20:21 +00001740 } else {
Ken Dyck6d90e892011-02-20 02:06:09 +00001741 std::pair<CharUnits, CharUnits> FieldInfo =
1742 Context.getTypeInfoInChars(D->getType());
Anders Carlsson07209442009-11-22 17:37:31 +00001743 FieldSize = FieldInfo.first;
1744 FieldAlign = FieldInfo.second;
Chad Rosier18903ee2011-08-04 01:21:14 +00001745
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001746 if (IsMsStruct) {
Douglas Gregordbe39272011-02-01 15:15:22 +00001747 // If MS bitfield layout is required, figure out what type is being
1748 // laid out and align the field to the width of that type.
1749
1750 // Resolve all typedefs down to their base type and round up the field
1751 // alignment if necessary.
1752 QualType T = Context.getBaseElementType(D->getType());
1753 if (const BuiltinType *BTy = T->getAs<BuiltinType>()) {
Ken Dyck6d90e892011-02-20 02:06:09 +00001754 CharUnits TypeSize = Context.getTypeSizeInChars(BTy);
Martin Storsjo87c2ad22018-03-01 20:22:57 +00001755
1756 if (!llvm::isPowerOf2_64(TypeSize.getQuantity())) {
1757 assert(
1758 !Context.getTargetInfo().getTriple().isWindowsMSVCEnvironment() &&
1759 "Non PowerOf2 size in MSVC mode");
1760 // Base types with sizes that aren't a power of two don't work
1761 // with the layout rules for MS structs. This isn't an issue in
1762 // MSVC itself since there are no such base data types there.
1763 // On e.g. x86_32 mingw and linux, long double is 12 bytes though.
1764 // Any structs involving that data type obviously can't be ABI
1765 // compatible with MSVC regardless of how it is laid out.
1766
1767 // Since ms_struct can be mass enabled (via a pragma or via the
1768 // -mms-bitfields command line parameter), this can trigger for
1769 // structs that don't actually need MSVC compatibility, so we
1770 // need to be able to sidestep the ms_struct layout for these types.
1771
1772 // Since the combination of -mms-bitfields together with structs
1773 // like max_align_t (which contains a long double) for mingw is
1774 // quite comon (and GCC handles it silently), just handle it
1775 // silently there. For other targets that have ms_struct enabled
1776 // (most probably via a pragma or attribute), trigger a diagnostic
1777 // that defaults to an error.
1778 if (!Context.getTargetInfo().getTriple().isWindowsGNUEnvironment())
1779 Diag(D->getLocation(), diag::warn_npot_ms_struct);
1780 }
Martin Storsjo96b01bc2018-02-27 06:27:06 +00001781 if (TypeSize > FieldAlign &&
1782 llvm::isPowerOf2_64(TypeSize.getQuantity()))
Douglas Gregordbe39272011-02-01 15:15:22 +00001783 FieldAlign = TypeSize;
1784 }
1785 }
Anders Carlsson79474332009-07-18 20:20:21 +00001786 }
Mike Stump11289f42009-09-09 15:08:12 +00001787
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001788 // The align if the field is not packed. This is to check if the attribute
1789 // was unnecessary (-Wpacked).
Ken Dyck6d90e892011-02-20 02:06:09 +00001790 CharUnits UnpackedFieldAlign = FieldAlign;
1791 CharUnits UnpackedFieldOffset = FieldOffset;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001792
Anders Carlsson07209442009-11-22 17:37:31 +00001793 if (FieldPacked)
Ken Dyck6d90e892011-02-20 02:06:09 +00001794 FieldAlign = CharUnits::One();
1795 CharUnits MaxAlignmentInChars =
1796 Context.toCharUnitsFromBits(D->getMaxAlignment());
1797 FieldAlign = std::max(FieldAlign, MaxAlignmentInChars);
1798 UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars);
Anders Carlsson07209442009-11-22 17:37:31 +00001799
1800 // The maximum field alignment overrides the aligned attribute.
Ken Dyck02ced6f2011-02-17 01:49:42 +00001801 if (!MaxFieldAlignment.isZero()) {
Ken Dyck6d90e892011-02-20 02:06:09 +00001802 FieldAlign = std::min(FieldAlign, MaxFieldAlignment);
1803 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001804 }
Anders Carlsson07209442009-11-22 17:37:31 +00001805
Douglas Gregor44ba7892012-01-28 00:53:29 +00001806 // Round up the current record size to the field's alignment boundary.
Rui Ueyama83aa9792016-01-14 21:00:27 +00001807 FieldOffset = FieldOffset.alignTo(FieldAlign);
1808 UnpackedFieldOffset = UnpackedFieldOffset.alignTo(UnpackedFieldAlign);
Douglas Gregor44ba7892012-01-28 00:53:29 +00001809
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001810 if (UseExternalLayout) {
Douglas Gregor44ba7892012-01-28 00:53:29 +00001811 FieldOffset = Context.toCharUnitsFromBits(
1812 updateExternalFieldOffset(D, Context.toBits(FieldOffset)));
1813
1814 if (!IsUnion && EmptySubobjects) {
1815 // Record the fact that we're placing a field at this offset.
1816 bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset);
1817 (void)Allowed;
1818 assert(Allowed && "Externally-placed field cannot be placed here");
1819 }
1820 } else {
Douglas Gregore9fc3772012-01-26 07:55:45 +00001821 if (!IsUnion && EmptySubobjects) {
1822 // Check if we can place the field at this offset.
1823 while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) {
1824 // We couldn't place the field at the offset. Try again at a new offset.
1825 FieldOffset += FieldAlign;
1826 }
Anders Carlsson07209442009-11-22 17:37:31 +00001827 }
Anders Carlsson07209442009-11-22 17:37:31 +00001828 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001829
Anders Carlsson79474332009-07-18 20:20:21 +00001830 // Place this field at the current location.
Ken Dyck6d90e892011-02-20 02:06:09 +00001831 FieldOffsets.push_back(Context.toBits(FieldOffset));
Mike Stump11289f42009-09-09 15:08:12 +00001832
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001833 if (!UseExternalLayout)
1834 CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset,
Douglas Gregore9fc3772012-01-26 07:55:45 +00001835 Context.toBits(UnpackedFieldOffset),
1836 Context.toBits(UnpackedFieldAlign), FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001837
Kostya Serebryany68c29da2014-10-27 19:34:10 +00001838 if (InsertExtraPadding) {
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001839 CharUnits ASanAlignment = CharUnits::fromQuantity(8);
1840 CharUnits ExtraSizeForAsan = ASanAlignment;
1841 if (FieldSize % ASanAlignment)
1842 ExtraSizeForAsan +=
1843 ASanAlignment - CharUnits::fromQuantity(FieldSize % ASanAlignment);
1844 FieldSize += ExtraSizeForAsan;
1845 }
1846
Anders Carlsson79474332009-07-18 20:20:21 +00001847 // Reserve space for this field.
Eli Friedman43f18342012-01-12 23:27:03 +00001848 uint64_t FieldSizeInBits = Context.toBits(FieldSize);
Anders Carlsson79474332009-07-18 20:20:21 +00001849 if (IsUnion)
Eli Friedman2e108372012-01-12 23:48:56 +00001850 setDataSize(std::max(getDataSizeInBits(), FieldSizeInBits));
Anders Carlsson79474332009-07-18 20:20:21 +00001851 else
Eli Friedman2e108372012-01-12 23:48:56 +00001852 setDataSize(FieldOffset + FieldSize);
Mike Stump11289f42009-09-09 15:08:12 +00001853
Eli Friedman2e108372012-01-12 23:48:56 +00001854 // Update the size.
1855 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Mike Stump11289f42009-09-09 15:08:12 +00001856
Anders Carlsson79474332009-07-18 20:20:21 +00001857 // Remember max struct/class alignment.
Ken Dyck6d90e892011-02-20 02:06:09 +00001858 UpdateAlignment(FieldAlign, UnpackedFieldAlign);
Anders Carlsson79474332009-07-18 20:20:21 +00001859}
1860
David Majnemer3b1c9902015-07-25 20:18:14 +00001861void ItaniumRecordLayoutBuilder::FinishLayout(const NamedDecl *D) {
Anders Carlsson79474332009-07-18 20:20:21 +00001862 // In C++, records cannot be of size 0.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001863 if (Context.getLangOpts().CPlusPlus && getSizeInBits() == 0) {
Fariborz Jahanian09b23312011-02-02 19:36:18 +00001864 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
1865 // Compatibility with gcc requires a class (pod or non-pod)
1866 // which is not empty but of size 0; such as having fields of
1867 // array of zero-length, remains of Size 0
1868 if (RD->isEmpty())
Ken Dyck1b4420e2011-02-28 02:01:38 +00001869 setSize(CharUnits::One());
Fariborz Jahanian09b23312011-02-02 19:36:18 +00001870 }
1871 else
Ken Dyck1b4420e2011-02-28 02:01:38 +00001872 setSize(CharUnits::One());
Fariborz Jahanian09b23312011-02-02 19:36:18 +00001873 }
Eli Friedman83a12582011-12-01 00:37:01 +00001874
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001875 // Finally, round the size of the record up to the alignment of the
1876 // record itself.
Eli Friedman2782dac2013-06-26 20:50:34 +00001877 uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastUnit;
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001878 uint64_t UnpackedSizeInBits =
Rui Ueyama83aa9792016-01-14 21:00:27 +00001879 llvm::alignTo(getSizeInBits(), Context.toBits(UnpackedAlignment));
Rui Ueyama83aa9792016-01-14 21:00:27 +00001880 uint64_t RoundedSize =
1881 llvm::alignTo(getSizeInBits(), Context.toBits(Alignment));
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001882
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001883 if (UseExternalLayout) {
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001884 // If we're inferring alignment, and the external size is smaller than
1885 // our size after we've rounded up to alignment, conservatively set the
1886 // alignment to 1.
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001887 if (InferAlignment && External.Size < RoundedSize) {
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001888 Alignment = CharUnits::One();
1889 InferAlignment = false;
1890 }
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001891 setSize(External.Size);
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001892 return;
1893 }
1894
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001895 // Set the size to the final size.
1896 setSize(RoundedSize);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001897
Douglas Gregore8bbc122011-09-02 00:18:52 +00001898 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001899 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1900 // Warn if padding was introduced to the struct/class/union.
Ken Dyckecfc7552011-02-24 01:13:28 +00001901 if (getSizeInBits() > UnpaddedSize) {
1902 unsigned PadSize = getSizeInBits() - UnpaddedSize;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001903 bool InBits = true;
1904 if (PadSize % CharBitNum == 0) {
1905 PadSize = PadSize / CharBitNum;
1906 InBits = false;
1907 }
1908 Diag(RD->getLocation(), diag::warn_padded_struct_size)
1909 << Context.getTypeDeclType(RD)
1910 << PadSize
Benjamin Kramerc06b6bd2015-08-21 12:51:01 +00001911 << (InBits ? 1 : 0); // (byte|bit)
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001912 }
1913
Yan Wangd79f3f62017-08-01 21:41:39 +00001914 // Warn if we packed it unnecessarily, when the unpacked alignment is not
1915 // greater than the one after packing, the size in bits doesn't change and
1916 // the offset of each field is identical.
1917 if (Packed && UnpackedAlignment <= Alignment &&
1918 UnpackedSizeInBits == getSizeInBits() && !HasPackedField)
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001919 Diag(D->getLocation(), diag::warn_unnecessary_packed)
1920 << Context.getTypeDeclType(RD);
1921 }
Anders Carlsson79474332009-07-18 20:20:21 +00001922}
1923
David Majnemer3b1c9902015-07-25 20:18:14 +00001924void ItaniumRecordLayoutBuilder::UpdateAlignment(
1925 CharUnits NewAlignment, CharUnits UnpackedNewAlignment) {
Douglas Gregore9fc3772012-01-26 07:55:45 +00001926 // The alignment is not modified when using 'mac68k' alignment or when
Douglas Gregor44ba7892012-01-28 00:53:29 +00001927 // we have an externally-supplied layout that also provides overall alignment.
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001928 if (IsMac68kAlign || (UseExternalLayout && !InferAlignment))
Daniel Dunbar6da10982010-05-27 05:45:51 +00001929 return;
1930
Ken Dyck85ef0432011-02-19 18:58:07 +00001931 if (NewAlignment > Alignment) {
Reid Kleckner5a63d702015-03-24 23:46:25 +00001932 assert(llvm::isPowerOf2_64(NewAlignment.getQuantity()) &&
1933 "Alignment not a power of 2");
Ken Dyck85ef0432011-02-19 18:58:07 +00001934 Alignment = NewAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001935 }
1936
Ken Dyck85ef0432011-02-19 18:58:07 +00001937 if (UnpackedNewAlignment > UnpackedAlignment) {
Reid Kleckner5a63d702015-03-24 23:46:25 +00001938 assert(llvm::isPowerOf2_64(UnpackedNewAlignment.getQuantity()) &&
1939 "Alignment not a power of 2");
Ken Dyck85ef0432011-02-19 18:58:07 +00001940 UnpackedAlignment = UnpackedNewAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001941 }
1942}
1943
Douglas Gregor44ba7892012-01-28 00:53:29 +00001944uint64_t
David Majnemer3b1c9902015-07-25 20:18:14 +00001945ItaniumRecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field,
1946 uint64_t ComputedOffset) {
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001947 uint64_t ExternalFieldOffset = External.getExternalFieldOffset(Field);
NAKAMURA Takumi472041f2015-02-25 10:32:20 +00001948
Douglas Gregor44ba7892012-01-28 00:53:29 +00001949 if (InferAlignment && ExternalFieldOffset < ComputedOffset) {
1950 // The externally-supplied field offset is before the field offset we
1951 // computed. Assume that the structure is packed.
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001952 Alignment = CharUnits::One();
Douglas Gregor44ba7892012-01-28 00:53:29 +00001953 InferAlignment = false;
1954 }
1955
1956 // Use the externally-supplied field offset.
Benjamin Kramer648e68b2012-08-31 22:14:25 +00001957 return ExternalFieldOffset;
1958}
1959
1960/// \brief Get diagnostic %select index for tag kind for
1961/// field padding diagnostic message.
1962/// WARNING: Indexes apply to particular diagnostics only!
1963///
1964/// \returns diagnostic %select index.
1965static unsigned getPaddingDiagFromTagKind(TagTypeKind Tag) {
1966 switch (Tag) {
1967 case TTK_Struct: return 0;
1968 case TTK_Interface: return 1;
1969 case TTK_Class: return 2;
1970 default: llvm_unreachable("Invalid tag kind for field padding diagnostic!");
1971 }
1972}
1973
David Majnemer3b1c9902015-07-25 20:18:14 +00001974void ItaniumRecordLayoutBuilder::CheckFieldPadding(
1975 uint64_t Offset, uint64_t UnpaddedOffset, uint64_t UnpackedOffset,
1976 unsigned UnpackedAlign, bool isPacked, const FieldDecl *D) {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001977 // We let objc ivars without warning, objc interfaces generally are not used
1978 // for padding tricks.
1979 if (isa<ObjCIvarDecl>(D))
Anders Carlsson79474332009-07-18 20:20:21 +00001980 return;
Mike Stump11289f42009-09-09 15:08:12 +00001981
Ted Kremenekfed48af2011-09-06 19:40:45 +00001982 // Don't warn about structs created without a SourceLocation. This can
1983 // be done by clients of the AST, such as codegen.
1984 if (D->getLocation().isInvalid())
1985 return;
1986
Douglas Gregore8bbc122011-09-02 00:18:52 +00001987 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
Mike Stump11289f42009-09-09 15:08:12 +00001988
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001989 // Warn if padding was introduced to the struct/class.
1990 if (!IsUnion && Offset > UnpaddedOffset) {
1991 unsigned PadSize = Offset - UnpaddedOffset;
1992 bool InBits = true;
1993 if (PadSize % CharBitNum == 0) {
1994 PadSize = PadSize / CharBitNum;
1995 InBits = false;
Benjamin Kramer648e68b2012-08-31 22:14:25 +00001996 }
1997 if (D->getIdentifier())
1998 Diag(D->getLocation(), diag::warn_padded_struct_field)
1999 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
2000 << Context.getTypeDeclType(D->getParent())
2001 << PadSize
Benjamin Kramerc06b6bd2015-08-21 12:51:01 +00002002 << (InBits ? 1 : 0) // (byte|bit)
Benjamin Kramer648e68b2012-08-31 22:14:25 +00002003 << D->getIdentifier();
2004 else
2005 Diag(D->getLocation(), diag::warn_padded_struct_anon_field)
2006 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
2007 << Context.getTypeDeclType(D->getParent())
2008 << PadSize
Benjamin Kramerc06b6bd2015-08-21 12:51:01 +00002009 << (InBits ? 1 : 0); // (byte|bit)
Yan Wangd79f3f62017-08-01 21:41:39 +00002010 }
2011 if (isPacked && Offset != UnpackedOffset) {
2012 HasPackedField = true;
2013 }
Anders Carlsson79474332009-07-18 20:20:21 +00002014}
Mike Stump11289f42009-09-09 15:08:12 +00002015
John McCall6bd2a892013-01-25 22:31:03 +00002016static const CXXMethodDecl *computeKeyFunction(ASTContext &Context,
2017 const CXXRecordDecl *RD) {
Daniel Dunbarccabe482010-04-19 20:44:53 +00002018 // If a class isn't polymorphic it doesn't have a key function.
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00002019 if (!RD->isPolymorphic())
Craig Topper36250ad2014-05-12 05:36:57 +00002020 return nullptr;
Eli Friedmanf2c79b62009-12-08 03:56:49 +00002021
Eli Friedman300f55d2011-06-10 21:53:06 +00002022 // A class that is not externally visible doesn't have a key function. (Or
Eli Friedmanf2c79b62009-12-08 03:56:49 +00002023 // at least, there's no point to assigning a key function to such a class;
2024 // this doesn't affect the ABI.)
Rafael Espindola3ae00052013-05-13 00:12:11 +00002025 if (!RD->isExternallyVisible())
Craig Topper36250ad2014-05-12 05:36:57 +00002026 return nullptr;
Eli Friedmanf2c79b62009-12-08 03:56:49 +00002027
Richard Smith750f5112014-03-24 23:54:09 +00002028 // Template instantiations don't have key functions per Itanium C++ ABI 5.2.6.
Argyrios Kyrtzidis8c64bbe2010-10-13 02:39:41 +00002029 // Same behavior as GCC.
2030 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
2031 if (TSK == TSK_ImplicitInstantiation ||
Richard Smith750f5112014-03-24 23:54:09 +00002032 TSK == TSK_ExplicitInstantiationDeclaration ||
Argyrios Kyrtzidis8c64bbe2010-10-13 02:39:41 +00002033 TSK == TSK_ExplicitInstantiationDefinition)
Craig Topper36250ad2014-05-12 05:36:57 +00002034 return nullptr;
Argyrios Kyrtzidis8c64bbe2010-10-13 02:39:41 +00002035
John McCall6bd2a892013-01-25 22:31:03 +00002036 bool allowInlineFunctions =
2037 Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline();
2038
David Majnemerc964b4b2014-07-16 06:04:00 +00002039 for (const CXXMethodDecl *MD : RD->methods()) {
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002040 if (!MD->isVirtual())
2041 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002042
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002043 if (MD->isPure())
2044 continue;
Eli Friedmanf2c79b62009-12-08 03:56:49 +00002045
Anders Carlssonf98849e2009-12-02 17:15:43 +00002046 // Ignore implicit member functions, they are always marked as inline, but
2047 // they don't have a body until they're defined.
2048 if (MD->isImplicit())
2049 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002050
Douglas Gregora318efd2010-01-05 19:06:31 +00002051 if (MD->isInlineSpecified())
2052 continue;
Eli Friedman71a26d82009-12-06 20:50:05 +00002053
2054 if (MD->hasInlineBody())
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002055 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002056
Benjamin Kramer4a902082012-08-03 15:43:22 +00002057 // Ignore inline deleted or defaulted functions.
Benjamin Kramer73d1be72012-08-03 08:39:58 +00002058 if (!MD->isUserProvided())
2059 continue;
2060
John McCall6bd2a892013-01-25 22:31:03 +00002061 // In certain ABIs, ignore functions with out-of-line inline definitions.
2062 if (!allowInlineFunctions) {
2063 const FunctionDecl *Def;
2064 if (MD->hasBody(Def) && Def->isInlineSpecified())
2065 continue;
2066 }
2067
Artem Belevich9b929462015-12-17 18:12:36 +00002068 if (Context.getLangOpts().CUDA) {
2069 // While compiler may see key method in this TU, during CUDA
2070 // compilation we should ignore methods that are not accessible
2071 // on this side of compilation.
2072 if (Context.getLangOpts().CUDAIsDevice) {
2073 // In device mode ignore methods without __device__ attribute.
2074 if (!MD->hasAttr<CUDADeviceAttr>())
2075 continue;
2076 } else {
2077 // In host mode ignore __device__-only methods.
2078 if (!MD->hasAttr<CUDAHostAttr>() && MD->hasAttr<CUDADeviceAttr>())
2079 continue;
2080 }
2081 }
2082
Reid Klecknerc2e3ba42015-08-10 19:39:01 +00002083 // If the key function is dllimport but the class isn't, then the class has
2084 // no key function. The DLL that exports the key function won't export the
2085 // vtable in this case.
2086 if (MD->hasAttr<DLLImportAttr>() && !RD->hasAttr<DLLImportAttr>())
2087 return nullptr;
2088
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002089 // We found it.
2090 return MD;
2091 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002092
Craig Topper36250ad2014-05-12 05:36:57 +00002093 return nullptr;
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002094}
2095
David Majnemer3b1c9902015-07-25 20:18:14 +00002096DiagnosticBuilder ItaniumRecordLayoutBuilder::Diag(SourceLocation Loc,
2097 unsigned DiagID) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +00002098 return Context.getDiagnostics().Report(Loc, DiagID);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002099}
2100
John McCall5c1f1d02013-01-29 01:14:22 +00002101/// Does the target C++ ABI require us to skip over the tail-padding
2102/// of the given class (considering it as a base class) when allocating
2103/// objects?
2104static bool mustSkipTailPadding(TargetCXXABI ABI, const CXXRecordDecl *RD) {
2105 switch (ABI.getTailPaddingUseRules()) {
2106 case TargetCXXABI::AlwaysUseTailPadding:
2107 return false;
2108
2109 case TargetCXXABI::UseTailPaddingUnlessPOD03:
2110 // FIXME: To the extent that this is meant to cover the Itanium ABI
2111 // rules, we should implement the restrictions about over-sized
2112 // bitfields:
2113 //
Vlad Tsyrklevichb1bb99d2017-09-12 00:21:17 +00002114 // http://itanium-cxx-abi.github.io/cxx-abi/abi.html#POD :
John McCall5c1f1d02013-01-29 01:14:22 +00002115 // In general, a type is considered a POD for the purposes of
2116 // layout if it is a POD type (in the sense of ISO C++
2117 // [basic.types]). However, a POD-struct or POD-union (in the
2118 // sense of ISO C++ [class]) with a bitfield member whose
2119 // declared width is wider than the declared type of the
2120 // bitfield is not a POD for the purpose of layout. Similarly,
2121 // an array type is not a POD for the purpose of layout if the
2122 // element type of the array is not a POD for the purpose of
2123 // layout.
2124 //
2125 // Where references to the ISO C++ are made in this paragraph,
2126 // the Technical Corrigendum 1 version of the standard is
2127 // intended.
2128 return RD->isPOD();
2129
2130 case TargetCXXABI::UseTailPaddingUnlessPOD11:
2131 // This is equivalent to RD->getTypeForDecl().isCXX11PODType(),
2132 // but with a lot of abstraction penalty stripped off. This does
2133 // assume that these properties are set correctly even in C++98
2134 // mode; fortunately, that is true because we want to assign
2135 // consistently semantics to the type-traits intrinsics (or at
2136 // least as many of them as possible).
Richard Smithb6070db2018-04-05 18:55:37 +00002137 return RD->isTrivial() && RD->isCXX11StandardLayout();
John McCall5c1f1d02013-01-29 01:14:22 +00002138 }
2139
2140 llvm_unreachable("bad tail-padding use kind");
2141}
2142
David Majnemer3b1c9902015-07-25 20:18:14 +00002143static bool isMsLayout(const ASTContext &Context) {
2144 return Context.getTargetInfo().getCXXABI().isMicrosoft();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002145}
2146
2147// This section contains an implementation of struct layout that is, up to the
Warren Hunt917f97f2014-04-11 00:54:15 +00002148// included tests, compatible with cl.exe (2013). The layout produced is
Warren Hunt8f8bad72013-10-11 20:19:00 +00002149// significantly different than those produced by the Itanium ABI. Here we note
2150// the most important differences.
2151//
2152// * The alignment of bitfields in unions is ignored when computing the
2153// alignment of the union.
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002154// * The existence of zero-width bitfield that occurs after anything other than
Warren Hunt8f8bad72013-10-11 20:19:00 +00002155// a non-zero length bitfield is ignored.
Warren Hunt917f97f2014-04-11 00:54:15 +00002156// * There is no explicit primary base for the purposes of layout. All bases
2157// with vfptrs are laid out first, followed by all bases without vfptrs.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002158// * The Itanium equivalent vtable pointers are split into a vfptr (virtual
2159// function pointer) and a vbptr (virtual base pointer). They can each be
Warren Hunt55d8e822013-10-23 23:53:07 +00002160// shared with a, non-virtual bases. These bases need not be the same. vfptrs
Warren Hunt917f97f2014-04-11 00:54:15 +00002161// always occur at offset 0. vbptrs can occur at an arbitrary offset and are
David Majnemer07639702016-02-12 19:21:02 +00002162// placed after the lexicographically last non-virtual base. This placement
Warren Hunt917f97f2014-04-11 00:54:15 +00002163// is always before fields but can be in the middle of the non-virtual bases
2164// due to the two-pass layout scheme for non-virtual-bases.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002165// * Virtual bases sometimes require a 'vtordisp' field that is laid out before
2166// the virtual base and is used in conjunction with virtual overrides during
Warren Hunt917f97f2014-04-11 00:54:15 +00002167// construction and destruction. This is always a 4 byte value and is used as
2168// an alternative to constructor vtables.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002169// * vtordisps are allocated in a block of memory with size and alignment equal
2170// to the alignment of the completed structure (before applying __declspec(
Warren Hunt55d8e822013-10-23 23:53:07 +00002171// align())). The vtordisp always occur at the end of the allocation block,
2172// immediately prior to the virtual base.
Warren Hunt917f97f2014-04-11 00:54:15 +00002173// * vfptrs are injected after all bases and fields have been laid out. In
2174// order to guarantee proper alignment of all fields, the vfptr injection
2175// pushes all bases and fields back by the alignment imposed by those bases
2176// and fields. This can potentially add a significant amount of padding.
2177// vfptrs are always injected at offset 0.
2178// * vbptrs are injected after all bases and fields have been laid out. In
2179// order to guarantee proper alignment of all fields, the vfptr injection
2180// pushes all bases and fields back by the alignment imposed by those bases
2181// and fields. This can potentially add a significant amount of padding.
2182// vbptrs are injected immediately after the last non-virtual base as
David Majnemer07639702016-02-12 19:21:02 +00002183// lexicographically ordered in the code. If this site isn't pointer aligned
Warren Hunt917f97f2014-04-11 00:54:15 +00002184// the vbptr is placed at the next properly aligned location. Enough padding
2185// is added to guarantee a fit.
2186// * The last zero sized non-virtual base can be placed at the end of the
2187// struct (potentially aliasing another object), or may alias with the first
2188// field, even if they are of the same type.
2189// * The last zero size virtual base may be placed at the end of the struct
2190// potentially aliasing another object.
Warren Hunt049f6732013-12-06 19:54:25 +00002191// * The ABI attempts to avoid aliasing of zero sized bases by adding padding
2192// between bases or vbases with specific properties. The criteria for
2193// additional padding between two bases is that the first base is zero sized
Warren Hunt39a907b2014-04-09 21:57:24 +00002194// or ends with a zero sized subobject and the second base is zero sized or
Warren Hunt917f97f2014-04-11 00:54:15 +00002195// trails with a zero sized base or field (sharing of vfptrs can reorder the
2196// layout of the so the leading base is not always the first one declared).
2197// This rule does take into account fields that are not records, so padding
2198// will occur even if the last field is, e.g. an int. The padding added for
2199// bases is 1 byte. The padding added between vbases depends on the alignment
2200// of the object but is at least 4 bytes (in both 32 and 64 bit modes).
2201// * There is no concept of non-virtual alignment, non-virtual alignment and
2202// alignment are always identical.
2203// * There is a distinction between alignment and required alignment.
2204// __declspec(align) changes the required alignment of a struct. This
2205// alignment is _always_ obeyed, even in the presence of #pragma pack. A
Justin Bogner2ca9a4a2014-10-08 05:45:39 +00002206// record inherits required alignment from all of its fields and bases.
Warren Huntf4518def2014-01-10 01:28:05 +00002207// * __declspec(align) on bitfields has the effect of changing the bitfield's
Warren Hunt917f97f2014-04-11 00:54:15 +00002208// alignment instead of its required alignment. This is the only known way
2209// to make the alignment of a struct bigger than 8. Interestingly enough
2210// this alignment is also immune to the effects of #pragma pack and can be
2211// used to create structures with large alignment under #pragma pack.
2212// However, because it does not impact required alignment, such a structure,
2213// when used as a field or base, will not be aligned if #pragma pack is
2214// still active at the time of use.
2215//
Alp Toker08f6e9e2014-05-05 19:53:42 +00002216// Known incompatibilities:
Warren Hunt917f97f2014-04-11 00:54:15 +00002217// * all: #pragma pack between fields in a record
2218// * 2010 and back: If the last field in a record is a bitfield, every object
2219// laid out after the record will have extra padding inserted before it. The
2220// extra padding will have size equal to the size of the storage class of the
2221// bitfield. 0 sized bitfields don't exhibit this behavior and the extra
2222// padding can be avoided by adding a 0 sized bitfield after the non-zero-
2223// sized bitfield.
2224// * 2012 and back: In 64-bit mode, if the alignment of a record is 16 or
2225// greater due to __declspec(align()) then a second layout phase occurs after
2226// The locations of the vf and vb pointers are known. This layout phase
2227// suffers from the "last field is a bitfield" bug in 2010 and results in
2228// _every_ field getting padding put in front of it, potentially including the
2229// vfptr, leaving the vfprt at a non-zero location which results in a fault if
2230// anything tries to read the vftbl. The second layout phase also treats
Alp Toker08f6e9e2014-05-05 19:53:42 +00002231// bitfields as separate entities and gives them each storage rather than
Warren Hunt917f97f2014-04-11 00:54:15 +00002232// packing them. Additionally, because this phase appears to perform a
2233// (an unstable) sort on the members before laying them out and because merged
2234// bitfields have the same address, the bitfields end up in whatever order
2235// the sort left them in, a behavior we could never hope to replicate.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002236
2237namespace {
2238struct MicrosoftRecordLayoutBuilder {
Warren Huntd640d7d2014-01-09 00:30:56 +00002239 struct ElementInfo {
2240 CharUnits Size;
2241 CharUnits Alignment;
2242 };
Warren Hunt8f8bad72013-10-11 20:19:00 +00002243 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
2244 MicrosoftRecordLayoutBuilder(const ASTContext &Context) : Context(Context) {}
2245private:
Aaron Ballmanabc18922015-02-15 22:54:08 +00002246 MicrosoftRecordLayoutBuilder(const MicrosoftRecordLayoutBuilder &) = delete;
2247 void operator=(const MicrosoftRecordLayoutBuilder &) = delete;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002248public:
Warren Hunt8f8bad72013-10-11 20:19:00 +00002249 void layout(const RecordDecl *RD);
2250 void cxxLayout(const CXXRecordDecl *RD);
2251 /// \brief Initializes size and alignment and honors some flags.
2252 void initializeLayout(const RecordDecl *RD);
2253 /// \brief Initialized C++ layout, compute alignment and virtual alignment and
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002254 /// existence of vfptrs and vbptrs. Alignment is needed before the vfptr is
Warren Hunt8f8bad72013-10-11 20:19:00 +00002255 /// laid out.
2256 void initializeCXXLayout(const CXXRecordDecl *RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002257 void layoutNonVirtualBases(const CXXRecordDecl *RD);
David Majnemercd3ebfe2016-05-23 17:16:12 +00002258 void layoutNonVirtualBase(const CXXRecordDecl *RD,
2259 const CXXRecordDecl *BaseDecl,
Warren Huntd640d7d2014-01-09 00:30:56 +00002260 const ASTRecordLayout &BaseLayout,
2261 const ASTRecordLayout *&PreviousBaseLayout);
2262 void injectVFPtr(const CXXRecordDecl *RD);
2263 void injectVBPtr(const CXXRecordDecl *RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002264 /// \brief Lays out the fields of the record. Also rounds size up to
2265 /// alignment.
2266 void layoutFields(const RecordDecl *RD);
2267 void layoutField(const FieldDecl *FD);
2268 void layoutBitField(const FieldDecl *FD);
2269 /// \brief Lays out a single zero-width bit-field in the record and handles
2270 /// special cases associated with zero-width bit-fields.
2271 void layoutZeroWidthBitField(const FieldDecl *FD);
2272 void layoutVirtualBases(const CXXRecordDecl *RD);
Warren Hunt1603e522013-12-10 01:44:39 +00002273 void finalizeLayout(const RecordDecl *RD);
Warren Huntd640d7d2014-01-09 00:30:56 +00002274 /// \brief Gets the size and alignment of a base taking pragma pack and
2275 /// __declspec(align) into account.
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002276 ElementInfo getAdjustedElementInfo(const ASTRecordLayout &Layout);
Warren Huntd640d7d2014-01-09 00:30:56 +00002277 /// \brief Gets the size and alignment of a field taking pragma pack and
2278 /// __declspec(align) into account. It also updates RequiredAlignment as a
2279 /// side effect because it is most convenient to do so here.
2280 ElementInfo getAdjustedElementInfo(const FieldDecl *FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002281 /// \brief Places a field at an offset in CharUnits.
2282 void placeFieldAtOffset(CharUnits FieldOffset) {
2283 FieldOffsets.push_back(Context.toBits(FieldOffset));
2284 }
2285 /// \brief Places a bitfield at a bit offset.
2286 void placeFieldAtBitOffset(uint64_t FieldOffset) {
2287 FieldOffsets.push_back(FieldOffset);
2288 }
2289 /// \brief Compute the set of virtual bases for which vtordisps are required.
David Majnemerc2e67532014-09-23 22:58:15 +00002290 void computeVtorDispSet(
2291 llvm::SmallPtrSetImpl<const CXXRecordDecl *> &HasVtorDispSet,
2292 const CXXRecordDecl *RD) const;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002293 const ASTContext &Context;
2294 /// \brief The size of the record being laid out.
2295 CharUnits Size;
Warren Huntf6ec7482014-02-21 01:40:35 +00002296 /// \brief The non-virtual size of the record layout.
2297 CharUnits NonVirtualSize;
2298 /// \brief The data size of the record layout.
Warren Huntd640d7d2014-01-09 00:30:56 +00002299 CharUnits DataSize;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002300 /// \brief The current alignment of the record layout.
2301 CharUnits Alignment;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002302 /// \brief The maximum allowed field alignment. This is set by #pragma pack.
2303 CharUnits MaxFieldAlignment;
Warren Hunt7b252d22013-12-06 00:01:17 +00002304 /// \brief The alignment that this record must obey. This is imposed by
2305 /// __declspec(align()) on the record itself or one of its fields or bases.
2306 CharUnits RequiredAlignment;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002307 /// \brief The size of the allocation of the currently active bitfield.
2308 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield
2309 /// is true.
2310 CharUnits CurrentBitfieldSize;
Warren Huntd640d7d2014-01-09 00:30:56 +00002311 /// \brief Offset to the virtual base table pointer (if one exists).
2312 CharUnits VBPtrOffset;
David Majnemer00a061d2014-09-30 06:45:43 +00002313 /// \brief Minimum record size possible.
2314 CharUnits MinEmptyStructSize;
Warren Huntd640d7d2014-01-09 00:30:56 +00002315 /// \brief The size and alignment info of a pointer.
2316 ElementInfo PointerInfo;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002317 /// \brief The primary base class (if one exists).
2318 const CXXRecordDecl *PrimaryBase;
2319 /// \brief The class we share our vb-pointer with.
2320 const CXXRecordDecl *SharedVBPtrBase;
Warren Huntd640d7d2014-01-09 00:30:56 +00002321 /// \brief The collection of field offsets.
2322 SmallVector<uint64_t, 16> FieldOffsets;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002323 /// \brief Base classes and their offsets in the record.
2324 BaseOffsetsMapTy Bases;
2325 /// \brief virtual base classes and their offsets in the record.
2326 ASTRecordLayout::VBaseOffsetsMapTy VBases;
Warren Huntd640d7d2014-01-09 00:30:56 +00002327 /// \brief The number of remaining bits in our last bitfield allocation.
2328 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield is
2329 /// true.
2330 unsigned RemainingBitsInField;
2331 bool IsUnion : 1;
2332 /// \brief True if the last field laid out was a bitfield and was not 0
2333 /// width.
2334 bool LastFieldIsNonZeroWidthBitfield : 1;
2335 /// \brief True if the class has its own vftable pointer.
2336 bool HasOwnVFPtr : 1;
2337 /// \brief True if the class has a vbtable pointer.
2338 bool HasVBPtr : 1;
Warren Hunt39a907b2014-04-09 21:57:24 +00002339 /// \brief True if the last sub-object within the type is zero sized or the
2340 /// object itself is zero sized. This *does not* count members that are not
2341 /// records. Only used for MS-ABI.
2342 bool EndsWithZeroSizedObject : 1;
Warren Hunt049f6732013-12-06 19:54:25 +00002343 /// \brief True if this class is zero sized or first base is zero sized or
2344 /// has this property. Only used for MS-ABI.
2345 bool LeadsWithZeroSizedBase : 1;
Reid Kleckner8b6d0342015-02-25 19:17:45 +00002346
2347 /// \brief True if the external AST source provided a layout for this record.
2348 bool UseExternalLayout : 1;
2349
2350 /// \brief The layout provided by the external AST source. Only active if
2351 /// UseExternalLayout is true.
2352 ExternalLayout External;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002353};
2354} // namespace
2355
Warren Huntd640d7d2014-01-09 00:30:56 +00002356MicrosoftRecordLayoutBuilder::ElementInfo
2357MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002358 const ASTRecordLayout &Layout) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002359 ElementInfo Info;
2360 Info.Alignment = Layout.getAlignment();
2361 // Respect pragma pack.
Warren Hunt7b252d22013-12-06 00:01:17 +00002362 if (!MaxFieldAlignment.isZero())
Warren Huntd640d7d2014-01-09 00:30:56 +00002363 Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
2364 // Track zero-sized subobjects here where it's already available.
David Majnemercd3ebfe2016-05-23 17:16:12 +00002365 EndsWithZeroSizedObject = Layout.endsWithZeroSizedObject();
Warren Huntd640d7d2014-01-09 00:30:56 +00002366 // Respect required alignment, this is necessary because we may have adjusted
Warren Hunt94258912014-01-11 01:16:40 +00002367 // the alignment in the case of pragam pack. Note that the required alignment
2368 // doesn't actually apply to the struct alignment at this point.
2369 Alignment = std::max(Alignment, Info.Alignment);
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002370 RequiredAlignment = std::max(RequiredAlignment, Layout.getRequiredAlignment());
Warren Huntd640d7d2014-01-09 00:30:56 +00002371 Info.Alignment = std::max(Info.Alignment, Layout.getRequiredAlignment());
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002372 Info.Size = Layout.getNonVirtualSize();
Warren Huntd640d7d2014-01-09 00:30:56 +00002373 return Info;
Warren Hunt7b252d22013-12-06 00:01:17 +00002374}
2375
Warren Huntd640d7d2014-01-09 00:30:56 +00002376MicrosoftRecordLayoutBuilder::ElementInfo
2377MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
2378 const FieldDecl *FD) {
David Majnemer34b57492014-07-30 01:30:47 +00002379 // Get the alignment of the field type's natural alignment, ignore any
2380 // alignment attributes.
Warren Huntd640d7d2014-01-09 00:30:56 +00002381 ElementInfo Info;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002382 std::tie(Info.Size, Info.Alignment) =
David Majnemer34b57492014-07-30 01:30:47 +00002383 Context.getTypeInfoInChars(FD->getType()->getUnqualifiedDesugaredType());
2384 // Respect align attributes on the field.
2385 CharUnits FieldRequiredAlignment =
Warren Huntf4518def2014-01-10 01:28:05 +00002386 Context.toCharUnitsFromBits(FD->getMaxAlignment());
David Majnemer34b57492014-07-30 01:30:47 +00002387 // Respect align attributes on the type.
2388 if (Context.isAlignmentRequired(FD->getType()))
2389 FieldRequiredAlignment = std::max(
2390 Context.getTypeAlignInChars(FD->getType()), FieldRequiredAlignment);
Warren Hunt049f6732013-12-06 19:54:25 +00002391 // Respect attributes applied to subobjects of the field.
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002392 if (FD->isBitField())
2393 // For some reason __declspec align impacts alignment rather than required
2394 // alignment when it is applied to bitfields.
Warren Huntf4518def2014-01-10 01:28:05 +00002395 Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002396 else {
2397 if (auto RT =
2398 FD->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
2399 auto const &Layout = Context.getASTRecordLayout(RT->getDecl());
David Majnemercd3ebfe2016-05-23 17:16:12 +00002400 EndsWithZeroSizedObject = Layout.endsWithZeroSizedObject();
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002401 FieldRequiredAlignment = std::max(FieldRequiredAlignment,
2402 Layout.getRequiredAlignment());
2403 }
Warren Huntf4518def2014-01-10 01:28:05 +00002404 // Capture required alignment as a side-effect.
2405 RequiredAlignment = std::max(RequiredAlignment, FieldRequiredAlignment);
2406 }
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002407 // Respect pragma pack, attribute pack and declspec align
2408 if (!MaxFieldAlignment.isZero())
2409 Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
2410 if (FD->hasAttr<PackedAttr>())
2411 Info.Alignment = CharUnits::One();
2412 Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002413 return Info;
2414}
2415
2416void MicrosoftRecordLayoutBuilder::layout(const RecordDecl *RD) {
David Majnemer00a061d2014-09-30 06:45:43 +00002417 // For C record layout, zero-sized records always have size 4.
2418 MinEmptyStructSize = CharUnits::fromQuantity(4);
Warren Huntd640d7d2014-01-09 00:30:56 +00002419 initializeLayout(RD);
2420 layoutFields(RD);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002421 DataSize = Size = Size.alignTo(Alignment);
David Majnemer79a1c892014-02-12 00:43:02 +00002422 RequiredAlignment = std::max(
2423 RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
Warren Huntd640d7d2014-01-09 00:30:56 +00002424 finalizeLayout(RD);
2425}
2426
2427void MicrosoftRecordLayoutBuilder::cxxLayout(const CXXRecordDecl *RD) {
David Majnemer00a061d2014-09-30 06:45:43 +00002428 // The C++ standard says that empty structs have size 1.
2429 MinEmptyStructSize = CharUnits::One();
Warren Huntd640d7d2014-01-09 00:30:56 +00002430 initializeLayout(RD);
2431 initializeCXXLayout(RD);
2432 layoutNonVirtualBases(RD);
2433 layoutFields(RD);
Warren Huntc89450e2014-03-24 21:37:27 +00002434 injectVBPtr(RD);
2435 injectVFPtr(RD);
2436 if (HasOwnVFPtr || (HasVBPtr && !SharedVBPtrBase))
2437 Alignment = std::max(Alignment, PointerInfo.Alignment);
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002438 auto RoundingAlignment = Alignment;
2439 if (!MaxFieldAlignment.isZero())
2440 RoundingAlignment = std::min(RoundingAlignment, MaxFieldAlignment);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002441 NonVirtualSize = Size = Size.alignTo(RoundingAlignment);
David Majnemer79a1c892014-02-12 00:43:02 +00002442 RequiredAlignment = std::max(
2443 RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
Warren Huntd640d7d2014-01-09 00:30:56 +00002444 layoutVirtualBases(RD);
2445 finalizeLayout(RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002446}
2447
2448void MicrosoftRecordLayoutBuilder::initializeLayout(const RecordDecl *RD) {
2449 IsUnion = RD->isUnion();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002450 Size = CharUnits::Zero();
2451 Alignment = CharUnits::One();
Warren Hunt7b252d22013-12-06 00:01:17 +00002452 // In 64-bit mode we always perform an alignment step after laying out vbases.
2453 // In 32-bit mode we do not. The check to see if we need to perform alignment
2454 // checks the RequiredAlignment field and performs alignment if it isn't 0.
David Majnemer37ea5782015-04-24 01:24:59 +00002455 RequiredAlignment = Context.getTargetInfo().getTriple().isArch64Bit()
2456 ? CharUnits::One()
2457 : CharUnits::Zero();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002458 // Compute the maximum field alignment.
2459 MaxFieldAlignment = CharUnits::Zero();
2460 // Honor the default struct packing maximum alignment flag.
2461 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct)
Warren Huntf4518def2014-01-10 01:28:05 +00002462 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
2463 // Honor the packing attribute. The MS-ABI ignores pragma pack if its larger
2464 // than the pointer size.
2465 if (const MaxFieldAlignmentAttr *MFAA = RD->getAttr<MaxFieldAlignmentAttr>()){
2466 unsigned PackedAlignment = MFAA->getAlignment();
2467 if (PackedAlignment <= Context.getTargetInfo().getPointerWidth(0))
2468 MaxFieldAlignment = Context.toCharUnitsFromBits(PackedAlignment);
2469 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002470 // Packed attribute forces max field alignment to be 1.
2471 if (RD->hasAttr<PackedAttr>())
2472 MaxFieldAlignment = CharUnits::One();
Reid Kleckner8b6d0342015-02-25 19:17:45 +00002473
2474 // Try to respect the external layout if present.
2475 UseExternalLayout = false;
2476 if (ExternalASTSource *Source = Context.getExternalSource())
2477 UseExternalLayout = Source->layoutRecordType(
2478 RD, External.Size, External.Align, External.FieldOffsets,
2479 External.BaseOffsets, External.VirtualBaseOffsets);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002480}
2481
Warren Hunt8f8bad72013-10-11 20:19:00 +00002482void
2483MicrosoftRecordLayoutBuilder::initializeCXXLayout(const CXXRecordDecl *RD) {
Warren Hunt39a907b2014-04-09 21:57:24 +00002484 EndsWithZeroSizedObject = false;
Warren Hunt049f6732013-12-06 19:54:25 +00002485 LeadsWithZeroSizedBase = false;
Warren Huntd640d7d2014-01-09 00:30:56 +00002486 HasOwnVFPtr = false;
2487 HasVBPtr = false;
Craig Topper36250ad2014-05-12 05:36:57 +00002488 PrimaryBase = nullptr;
2489 SharedVBPtrBase = nullptr;
Warren Huntd640d7d2014-01-09 00:30:56 +00002490 // Calculate pointer size and alignment. These are used for vfptr and vbprt
2491 // injection.
2492 PointerInfo.Size =
2493 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
David Majnemer37ea5782015-04-24 01:24:59 +00002494 PointerInfo.Alignment =
2495 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
Warren Huntd640d7d2014-01-09 00:30:56 +00002496 // Respect pragma pack.
2497 if (!MaxFieldAlignment.isZero())
2498 PointerInfo.Alignment = std::min(PointerInfo.Alignment, MaxFieldAlignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002499}
2500
2501void
2502MicrosoftRecordLayoutBuilder::layoutNonVirtualBases(const CXXRecordDecl *RD) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002503 // The MS-ABI lays out all bases that contain leading vfptrs before it lays
2504 // out any bases that do not contain vfptrs. We implement this as two passes
2505 // over the bases. This approach guarantees that the primary base is laid out
2506 // first. We use these passes to calculate some additional aggregated
David Majnemer07639702016-02-12 19:21:02 +00002507 // information about the bases, such as required alignment and the presence of
Warren Huntd640d7d2014-01-09 00:30:56 +00002508 // zero sized members.
Craig Topper36250ad2014-05-12 05:36:57 +00002509 const ASTRecordLayout *PreviousBaseLayout = nullptr;
Warren Huntd640d7d2014-01-09 00:30:56 +00002510 // Iterate through the bases and lay out the non-virtual ones.
David Majnemerc964b4b2014-07-16 06:04:00 +00002511 for (const CXXBaseSpecifier &Base : RD->bases()) {
2512 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002513 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
Warren Huntd640d7d2014-01-09 00:30:56 +00002514 // Mark and skip virtual bases.
David Majnemerc964b4b2014-07-16 06:04:00 +00002515 if (Base.isVirtual()) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002516 HasVBPtr = true;
2517 continue;
2518 }
David Majnemer07639702016-02-12 19:21:02 +00002519 // Check for a base to share a VBPtr with.
Warren Huntd640d7d2014-01-09 00:30:56 +00002520 if (!SharedVBPtrBase && BaseLayout.hasVBPtr()) {
2521 SharedVBPtrBase = BaseDecl;
2522 HasVBPtr = true;
2523 }
2524 // Only lay out bases with extendable VFPtrs on the first pass.
2525 if (!BaseLayout.hasExtendableVFPtr())
2526 continue;
2527 // If we don't have a primary base, this one qualifies.
Warren Huntbadf9e02014-01-13 19:55:52 +00002528 if (!PrimaryBase) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002529 PrimaryBase = BaseDecl;
Warren Huntbadf9e02014-01-13 19:55:52 +00002530 LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
2531 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002532 // Lay out the base.
David Majnemercd3ebfe2016-05-23 17:16:12 +00002533 layoutNonVirtualBase(RD, BaseDecl, BaseLayout, PreviousBaseLayout);
Warren Huntd640d7d2014-01-09 00:30:56 +00002534 }
2535 // Figure out if we need a fresh VFPtr for this class.
2536 if (!PrimaryBase && RD->isDynamicClass())
2537 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2538 e = RD->method_end();
2539 !HasOwnVFPtr && i != e; ++i)
2540 HasOwnVFPtr = i->isVirtual() && i->size_overridden_methods() == 0;
2541 // If we don't have a primary base then we have a leading object that could
2542 // itself lead with a zero-sized object, something we track.
2543 bool CheckLeadingLayout = !PrimaryBase;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002544 // Iterate through the bases and lay out the non-virtual ones.
David Majnemerc964b4b2014-07-16 06:04:00 +00002545 for (const CXXBaseSpecifier &Base : RD->bases()) {
2546 if (Base.isVirtual())
Warren Hunt8f8bad72013-10-11 20:19:00 +00002547 continue;
David Majnemerc964b4b2014-07-16 06:04:00 +00002548 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002549 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2550 // Only lay out bases without extendable VFPtrs on the second pass.
Warren Huntbb9c3c32014-04-10 23:23:34 +00002551 if (BaseLayout.hasExtendableVFPtr()) {
2552 VBPtrOffset = Bases[BaseDecl] + BaseLayout.getNonVirtualSize();
Warren Hunt4431fe62013-12-12 22:33:37 +00002553 continue;
Warren Huntbb9c3c32014-04-10 23:23:34 +00002554 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002555 // If this is the first layout, check to see if it leads with a zero sized
2556 // object. If it does, so do we.
2557 if (CheckLeadingLayout) {
2558 CheckLeadingLayout = false;
2559 LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
Warren Hunt049f6732013-12-06 19:54:25 +00002560 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002561 // Lay out the base.
David Majnemercd3ebfe2016-05-23 17:16:12 +00002562 layoutNonVirtualBase(RD, BaseDecl, BaseLayout, PreviousBaseLayout);
Warren Huntbb9c3c32014-04-10 23:23:34 +00002563 VBPtrOffset = Bases[BaseDecl] + BaseLayout.getNonVirtualSize();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002564 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002565 // Set our VBPtroffset if we know it at this point.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002566 if (!HasVBPtr)
2567 VBPtrOffset = CharUnits::fromQuantity(-1);
Warren Hunt6eba9072014-01-14 00:31:30 +00002568 else if (SharedVBPtrBase) {
2569 const ASTRecordLayout &Layout = Context.getASTRecordLayout(SharedVBPtrBase);
2570 VBPtrOffset = Bases[SharedVBPtrBase] + Layout.getVBPtrOffset();
2571 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002572}
2573
David Majnemercd3ebfe2016-05-23 17:16:12 +00002574static bool recordUsesEBO(const RecordDecl *RD) {
2575 if (!isa<CXXRecordDecl>(RD))
2576 return false;
2577 if (RD->hasAttr<EmptyBasesAttr>())
2578 return true;
2579 if (auto *LVA = RD->getAttr<LayoutVersionAttr>())
2580 // TODO: Double check with the next version of MSVC.
2581 if (LVA->getVersion() <= LangOptions::MSVC2015)
2582 return false;
2583 // TODO: Some later version of MSVC will change the default behavior of the
2584 // compiler to enable EBO by default. When this happens, we will need an
2585 // additional isCompatibleWithMSVC check.
2586 return false;
2587}
2588
Warren Huntd640d7d2014-01-09 00:30:56 +00002589void MicrosoftRecordLayoutBuilder::layoutNonVirtualBase(
David Majnemercd3ebfe2016-05-23 17:16:12 +00002590 const CXXRecordDecl *RD,
Warren Huntd640d7d2014-01-09 00:30:56 +00002591 const CXXRecordDecl *BaseDecl,
2592 const ASTRecordLayout &BaseLayout,
2593 const ASTRecordLayout *&PreviousBaseLayout) {
Warren Huntf4518def2014-01-10 01:28:05 +00002594 // Insert padding between two bases if the left first one is zero sized or
2595 // contains a zero sized subobject and the right is zero sized or one leads
2596 // with a zero sized base.
David Majnemercd3ebfe2016-05-23 17:16:12 +00002597 bool MDCUsesEBO = recordUsesEBO(RD);
2598 if (PreviousBaseLayout && PreviousBaseLayout->endsWithZeroSizedObject() &&
2599 BaseLayout.leadsWithZeroSizedBase() && !MDCUsesEBO)
Warren Huntf4518def2014-01-10 01:28:05 +00002600 Size++;
2601 ElementInfo Info = getAdjustedElementInfo(BaseLayout);
Reid Kleckner8b6d0342015-02-25 19:17:45 +00002602 CharUnits BaseOffset;
2603
2604 // Respect the external AST source base offset, if present.
2605 bool FoundBase = false;
2606 if (UseExternalLayout) {
2607 FoundBase = External.getExternalNVBaseOffset(BaseDecl, BaseOffset);
David Majnemercd3ebfe2016-05-23 17:16:12 +00002608 if (FoundBase) {
Reid Kleckner8b6d0342015-02-25 19:17:45 +00002609 assert(BaseOffset >= Size && "base offset already allocated");
David Majnemercd3ebfe2016-05-23 17:16:12 +00002610 Size = BaseOffset;
2611 }
Reid Kleckner8b6d0342015-02-25 19:17:45 +00002612 }
2613
David Majnemercd3ebfe2016-05-23 17:16:12 +00002614 if (!FoundBase) {
2615 if (MDCUsesEBO && BaseDecl->isEmpty() &&
2616 BaseLayout.getNonVirtualSize() == CharUnits::Zero()) {
2617 BaseOffset = CharUnits::Zero();
2618 } else {
2619 // Otherwise, lay the base out at the end of the MDC.
2620 BaseOffset = Size = Size.alignTo(Info.Alignment);
2621 }
2622 }
Warren Huntf4518def2014-01-10 01:28:05 +00002623 Bases.insert(std::make_pair(BaseDecl, BaseOffset));
David Majnemercd3ebfe2016-05-23 17:16:12 +00002624 Size += BaseLayout.getNonVirtualSize();
Warren Huntf4518def2014-01-10 01:28:05 +00002625 PreviousBaseLayout = &BaseLayout;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002626}
2627
2628void MicrosoftRecordLayoutBuilder::layoutFields(const RecordDecl *RD) {
2629 LastFieldIsNonZeroWidthBitfield = false;
David Majnemerc964b4b2014-07-16 06:04:00 +00002630 for (const FieldDecl *Field : RD->fields())
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002631 layoutField(Field);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002632}
2633
2634void MicrosoftRecordLayoutBuilder::layoutField(const FieldDecl *FD) {
2635 if (FD->isBitField()) {
2636 layoutBitField(FD);
2637 return;
2638 }
2639 LastFieldIsNonZeroWidthBitfield = false;
Warren Huntd640d7d2014-01-09 00:30:56 +00002640 ElementInfo Info = getAdjustedElementInfo(FD);
David Majnemeradc45bb2014-04-13 08:15:50 +00002641 Alignment = std::max(Alignment, Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002642 if (IsUnion) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002643 placeFieldAtOffset(CharUnits::Zero());
2644 Size = std::max(Size, Info.Size);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002645 } else {
Reid Kleckner8b6d0342015-02-25 19:17:45 +00002646 CharUnits FieldOffset;
2647 if (UseExternalLayout) {
2648 FieldOffset =
2649 Context.toCharUnitsFromBits(External.getExternalFieldOffset(FD));
2650 assert(FieldOffset >= Size && "field offset already allocated");
2651 } else {
Rui Ueyama83aa9792016-01-14 21:00:27 +00002652 FieldOffset = Size.alignTo(Info.Alignment);
Reid Kleckner8b6d0342015-02-25 19:17:45 +00002653 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002654 placeFieldAtOffset(FieldOffset);
Warren Huntd640d7d2014-01-09 00:30:56 +00002655 Size = FieldOffset + Info.Size;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002656 }
2657}
2658
2659void MicrosoftRecordLayoutBuilder::layoutBitField(const FieldDecl *FD) {
2660 unsigned Width = FD->getBitWidthValue(Context);
2661 if (Width == 0) {
2662 layoutZeroWidthBitField(FD);
2663 return;
2664 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002665 ElementInfo Info = getAdjustedElementInfo(FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002666 // Clamp the bitfield to a containable size for the sake of being able
2667 // to lay them out. Sema will throw an error.
Warren Huntd640d7d2014-01-09 00:30:56 +00002668 if (Width > Context.toBits(Info.Size))
2669 Width = Context.toBits(Info.Size);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002670 // Check to see if this bitfield fits into an existing allocation. Note:
2671 // MSVC refuses to pack bitfields of formal types with different sizes
2672 // into the same allocation.
2673 if (!IsUnion && LastFieldIsNonZeroWidthBitfield &&
Warren Huntd640d7d2014-01-09 00:30:56 +00002674 CurrentBitfieldSize == Info.Size && Width <= RemainingBitsInField) {
Warren Hunt8f8bad72013-10-11 20:19:00 +00002675 placeFieldAtBitOffset(Context.toBits(Size) - RemainingBitsInField);
2676 RemainingBitsInField -= Width;
2677 return;
2678 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002679 LastFieldIsNonZeroWidthBitfield = true;
Warren Huntd640d7d2014-01-09 00:30:56 +00002680 CurrentBitfieldSize = Info.Size;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002681 if (IsUnion) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002682 placeFieldAtOffset(CharUnits::Zero());
2683 Size = std::max(Size, Info.Size);
David Majnemeradc45bb2014-04-13 08:15:50 +00002684 // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002685 } else {
2686 // Allocate a new block of memory and place the bitfield in it.
Rui Ueyama83aa9792016-01-14 21:00:27 +00002687 CharUnits FieldOffset = Size.alignTo(Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002688 placeFieldAtOffset(FieldOffset);
Warren Huntd640d7d2014-01-09 00:30:56 +00002689 Size = FieldOffset + Info.Size;
David Majnemeradc45bb2014-04-13 08:15:50 +00002690 Alignment = std::max(Alignment, Info.Alignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002691 RemainingBitsInField = Context.toBits(Info.Size) - Width;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002692 }
2693}
2694
2695void
2696MicrosoftRecordLayoutBuilder::layoutZeroWidthBitField(const FieldDecl *FD) {
2697 // Zero-width bitfields are ignored unless they follow a non-zero-width
2698 // bitfield.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002699 if (!LastFieldIsNonZeroWidthBitfield) {
2700 placeFieldAtOffset(IsUnion ? CharUnits::Zero() : Size);
2701 // TODO: Add a Sema warning that MS ignores alignment for zero
Alp Tokerd4733632013-12-05 04:47:09 +00002702 // sized bitfields that occur after zero-size bitfields or non-bitfields.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002703 return;
2704 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002705 LastFieldIsNonZeroWidthBitfield = false;
Warren Huntd640d7d2014-01-09 00:30:56 +00002706 ElementInfo Info = getAdjustedElementInfo(FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002707 if (IsUnion) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002708 placeFieldAtOffset(CharUnits::Zero());
2709 Size = std::max(Size, Info.Size);
David Majnemeradc45bb2014-04-13 08:15:50 +00002710 // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002711 } else {
2712 // Round up the current record size to the field's alignment boundary.
Rui Ueyama83aa9792016-01-14 21:00:27 +00002713 CharUnits FieldOffset = Size.alignTo(Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002714 placeFieldAtOffset(FieldOffset);
2715 Size = FieldOffset;
David Majnemeradc45bb2014-04-13 08:15:50 +00002716 Alignment = std::max(Alignment, Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002717 }
2718}
2719
Warren Huntd640d7d2014-01-09 00:30:56 +00002720void MicrosoftRecordLayoutBuilder::injectVBPtr(const CXXRecordDecl *RD) {
Warren Hunt6eba9072014-01-14 00:31:30 +00002721 if (!HasVBPtr || SharedVBPtrBase)
Warren Huntd640d7d2014-01-09 00:30:56 +00002722 return;
Warren Huntd640d7d2014-01-09 00:30:56 +00002723 // Inject the VBPointer at the injection site.
2724 CharUnits InjectionSite = VBPtrOffset;
2725 // But before we do, make sure it's properly aligned.
Rui Ueyama83aa9792016-01-14 21:00:27 +00002726 VBPtrOffset = VBPtrOffset.alignTo(PointerInfo.Alignment);
Reid Kleckner8b6d0342015-02-25 19:17:45 +00002727 // Shift everything after the vbptr down, unless we're using an external
2728 // layout.
2729 if (UseExternalLayout)
2730 return;
Warren Huntd640d7d2014-01-09 00:30:56 +00002731 // Determine where the first field should be laid out after the vbptr.
2732 CharUnits FieldStart = VBPtrOffset + PointerInfo.Size;
2733 // Make sure that the amount we push the fields back by is a multiple of the
2734 // alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00002735 CharUnits Offset = (FieldStart - InjectionSite)
2736 .alignTo(std::max(RequiredAlignment, Alignment));
Warren Huntd640d7d2014-01-09 00:30:56 +00002737 Size += Offset;
David Majnemerc964b4b2014-07-16 06:04:00 +00002738 for (uint64_t &FieldOffset : FieldOffsets)
2739 FieldOffset += Context.toBits(Offset);
2740 for (BaseOffsetsMapTy::value_type &Base : Bases)
2741 if (Base.second >= InjectionSite)
2742 Base.second += Offset;
Warren Huntd640d7d2014-01-09 00:30:56 +00002743}
2744
2745void MicrosoftRecordLayoutBuilder::injectVFPtr(const CXXRecordDecl *RD) {
2746 if (!HasOwnVFPtr)
2747 return;
2748 // Make sure that the amount we push the struct back by is a multiple of the
2749 // alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00002750 CharUnits Offset =
2751 PointerInfo.Size.alignTo(std::max(RequiredAlignment, Alignment));
Zachary Turnerf686a442015-10-01 22:08:02 +00002752 // Push back the vbptr, but increase the size of the object and push back
2753 // regular fields by the offset only if not using external record layout.
Warren Huntd640d7d2014-01-09 00:30:56 +00002754 if (HasVBPtr)
2755 VBPtrOffset += Offset;
Zachary Turnerf686a442015-10-01 22:08:02 +00002756
2757 if (UseExternalLayout)
2758 return;
2759
2760 Size += Offset;
2761
2762 // If we're using an external layout, the fields offsets have already
2763 // accounted for this adjustment.
2764 for (uint64_t &FieldOffset : FieldOffsets)
2765 FieldOffset += Context.toBits(Offset);
David Majnemerc964b4b2014-07-16 06:04:00 +00002766 for (BaseOffsetsMapTy::value_type &Base : Bases)
2767 Base.second += Offset;
Warren Huntd640d7d2014-01-09 00:30:56 +00002768}
2769
Warren Hunt8f8bad72013-10-11 20:19:00 +00002770void MicrosoftRecordLayoutBuilder::layoutVirtualBases(const CXXRecordDecl *RD) {
2771 if (!HasVBPtr)
2772 return;
Warren Huntd640d7d2014-01-09 00:30:56 +00002773 // Vtordisps are always 4 bytes (even in 64-bit mode)
2774 CharUnits VtorDispSize = CharUnits::fromQuantity(4);
2775 CharUnits VtorDispAlignment = VtorDispSize;
2776 // vtordisps respect pragma pack.
2777 if (!MaxFieldAlignment.isZero())
2778 VtorDispAlignment = std::min(VtorDispAlignment, MaxFieldAlignment);
2779 // The alignment of the vtordisp is at least the required alignment of the
2780 // entire record. This requirement may be present to support vtordisp
2781 // injection.
David Majnemerc964b4b2014-07-16 06:04:00 +00002782 for (const CXXBaseSpecifier &VBase : RD->vbases()) {
2783 const CXXRecordDecl *BaseDecl = VBase.getType()->getAsCXXRecordDecl();
David Majnemer79a1c892014-02-12 00:43:02 +00002784 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2785 RequiredAlignment =
2786 std::max(RequiredAlignment, BaseLayout.getRequiredAlignment());
2787 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002788 VtorDispAlignment = std::max(VtorDispAlignment, RequiredAlignment);
2789 // Compute the vtordisp set.
David Majnemerc2e67532014-09-23 22:58:15 +00002790 llvm::SmallPtrSet<const CXXRecordDecl *, 2> HasVtorDispSet;
2791 computeVtorDispSet(HasVtorDispSet, RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002792 // Iterate through the virtual bases and lay them out.
Craig Topper36250ad2014-05-12 05:36:57 +00002793 const ASTRecordLayout *PreviousBaseLayout = nullptr;
David Majnemerc964b4b2014-07-16 06:04:00 +00002794 for (const CXXBaseSpecifier &VBase : RD->vbases()) {
2795 const CXXRecordDecl *BaseDecl = VBase.getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002796 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
David Majnemerc2e67532014-09-23 22:58:15 +00002797 bool HasVtordisp = HasVtorDispSet.count(BaseDecl) > 0;
Warren Huntd640d7d2014-01-09 00:30:56 +00002798 // Insert padding between two bases if the left first one is zero sized or
2799 // contains a zero sized subobject and the right is zero sized or one leads
2800 // with a zero sized base. The padding between virtual bases is 4
2801 // bytes (in both 32 and 64 bits modes) and always involves rounding up to
2802 // the required alignment, we don't know why.
David Majnemercd3ebfe2016-05-23 17:16:12 +00002803 if ((PreviousBaseLayout && PreviousBaseLayout->endsWithZeroSizedObject() &&
2804 BaseLayout.leadsWithZeroSizedBase() && !recordUsesEBO(RD)) ||
2805 HasVtordisp) {
Rui Ueyama83aa9792016-01-14 21:00:27 +00002806 Size = Size.alignTo(VtorDispAlignment) + VtorDispSize;
David Majnemera2464682014-07-17 00:55:19 +00002807 Alignment = std::max(VtorDispAlignment, Alignment);
David Majnemerbf3d4302014-07-16 07:16:58 +00002808 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002809 // Insert the virtual base.
2810 ElementInfo Info = getAdjustedElementInfo(BaseLayout);
Reid Kleckner8b6d0342015-02-25 19:17:45 +00002811 CharUnits BaseOffset;
2812
2813 // Respect the external AST source base offset, if present.
2814 bool FoundBase = false;
2815 if (UseExternalLayout) {
2816 FoundBase = External.getExternalVBaseOffset(BaseDecl, BaseOffset);
2817 if (FoundBase)
2818 assert(BaseOffset >= Size && "base offset already allocated");
2819 }
2820 if (!FoundBase)
Rui Ueyama83aa9792016-01-14 21:00:27 +00002821 BaseOffset = Size.alignTo(Info.Alignment);
Reid Kleckner8b6d0342015-02-25 19:17:45 +00002822
Warren Huntd640d7d2014-01-09 00:30:56 +00002823 VBases.insert(std::make_pair(BaseDecl,
2824 ASTRecordLayout::VBaseInfo(BaseOffset, HasVtordisp)));
Warren Huntf6ec7482014-02-21 01:40:35 +00002825 Size = BaseOffset + BaseLayout.getNonVirtualSize();
Warren Huntd640d7d2014-01-09 00:30:56 +00002826 PreviousBaseLayout = &BaseLayout;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002827 }
2828}
2829
Warren Huntc3384312013-12-11 22:28:32 +00002830void MicrosoftRecordLayoutBuilder::finalizeLayout(const RecordDecl *RD) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002831 // Respect required alignment. Note that in 32-bit mode Required alignment
David Majnemer00a061d2014-09-30 06:45:43 +00002832 // may be 0 and cause size not to be updated.
Warren Huntf6ec7482014-02-21 01:40:35 +00002833 DataSize = Size;
Warren Huntd640d7d2014-01-09 00:30:56 +00002834 if (!RequiredAlignment.isZero()) {
2835 Alignment = std::max(Alignment, RequiredAlignment);
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002836 auto RoundingAlignment = Alignment;
2837 if (!MaxFieldAlignment.isZero())
2838 RoundingAlignment = std::min(RoundingAlignment, MaxFieldAlignment);
2839 RoundingAlignment = std::max(RoundingAlignment, RequiredAlignment);
Rui Ueyama83aa9792016-01-14 21:00:27 +00002840 Size = Size.alignTo(RoundingAlignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002841 }
Warren Hunt049f6732013-12-06 19:54:25 +00002842 if (Size.isZero()) {
David Majnemercd3ebfe2016-05-23 17:16:12 +00002843 if (!recordUsesEBO(RD) || !cast<CXXRecordDecl>(RD)->isEmpty()) {
2844 EndsWithZeroSizedObject = true;
2845 LeadsWithZeroSizedBase = true;
2846 }
David Majnemer00a061d2014-09-30 06:45:43 +00002847 // Zero-sized structures have size equal to their alignment if a
2848 // __declspec(align) came into play.
2849 if (RequiredAlignment >= MinEmptyStructSize)
2850 Size = Alignment;
2851 else
2852 Size = MinEmptyStructSize;
Warren Hunt049f6732013-12-06 19:54:25 +00002853 }
Reid Kleckner8b6d0342015-02-25 19:17:45 +00002854
2855 if (UseExternalLayout) {
2856 Size = Context.toCharUnitsFromBits(External.Size);
2857 if (External.Align)
2858 Alignment = Context.toCharUnitsFromBits(External.Align);
2859 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002860}
2861
Warren Hunt73f43982014-04-11 22:05:28 +00002862// Recursively walks the non-virtual bases of a class and determines if any of
2863// them are in the bases with overridden methods set.
David Majnemer12727642014-07-16 06:30:31 +00002864static bool
2865RequiresVtordisp(const llvm::SmallPtrSetImpl<const CXXRecordDecl *> &
2866 BasesWithOverriddenMethods,
2867 const CXXRecordDecl *RD) {
Warren Hunt73f43982014-04-11 22:05:28 +00002868 if (BasesWithOverriddenMethods.count(RD))
Warren Hunt8f8bad72013-10-11 20:19:00 +00002869 return true;
2870 // If any of a virtual bases non-virtual bases (recursively) requires a
2871 // vtordisp than so does this virtual base.
David Majnemerc964b4b2014-07-16 06:04:00 +00002872 for (const CXXBaseSpecifier &Base : RD->bases())
2873 if (!Base.isVirtual() &&
Warren Hunt73f43982014-04-11 22:05:28 +00002874 RequiresVtordisp(BasesWithOverriddenMethods,
David Majnemerc964b4b2014-07-16 06:04:00 +00002875 Base.getType()->getAsCXXRecordDecl()))
Warren Hunt8f8bad72013-10-11 20:19:00 +00002876 return true;
2877 return false;
2878}
2879
David Majnemerc2e67532014-09-23 22:58:15 +00002880void MicrosoftRecordLayoutBuilder::computeVtorDispSet(
2881 llvm::SmallPtrSetImpl<const CXXRecordDecl *> &HasVtordispSet,
2882 const CXXRecordDecl *RD) const {
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00002883 // /vd2 or #pragma vtordisp(2): Always use vtordisps for virtual bases with
2884 // vftables.
2885 if (RD->getMSVtorDispMode() == MSVtorDispAttr::ForVFTable) {
David Majnemerc964b4b2014-07-16 06:04:00 +00002886 for (const CXXBaseSpecifier &Base : RD->vbases()) {
2887 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00002888 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
2889 if (Layout.hasExtendableVFPtr())
2890 HasVtordispSet.insert(BaseDecl);
2891 }
David Majnemerc2e67532014-09-23 22:58:15 +00002892 return;
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00002893 }
2894
Warren Hunt8f8bad72013-10-11 20:19:00 +00002895 // If any of our bases need a vtordisp for this type, so do we. Check our
2896 // direct bases for vtordisp requirements.
David Majnemerc964b4b2014-07-16 06:04:00 +00002897 for (const CXXBaseSpecifier &Base : RD->bases()) {
2898 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002899 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
Reid Klecknercd612ab2014-04-11 16:57:42 +00002900 for (const auto &bi : Layout.getVBaseOffsetsMap())
2901 if (bi.second.hasVtorDisp())
2902 HasVtordispSet.insert(bi.first);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002903 }
David Majnemerd43388c2014-04-13 02:27:32 +00002904 // We don't introduce any additional vtordisps if either:
2905 // * A user declared constructor or destructor aren't declared.
2906 // * #pragma vtordisp(0) or the /vd0 flag are in use.
2907 if ((!RD->hasUserDeclaredConstructor() && !RD->hasUserDeclaredDestructor()) ||
2908 RD->getMSVtorDispMode() == MSVtorDispAttr::Never)
David Majnemerc2e67532014-09-23 22:58:15 +00002909 return;
David Majnemerd43388c2014-04-13 02:27:32 +00002910 // /vd1 or #pragma vtordisp(1): Try to guess based on whether we think it's
2911 // possible for a partially constructed object with virtual base overrides to
2912 // escape a non-trivial constructor.
2913 assert(RD->getMSVtorDispMode() == MSVtorDispAttr::ForVBaseOverride);
Warren Hunt73f43982014-04-11 22:05:28 +00002914 // Compute a set of base classes which define methods we override. A virtual
2915 // base in this set will require a vtordisp. A virtual base that transitively
2916 // contains one of these bases as a non-virtual base will also require a
2917 // vtordisp.
2918 llvm::SmallPtrSet<const CXXMethodDecl *, 8> Work;
2919 llvm::SmallPtrSet<const CXXRecordDecl *, 2> BasesWithOverriddenMethods;
David Majnemerc2e67532014-09-23 22:58:15 +00002920 // Seed the working set with our non-destructor, non-pure virtual methods.
David Majnemerc964b4b2014-07-16 06:04:00 +00002921 for (const CXXMethodDecl *MD : RD->methods())
David Majnemerc2e67532014-09-23 22:58:15 +00002922 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD) && !MD->isPure())
David Majnemerc964b4b2014-07-16 06:04:00 +00002923 Work.insert(MD);
Warren Hunt73f43982014-04-11 22:05:28 +00002924 while (!Work.empty()) {
2925 const CXXMethodDecl *MD = *Work.begin();
Benjamin Krameracfa3392017-12-17 23:52:45 +00002926 auto MethodRange = MD->overridden_methods();
Warren Hunt73f43982014-04-11 22:05:28 +00002927 // If a virtual method has no-overrides it lives in its parent's vtable.
Benjamin Krameracfa3392017-12-17 23:52:45 +00002928 if (MethodRange.begin() == MethodRange.end())
Warren Hunt73f43982014-04-11 22:05:28 +00002929 BasesWithOverriddenMethods.insert(MD->getParent());
2930 else
Benjamin Krameracfa3392017-12-17 23:52:45 +00002931 Work.insert(MethodRange.begin(), MethodRange.end());
Warren Hunt73f43982014-04-11 22:05:28 +00002932 // We've finished processing this element, remove it from the working set.
2933 Work.erase(MD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002934 }
Warren Hunt73f43982014-04-11 22:05:28 +00002935 // For each of our virtual bases, check if it is in the set of overridden
2936 // bases or if it transitively contains a non-virtual base that is.
David Majnemerc964b4b2014-07-16 06:04:00 +00002937 for (const CXXBaseSpecifier &Base : RD->vbases()) {
2938 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002939 if (!HasVtordispSet.count(BaseDecl) &&
Warren Hunt73f43982014-04-11 22:05:28 +00002940 RequiresVtordisp(BasesWithOverriddenMethods, BaseDecl))
Warren Huntd640d7d2014-01-09 00:30:56 +00002941 HasVtordispSet.insert(BaseDecl);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002942 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002943}
2944
Anders Carlssondf291d82010-05-26 04:56:53 +00002945/// getASTRecordLayout - Get or compute information about the layout of the
2946/// specified record (struct/union/class), which indicates its size and field
2947/// position information.
Jay Foad39c79802011-01-12 09:06:06 +00002948const ASTRecordLayout &
2949ASTContext::getASTRecordLayout(const RecordDecl *D) const {
John McCall0710e552011-10-07 02:39:22 +00002950 // These asserts test different things. A record has a definition
2951 // as soon as we begin to parse the definition. That definition is
2952 // not a complete definition (which is what isDefinition() tests)
2953 // until we *finish* parsing the definition.
Sean Callanan56c19892012-02-08 00:04:52 +00002954
2955 if (D->hasExternalLexicalStorage() && !D->getDefinition())
2956 getExternalSource()->CompleteType(const_cast<RecordDecl*>(D));
2957
Anders Carlssondf291d82010-05-26 04:56:53 +00002958 D = D->getDefinition();
2959 assert(D && "Cannot get layout of forward declarations!");
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00002960 assert(!D->isInvalidDecl() && "Cannot get layout of invalid decl!");
John McCallf937c022011-10-07 06:10:15 +00002961 assert(D->isCompleteDefinition() && "Cannot layout type before complete!");
Anders Carlssondf291d82010-05-26 04:56:53 +00002962
2963 // Look up this layout, if already laid out, return what we have.
2964 // Note that we can't save a reference to the entry because this function
2965 // is recursive.
2966 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
2967 if (Entry) return *Entry;
2968
Craig Topper36250ad2014-05-12 05:36:57 +00002969 const ASTRecordLayout *NewEntry = nullptr;
Anders Carlssond2954862010-05-26 05:10:47 +00002970
David Majnemer3b1c9902015-07-25 20:18:14 +00002971 if (isMsLayout(*this)) {
2972 MicrosoftRecordLayoutBuilder Builder(*this);
2973 if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
2974 Builder.cxxLayout(RD);
2975 NewEntry = new (*this) ASTRecordLayout(
2976 *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment,
2977 Builder.HasOwnVFPtr, Builder.HasOwnVFPtr || Builder.PrimaryBase,
David Majnemer97276c82016-05-24 18:10:50 +00002978 Builder.VBPtrOffset, Builder.DataSize, Builder.FieldOffsets,
David Majnemer3b1c9902015-07-25 20:18:14 +00002979 Builder.NonVirtualSize, Builder.Alignment, CharUnits::Zero(),
2980 Builder.PrimaryBase, false, Builder.SharedVBPtrBase,
2981 Builder.EndsWithZeroSizedObject, Builder.LeadsWithZeroSizedBase,
2982 Builder.Bases, Builder.VBases);
2983 } else {
2984 Builder.layout(D);
2985 NewEntry = new (*this) ASTRecordLayout(
2986 *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment,
David Majnemer97276c82016-05-24 18:10:50 +00002987 Builder.Size, Builder.FieldOffsets);
David Majnemer3b1c9902015-07-25 20:18:14 +00002988 }
Anders Carlssond2954862010-05-26 05:10:47 +00002989 } else {
David Majnemer3b1c9902015-07-25 20:18:14 +00002990 if (const auto *RD = dyn_cast<CXXRecordDecl>(D)) {
2991 EmptySubobjectMap EmptySubobjects(*this, RD);
2992 ItaniumRecordLayoutBuilder Builder(*this, &EmptySubobjects);
2993 Builder.Layout(RD);
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002994
David Majnemer3b1c9902015-07-25 20:18:14 +00002995 // In certain situations, we are allowed to lay out objects in the
2996 // tail-padding of base classes. This is ABI-dependent.
2997 // FIXME: this should be stored in the record layout.
2998 bool skipTailPadding =
2999 mustSkipTailPadding(getTargetInfo().getCXXABI(), RD);
3000
3001 // FIXME: This should be done in FinalizeLayout.
3002 CharUnits DataSize =
3003 skipTailPadding ? Builder.getSize() : Builder.getDataSize();
3004 CharUnits NonVirtualSize =
3005 skipTailPadding ? DataSize : Builder.NonVirtualSize;
3006 NewEntry = new (*this) ASTRecordLayout(
3007 *this, Builder.getSize(), Builder.Alignment,
3008 /*RequiredAlignment : used by MS-ABI)*/
3009 Builder.Alignment, Builder.HasOwnVFPtr, RD->isDynamicClass(),
David Majnemer97276c82016-05-24 18:10:50 +00003010 CharUnits::fromQuantity(-1), DataSize, Builder.FieldOffsets,
3011 NonVirtualSize, Builder.NonVirtualAlignment,
David Majnemer3b1c9902015-07-25 20:18:14 +00003012 EmptySubobjects.SizeOfLargestEmptySubobject, Builder.PrimaryBase,
3013 Builder.PrimaryBaseIsVirtual, nullptr, false, false, Builder.Bases,
3014 Builder.VBases);
3015 } else {
3016 ItaniumRecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/nullptr);
3017 Builder.Layout(D);
3018
3019 NewEntry = new (*this) ASTRecordLayout(
3020 *this, Builder.getSize(), Builder.Alignment,
3021 /*RequiredAlignment : used by MS-ABI)*/
David Majnemer97276c82016-05-24 18:10:50 +00003022 Builder.Alignment, Builder.getSize(), Builder.FieldOffsets);
David Majnemer3b1c9902015-07-25 20:18:14 +00003023 }
Anders Carlssond2954862010-05-26 05:10:47 +00003024 }
3025
Anders Carlssondf291d82010-05-26 04:56:53 +00003026 ASTRecordLayouts[D] = NewEntry;
3027
David Blaikiebbafb8a2012-03-11 07:00:24 +00003028 if (getLangOpts().DumpRecordLayouts) {
Argyrios Kyrtzidis8ade08e2013-07-12 22:30:03 +00003029 llvm::outs() << "\n*** Dumping AST Record Layout\n";
3030 DumpRecordLayout(D, llvm::outs(), getLangOpts().DumpRecordLayoutsSimple);
Anders Carlssondf291d82010-05-26 04:56:53 +00003031 }
3032
3033 return *NewEntry;
3034}
3035
John McCall6bd2a892013-01-25 22:31:03 +00003036const CXXMethodDecl *ASTContext::getCurrentKeyFunction(const CXXRecordDecl *RD) {
Reid Kleckner5d7f2982013-05-29 16:18:30 +00003037 if (!getTargetInfo().getCXXABI().hasKeyFunctions())
Craig Topper36250ad2014-05-12 05:36:57 +00003038 return nullptr;
Reid Kleckner5d7f2982013-05-29 16:18:30 +00003039
John McCall6bd2a892013-01-25 22:31:03 +00003040 assert(RD->getDefinition() && "Cannot get key function for forward decl!");
George Burgess IV00f70bd2018-03-01 05:43:23 +00003041 RD = RD->getDefinition();
Daniel Dunbar592a85c2010-05-27 02:25:46 +00003042
Richard Smitha9a1c682014-07-07 06:38:20 +00003043 // Beware:
3044 // 1) computing the key function might trigger deserialization, which might
3045 // invalidate iterators into KeyFunctions
3046 // 2) 'get' on the LazyDeclPtr might also trigger deserialization and
3047 // invalidate the LazyDeclPtr within the map itself
3048 LazyDeclPtr Entry = KeyFunctions[RD];
3049 const Decl *Result =
3050 Entry ? Entry.get(getExternalSource()) : computeKeyFunction(*this, RD);
Daniel Dunbar592a85c2010-05-27 02:25:46 +00003051
Richard Smitha9a1c682014-07-07 06:38:20 +00003052 // Store it back if it changed.
3053 if (Entry.isOffset() || Entry.isValid() != bool(Result))
3054 KeyFunctions[RD] = const_cast<Decl*>(Result);
3055
3056 return cast_or_null<CXXMethodDecl>(Result);
John McCall6bd2a892013-01-25 22:31:03 +00003057}
3058
Richard Smith676c4042013-08-29 23:59:27 +00003059void ASTContext::setNonKeyFunction(const CXXMethodDecl *Method) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00003060 assert(Method == Method->getFirstDecl() &&
John McCall6bd2a892013-01-25 22:31:03 +00003061 "not working with method declaration from class definition");
3062
3063 // Look up the cache entry. Since we're working with the first
3064 // declaration, its parent must be the class definition, which is
3065 // the correct key for the KeyFunctions hash.
Reid Klecknerb4a26ed2015-05-21 00:12:53 +00003066 const auto &Map = KeyFunctions;
3067 auto I = Map.find(Method->getParent());
John McCall6bd2a892013-01-25 22:31:03 +00003068
3069 // If it's not cached, there's nothing to do.
Reid Klecknerb4a26ed2015-05-21 00:12:53 +00003070 if (I == Map.end()) return;
John McCall6bd2a892013-01-25 22:31:03 +00003071
3072 // If it is cached, check whether it's the target method, and if so,
Richard Smitha9a1c682014-07-07 06:38:20 +00003073 // remove it from the cache. Note, the call to 'get' might invalidate
3074 // the iterator and the LazyDeclPtr object within the map.
3075 LazyDeclPtr Ptr = I->second;
3076 if (Ptr.get(getExternalSource()) == Method) {
John McCall6bd2a892013-01-25 22:31:03 +00003077 // FIXME: remember that we did this for module / chained PCH state?
Richard Smitha9a1c682014-07-07 06:38:20 +00003078 KeyFunctions.erase(Method->getParent());
John McCall6bd2a892013-01-25 22:31:03 +00003079 }
Anders Carlssondf291d82010-05-26 04:56:53 +00003080}
3081
Richard Smithdafff942012-01-14 04:30:29 +00003082static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) {
3083 const ASTRecordLayout &Layout = C.getASTRecordLayout(FD->getParent());
3084 return Layout.getFieldOffset(FD->getFieldIndex());
3085}
3086
3087uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const {
3088 uint64_t OffsetInBits;
3089 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
3090 OffsetInBits = ::getFieldOffset(*this, FD);
3091 } else {
3092 const IndirectFieldDecl *IFD = cast<IndirectFieldDecl>(VD);
3093
3094 OffsetInBits = 0;
David Majnemerc964b4b2014-07-16 06:04:00 +00003095 for (const NamedDecl *ND : IFD->chain())
3096 OffsetInBits += ::getFieldOffset(*this, cast<FieldDecl>(ND));
Richard Smithdafff942012-01-14 04:30:29 +00003097 }
3098
3099 return OffsetInBits;
3100}
3101
Akira Hatanaka4b1c4842017-06-27 04:34:04 +00003102uint64_t ASTContext::lookupFieldBitOffset(const ObjCInterfaceDecl *OID,
3103 const ObjCImplementationDecl *ID,
3104 const ObjCIvarDecl *Ivar) const {
3105 const ObjCInterfaceDecl *Container = Ivar->getContainingInterface();
3106
3107 // FIXME: We should eliminate the need to have ObjCImplementationDecl passed
3108 // in here; it should never be necessary because that should be the lexical
3109 // decl context for the ivar.
3110
3111 // If we know have an implementation (and the ivar is in it) then
3112 // look up in the implementation layout.
3113 const ASTRecordLayout *RL;
3114 if (ID && declaresSameEntity(ID->getClassInterface(), Container))
3115 RL = &getASTObjCImplementationLayout(ID);
3116 else
3117 RL = &getASTObjCInterfaceLayout(Container);
3118
3119 // Compute field index.
3120 //
3121 // FIXME: The index here is closely tied to how ASTContext::getObjCLayout is
3122 // implemented. This should be fixed to get the information from the layout
3123 // directly.
3124 unsigned Index = 0;
3125
3126 for (const ObjCIvarDecl *IVD = Container->all_declared_ivar_begin();
3127 IVD; IVD = IVD->getNextIvar()) {
3128 if (Ivar == IVD)
3129 break;
3130 ++Index;
3131 }
3132 assert(Index < RL->getFieldCount() && "Ivar is not inside record layout!");
3133
3134 return RL->getFieldOffset(Index);
3135}
3136
Eric Christopher8a39a012011-10-05 06:00:51 +00003137/// getObjCLayout - Get or compute information about the layout of the
3138/// given interface.
Anders Carlssondf291d82010-05-26 04:56:53 +00003139///
3140/// \param Impl - If given, also include the layout of the interface's
3141/// implementation. This may differ by including synthesized ivars.
3142const ASTRecordLayout &
3143ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
Jay Foad39c79802011-01-12 09:06:06 +00003144 const ObjCImplementationDecl *Impl) const {
Douglas Gregor64d92572011-12-20 15:50:13 +00003145 // Retrieve the definition
Sean Callanand9a909c2012-03-15 16:33:08 +00003146 if (D->hasExternalLexicalStorage() && !D->getDefinition())
3147 getExternalSource()->CompleteType(const_cast<ObjCInterfaceDecl*>(D));
Douglas Gregor64d92572011-12-20 15:50:13 +00003148 D = D->getDefinition();
3149 assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!");
Anders Carlssondf291d82010-05-26 04:56:53 +00003150
3151 // Look up this layout, if already laid out, return what we have.
Roman Divackye6377112012-09-06 15:59:27 +00003152 const ObjCContainerDecl *Key =
3153 Impl ? (const ObjCContainerDecl*) Impl : (const ObjCContainerDecl*) D;
Anders Carlssondf291d82010-05-26 04:56:53 +00003154 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
3155 return *Entry;
3156
3157 // Add in synthesized ivar count if laying out an implementation.
3158 if (Impl) {
3159 unsigned SynthCount = CountNonClassIvars(D);
David Majnemer07639702016-02-12 19:21:02 +00003160 // If there aren't any synthesized ivars then reuse the interface
Anders Carlssondf291d82010-05-26 04:56:53 +00003161 // entry. Note we can't cache this because we simply free all
3162 // entries later; however we shouldn't look up implementations
3163 // frequently.
3164 if (SynthCount == 0)
Craig Topper36250ad2014-05-12 05:36:57 +00003165 return getObjCLayout(D, nullptr);
Anders Carlssondf291d82010-05-26 04:56:53 +00003166 }
3167
David Majnemer3b1c9902015-07-25 20:18:14 +00003168 ItaniumRecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/nullptr);
Anders Carlsson6ed3a9a2010-05-26 05:04:25 +00003169 Builder.Layout(D);
3170
Anders Carlssondf291d82010-05-26 04:56:53 +00003171 const ASTRecordLayout *NewEntry =
David Majnemer97276c82016-05-24 18:10:50 +00003172 new (*this) ASTRecordLayout(*this, Builder.getSize(),
Ken Dyck4731d5b2011-02-16 02:05:21 +00003173 Builder.Alignment,
Warren Hunt7b252d22013-12-06 00:01:17 +00003174 /*RequiredAlignment : used by MS-ABI)*/
3175 Builder.Alignment,
Ken Dyck1b4420e2011-02-28 02:01:38 +00003176 Builder.getDataSize(),
David Majnemer97276c82016-05-24 18:10:50 +00003177 Builder.FieldOffsets);
Daniel Dunbar592a85c2010-05-27 02:25:46 +00003178
Anders Carlssondf291d82010-05-26 04:56:53 +00003179 ObjCLayouts[Key] = NewEntry;
3180
3181 return *NewEntry;
3182}
3183
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003184static void PrintOffset(raw_ostream &OS,
Anders Carlsson3f018712010-10-31 23:45:59 +00003185 CharUnits Offset, unsigned IndentLevel) {
John McCall0d461692015-08-19 22:42:36 +00003186 OS << llvm::format("%10" PRId64 " | ", (int64_t)Offset.getQuantity());
3187 OS.indent(IndentLevel * 2);
3188}
3189
3190static void PrintBitFieldOffset(raw_ostream &OS, CharUnits Offset,
3191 unsigned Begin, unsigned Width,
3192 unsigned IndentLevel) {
3193 llvm::SmallString<10> Buffer;
3194 {
3195 llvm::raw_svector_ostream BufferOS(Buffer);
3196 BufferOS << Offset.getQuantity() << ':';
3197 if (Width == 0) {
3198 BufferOS << '-';
3199 } else {
3200 BufferOS << Begin << '-' << (Begin + Width - 1);
3201 }
3202 }
3203
3204 OS << llvm::right_justify(Buffer, 10) << " | ";
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003205 OS.indent(IndentLevel * 2);
3206}
3207
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00003208static void PrintIndentNoOffset(raw_ostream &OS, unsigned IndentLevel) {
John McCall0d461692015-08-19 22:42:36 +00003209 OS << " | ";
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00003210 OS.indent(IndentLevel * 2);
3211}
3212
John McCall0d461692015-08-19 22:42:36 +00003213static void DumpRecordLayout(raw_ostream &OS, const RecordDecl *RD,
3214 const ASTContext &C,
3215 CharUnits Offset,
3216 unsigned IndentLevel,
3217 const char* Description,
3218 bool PrintSizeInfo,
3219 bool IncludeVirtualBases) {
Anders Carlsson3f018712010-10-31 23:45:59 +00003220 const ASTRecordLayout &Layout = C.getASTRecordLayout(RD);
John McCall0d461692015-08-19 22:42:36 +00003221 auto CXXRD = dyn_cast<CXXRecordDecl>(RD);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003222
3223 PrintOffset(OS, Offset, IndentLevel);
John McCall0d461692015-08-19 22:42:36 +00003224 OS << C.getTypeDeclType(const_cast<RecordDecl*>(RD)).getAsString();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003225 if (Description)
3226 OS << ' ' << Description;
John McCall0d461692015-08-19 22:42:36 +00003227 if (CXXRD && CXXRD->isEmpty())
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003228 OS << " (empty)";
3229 OS << '\n';
3230
3231 IndentLevel++;
3232
John McCall0d461692015-08-19 22:42:36 +00003233 // Dump bases.
3234 if (CXXRD) {
3235 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
3236 bool HasOwnVFPtr = Layout.hasOwnVFPtr();
3237 bool HasOwnVBPtr = Layout.hasOwnVBPtr();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003238
John McCall0d461692015-08-19 22:42:36 +00003239 // Vtable pointer.
3240 if (CXXRD->isDynamicClass() && !PrimaryBase && !isMsLayout(C)) {
3241 PrintOffset(OS, Offset, IndentLevel);
3242 OS << '(' << *RD << " vtable pointer)\n";
3243 } else if (HasOwnVFPtr) {
3244 PrintOffset(OS, Offset, IndentLevel);
3245 // vfptr (for Microsoft C++ ABI)
3246 OS << '(' << *RD << " vftable pointer)\n";
3247 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00003248
John McCall0d461692015-08-19 22:42:36 +00003249 // Collect nvbases.
3250 SmallVector<const CXXRecordDecl *, 4> Bases;
3251 for (const CXXBaseSpecifier &Base : CXXRD->bases()) {
3252 assert(!Base.getType()->isDependentType() &&
3253 "Cannot layout class with dependent bases.");
3254 if (!Base.isVirtual())
3255 Bases.push_back(Base.getType()->getAsCXXRecordDecl());
3256 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003257
John McCall0d461692015-08-19 22:42:36 +00003258 // Sort nvbases by offset.
3259 std::stable_sort(Bases.begin(), Bases.end(),
3260 [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
3261 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
3262 });
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003263
John McCall0d461692015-08-19 22:42:36 +00003264 // Dump (non-virtual) bases
3265 for (const CXXRecordDecl *Base : Bases) {
3266 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
3267 DumpRecordLayout(OS, Base, C, BaseOffset, IndentLevel,
3268 Base == PrimaryBase ? "(primary base)" : "(base)",
3269 /*PrintSizeInfo=*/false,
3270 /*IncludeVirtualBases=*/false);
3271 }
Eli Friedman43114f92011-10-21 22:49:56 +00003272
John McCall0d461692015-08-19 22:42:36 +00003273 // vbptr (for Microsoft C++ ABI)
3274 if (HasOwnVBPtr) {
3275 PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel);
3276 OS << '(' << *RD << " vbtable pointer)\n";
3277 }
Eli Friedman84d2d3a2011-09-27 19:12:27 +00003278 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003279
3280 // Dump fields.
3281 uint64_t FieldNo = 0;
John McCall0d461692015-08-19 22:42:36 +00003282 for (RecordDecl::field_iterator I = RD->field_begin(),
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003283 E = RD->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +00003284 const FieldDecl &Field = **I;
John McCall0d461692015-08-19 22:42:36 +00003285 uint64_t LocalFieldOffsetInBits = Layout.getFieldOffset(FieldNo);
3286 CharUnits FieldOffset =
3287 Offset + C.toCharUnitsFromBits(LocalFieldOffsetInBits);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003288
John McCall0d461692015-08-19 22:42:36 +00003289 // Recursively dump fields of record type.
3290 if (auto RT = Field.getType()->getAs<RecordType>()) {
3291 DumpRecordLayout(OS, RT->getDecl(), C, FieldOffset, IndentLevel,
3292 Field.getName().data(),
3293 /*PrintSizeInfo=*/false,
3294 /*IncludeVirtualBases=*/true);
Reid Klecknercd612ab2014-04-11 16:57:42 +00003295 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003296 }
3297
John McCall0d461692015-08-19 22:42:36 +00003298 if (Field.isBitField()) {
3299 uint64_t LocalFieldByteOffsetInBits = C.toBits(FieldOffset - Offset);
3300 unsigned Begin = LocalFieldOffsetInBits - LocalFieldByteOffsetInBits;
3301 unsigned Width = Field.getBitWidthValue(C);
3302 PrintBitFieldOffset(OS, FieldOffset, Begin, Width, IndentLevel);
3303 } else {
3304 PrintOffset(OS, FieldOffset, IndentLevel);
3305 }
David Blaikie2d7c57e2012-04-30 02:36:29 +00003306 OS << Field.getType().getAsString() << ' ' << Field << '\n';
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003307 }
3308
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003309 // Dump virtual bases.
John McCall0d461692015-08-19 22:42:36 +00003310 if (CXXRD && IncludeVirtualBases) {
3311 const ASTRecordLayout::VBaseOffsetsMapTy &VtorDisps =
3312 Layout.getVBaseOffsetsMap();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003313
John McCall0d461692015-08-19 22:42:36 +00003314 for (const CXXBaseSpecifier &Base : CXXRD->vbases()) {
3315 assert(Base.isVirtual() && "Found non-virtual class!");
3316 const CXXRecordDecl *VBase = Base.getType()->getAsCXXRecordDecl();
John McCalle42a3362012-05-01 08:55:32 +00003317
John McCall0d461692015-08-19 22:42:36 +00003318 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
3319
3320 if (VtorDisps.find(VBase)->second.hasVtorDisp()) {
3321 PrintOffset(OS, VBaseOffset - CharUnits::fromQuantity(4), IndentLevel);
3322 OS << "(vtordisp for vbase " << *VBase << ")\n";
3323 }
3324
3325 DumpRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel,
3326 VBase == Layout.getPrimaryBase() ?
3327 "(primary virtual base)" : "(virtual base)",
3328 /*PrintSizeInfo=*/false,
3329 /*IncludeVirtualBases=*/false);
John McCalle42a3362012-05-01 08:55:32 +00003330 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003331 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003332
John McCall0d461692015-08-19 22:42:36 +00003333 if (!PrintSizeInfo) return;
3334
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00003335 PrintIndentNoOffset(OS, IndentLevel - 1);
3336 OS << "[sizeof=" << Layout.getSize().getQuantity();
John McCall0d461692015-08-19 22:42:36 +00003337 if (CXXRD && !isMsLayout(C))
Warren Hunt8f8bad72013-10-11 20:19:00 +00003338 OS << ", dsize=" << Layout.getDataSize().getQuantity();
John McCall0d461692015-08-19 22:42:36 +00003339 OS << ", align=" << Layout.getAlignment().getQuantity();
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00003340
John McCall0d461692015-08-19 22:42:36 +00003341 if (CXXRD) {
3342 OS << ",\n";
3343 PrintIndentNoOffset(OS, IndentLevel - 1);
3344 OS << " nvsize=" << Layout.getNonVirtualSize().getQuantity();
3345 OS << ", nvalign=" << Layout.getNonVirtualAlignment().getQuantity();
3346 }
3347 OS << "]\n";
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003348}
Daniel Dunbarccabe482010-04-19 20:44:53 +00003349
3350void ASTContext::DumpRecordLayout(const RecordDecl *RD,
Douglas Gregore9fc3772012-01-26 07:55:45 +00003351 raw_ostream &OS,
3352 bool Simple) const {
Douglas Gregore9fc3772012-01-26 07:55:45 +00003353 if (!Simple) {
John McCall0d461692015-08-19 22:42:36 +00003354 ::DumpRecordLayout(OS, RD, *this, CharUnits(), 0, nullptr,
3355 /*PrintSizeInfo*/true,
3356 /*IncludeVirtualBases=*/true);
3357 return;
Douglas Gregore9fc3772012-01-26 07:55:45 +00003358 }
John McCall0d461692015-08-19 22:42:36 +00003359
3360 // The "simple" format is designed to be parsed by the
3361 // layout-override testing code. There shouldn't be any external
3362 // uses of this format --- when LLDB overrides a layout, it sets up
3363 // the data structures directly --- so feel free to adjust this as
3364 // you like as long as you also update the rudimentary parser for it
3365 // in libFrontend.
3366
3367 const ASTRecordLayout &Info = getASTRecordLayout(RD);
3368 OS << "Type: " << getTypeDeclType(RD).getAsString() << "\n";
Daniel Dunbarccabe482010-04-19 20:44:53 +00003369 OS << "\nLayout: ";
3370 OS << "<ASTRecordLayout\n";
Ken Dyckb0fcc592011-02-11 01:54:29 +00003371 OS << " Size:" << toBits(Info.getSize()) << "\n";
David Majnemer3b1c9902015-07-25 20:18:14 +00003372 if (!isMsLayout(*this))
Warren Hunt8f8bad72013-10-11 20:19:00 +00003373 OS << " DataSize:" << toBits(Info.getDataSize()) << "\n";
Ken Dyck7ad11e72011-02-15 02:32:40 +00003374 OS << " Alignment:" << toBits(Info.getAlignment()) << "\n";
Daniel Dunbarccabe482010-04-19 20:44:53 +00003375 OS << " FieldOffsets: [";
3376 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) {
3377 if (i) OS << ", ";
3378 OS << Info.getFieldOffset(i);
3379 }
3380 OS << "]>\n";
3381}