blob: f4733cc6b767803c7fd4d1f5e40f3abfd9c1c9c7 [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"
Ted Kremenekf75d0892011-03-19 01:00:36 +000021#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "llvm/Support/Format.h"
23#include "llvm/Support/MathExtras.h"
Anders Carlsson79474332009-07-18 20:20:21 +000024
25using namespace clang;
26
Benjamin Kramerc7656cd2010-05-26 09:58:31 +000027namespace {
Anders Carlssonf58de112010-05-26 15:32:58 +000028
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000029/// BaseSubobjectInfo - Represents a single base subobject in a complete class.
30/// For a class hierarchy like
31///
32/// class A { };
33/// class B : A { };
34/// class C : A, B { };
35///
36/// The BaseSubobjectInfo graph for C will have three BaseSubobjectInfo
37/// instances, one for B and two for A.
38///
39/// If a base is virtual, it will only have one BaseSubobjectInfo allocated.
40struct BaseSubobjectInfo {
41 /// Class - The class for this base info.
Anders Carlsson056818f2010-05-28 21:13:31 +000042 const CXXRecordDecl *Class;
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000043
44 /// IsVirtual - Whether the BaseInfo represents a virtual base or not.
Anders Carlsson056818f2010-05-28 21:13:31 +000045 bool IsVirtual;
46
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000047 /// Bases - Information about the base subobjects.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000048 SmallVector<BaseSubobjectInfo*, 4> Bases;
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000049
Anders Carlssone3c24c72010-05-29 17:35:14 +000050 /// PrimaryVirtualBaseInfo - Holds the base info for the primary virtual base
51 /// of this base info (if one exists).
52 BaseSubobjectInfo *PrimaryVirtualBaseInfo;
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000053
54 // FIXME: Document.
55 const BaseSubobjectInfo *Derived;
Anders Carlsson056818f2010-05-28 21:13:31 +000056};
57
Anders Carlssonf58de112010-05-26 15:32:58 +000058/// EmptySubobjectMap - Keeps track of which empty subobjects exist at different
59/// offsets while laying out a C++ class.
60class EmptySubobjectMap {
Jay Foad39c79802011-01-12 09:06:06 +000061 const ASTContext &Context;
Anders Carlsson233e2722010-10-31 21:54:55 +000062 uint64_t CharWidth;
63
Anders Carlssonf58de112010-05-26 15:32:58 +000064 /// Class - The class whose empty entries we're keeping track of.
65 const CXXRecordDecl *Class;
Daniel Dunbar592a85c2010-05-27 02:25:46 +000066
Anders Carlsson439edd12010-05-27 05:41:06 +000067 /// EmptyClassOffsets - A map from offsets to empty record decls.
Benjamin Kramer834652a2014-05-03 18:44:26 +000068 typedef llvm::TinyPtrVector<const CXXRecordDecl *> ClassVectorTy;
Anders Carlssonf8f756d2010-10-31 21:22:43 +000069 typedef llvm::DenseMap<CharUnits, ClassVectorTy> EmptyClassOffsetsMapTy;
Anders Carlsson439edd12010-05-27 05:41:06 +000070 EmptyClassOffsetsMapTy EmptyClassOffsets;
71
Anders Carlssoncc5de092010-06-08 15:56:03 +000072 /// MaxEmptyClassOffset - The highest offset known to contain an empty
73 /// base subobject.
Anders Carlsson725190f2010-10-31 21:39:24 +000074 CharUnits MaxEmptyClassOffset;
Anders Carlssoncc5de092010-06-08 15:56:03 +000075
Daniel Dunbar592a85c2010-05-27 02:25:46 +000076 /// ComputeEmptySubobjectSizes - Compute the size of the largest base or
Anders Carlssonc5ca1f72010-05-26 15:54:25 +000077 /// member subobject that is empty.
78 void ComputeEmptySubobjectSizes();
Anders Carlsson439edd12010-05-27 05:41:06 +000079
Anders Carlsson725190f2010-10-31 21:39:24 +000080 void AddSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset);
Anders Carlssondb319762010-05-27 18:20:57 +000081
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000082 void UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +000083 CharUnits Offset, bool PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +000084
Anders Carlssondb319762010-05-27 18:20:57 +000085 void UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
86 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +000087 CharUnits Offset);
88 void UpdateEmptyFieldSubobjects(const FieldDecl *FD, CharUnits Offset);
Anders Carlssondb319762010-05-27 18:20:57 +000089
Anders Carlssoncc5de092010-06-08 15:56:03 +000090 /// AnyEmptySubobjectsBeyondOffset - Returns whether there are any empty
91 /// subobjects beyond the given offset.
Anders Carlsson725190f2010-10-31 21:39:24 +000092 bool AnyEmptySubobjectsBeyondOffset(CharUnits Offset) const {
Anders Carlssoncc5de092010-06-08 15:56:03 +000093 return Offset <= MaxEmptyClassOffset;
94 }
95
Anders Carlsson233e2722010-10-31 21:54:55 +000096 CharUnits
97 getFieldOffset(const ASTRecordLayout &Layout, unsigned FieldNo) const {
98 uint64_t FieldOffset = Layout.getFieldOffset(FieldNo);
99 assert(FieldOffset % CharWidth == 0 &&
100 "Field offset not at char boundary!");
101
Ken Dyck7c4026b2011-01-24 01:28:50 +0000102 return Context.toCharUnitsFromBits(FieldOffset);
Anders Carlssonf8f756d2010-10-31 21:22:43 +0000103 }
Anders Carlssonf8f756d2010-10-31 21:22:43 +0000104
Charles Davisc2c576a2010-08-19 00:55:19 +0000105protected:
Anders Carlsson725190f2010-10-31 21:39:24 +0000106 bool CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
107 CharUnits Offset) const;
Charles Davisc2c576a2010-08-19 00:55:19 +0000108
109 bool CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000110 CharUnits Offset);
Charles Davisc2c576a2010-08-19 00:55:19 +0000111
112 bool CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
113 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000114 CharUnits Offset) const;
Charles Davisc2c576a2010-08-19 00:55:19 +0000115 bool CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
Anders Carlsson233e2722010-10-31 21:54:55 +0000116 CharUnits Offset) const;
Charles Davisc2c576a2010-08-19 00:55:19 +0000117
Anders Carlssonf58de112010-05-26 15:32:58 +0000118public:
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000119 /// This holds the size of the largest empty subobject (either a base
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000120 /// or a member). Will be zero if the record being built doesn't contain
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000121 /// any empty classes.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000122 CharUnits SizeOfLargestEmptySubobject;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000123
Jay Foad39c79802011-01-12 09:06:06 +0000124 EmptySubobjectMap(const ASTContext &Context, const CXXRecordDecl *Class)
Anders Carlsson28466ab2010-10-31 22:13:23 +0000125 : Context(Context), CharWidth(Context.getCharWidth()), Class(Class) {
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000126 ComputeEmptySubobjectSizes();
127 }
128
129 /// CanPlaceBaseAtOffset - Return whether the given base class can be placed
130 /// at the given offset.
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000131 /// Returns false if placing the record will result in two components
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000132 /// (direct or indirect) of the same type having the same offset.
Anders Carlssoncc5de092010-06-08 15:56:03 +0000133 bool CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000134 CharUnits Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000135
136 /// CanPlaceFieldAtOffset - Return whether a field can be placed at the given
137 /// offset.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000138 bool CanPlaceFieldAtOffset(const FieldDecl *FD, CharUnits Offset);
Anders Carlssonf58de112010-05-26 15:32:58 +0000139};
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000140
141void EmptySubobjectMap::ComputeEmptySubobjectSizes() {
142 // Check the bases.
David Majnemerc964b4b2014-07-16 06:04:00 +0000143 for (const CXXBaseSpecifier &Base : Class->bases()) {
144 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000145
Anders Carlsson28466ab2010-10-31 22:13:23 +0000146 CharUnits EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000147 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
148 if (BaseDecl->isEmpty()) {
149 // If the class decl is empty, get its size.
Ken Dyckc8ae5502011-02-09 01:59:34 +0000150 EmptySize = Layout.getSize();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000151 } else {
152 // Otherwise, we get the largest empty subobject for the decl.
153 EmptySize = Layout.getSizeOfLargestEmptySubobject();
154 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000155
Anders Carlsson28466ab2010-10-31 22:13:23 +0000156 if (EmptySize > SizeOfLargestEmptySubobject)
157 SizeOfLargestEmptySubobject = EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000158 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000159
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000160 // Check the fields.
David Majnemerc964b4b2014-07-16 06:04:00 +0000161 for (const FieldDecl *FD : Class->fields()) {
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000162 const RecordType *RT =
David Majnemerc964b4b2014-07-16 06:04:00 +0000163 Context.getBaseElementType(FD->getType())->getAs<RecordType>();
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000164
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000165 // We only care about record types.
166 if (!RT)
167 continue;
168
Anders Carlsson28466ab2010-10-31 22:13:23 +0000169 CharUnits EmptySize;
Reid Klecknercd612ab2014-04-11 16:57:42 +0000170 const CXXRecordDecl *MemberDecl = RT->getAsCXXRecordDecl();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000171 const ASTRecordLayout &Layout = Context.getASTRecordLayout(MemberDecl);
172 if (MemberDecl->isEmpty()) {
173 // If the class decl is empty, get its size.
Ken Dyckc8ae5502011-02-09 01:59:34 +0000174 EmptySize = Layout.getSize();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000175 } else {
176 // Otherwise, we get the largest empty subobject for the decl.
177 EmptySize = Layout.getSizeOfLargestEmptySubobject();
178 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000179
Anders Carlsson28466ab2010-10-31 22:13:23 +0000180 if (EmptySize > SizeOfLargestEmptySubobject)
181 SizeOfLargestEmptySubobject = EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000182 }
183}
184
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000185bool
Anders Carlssondb319762010-05-27 18:20:57 +0000186EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
Anders Carlsson725190f2010-10-31 21:39:24 +0000187 CharUnits Offset) const {
Anders Carlssondb319762010-05-27 18:20:57 +0000188 // We only need to check empty bases.
189 if (!RD->isEmpty())
190 return true;
191
Anders Carlsson725190f2010-10-31 21:39:24 +0000192 EmptyClassOffsetsMapTy::const_iterator I = EmptyClassOffsets.find(Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000193 if (I == EmptyClassOffsets.end())
194 return true;
David Majnemerc964b4b2014-07-16 06:04:00 +0000195
196 const ClassVectorTy &Classes = I->second;
Anders Carlssondb319762010-05-27 18:20:57 +0000197 if (std::find(Classes.begin(), Classes.end(), RD) == Classes.end())
198 return true;
199
200 // There is already an empty class of the same type at this offset.
201 return false;
202}
203
204void EmptySubobjectMap::AddSubobjectAtOffset(const CXXRecordDecl *RD,
Anders Carlsson725190f2010-10-31 21:39:24 +0000205 CharUnits Offset) {
Anders Carlssondb319762010-05-27 18:20:57 +0000206 // We only care about empty bases.
207 if (!RD->isEmpty())
208 return;
209
Reid Kleckner369f3162013-05-14 20:30:42 +0000210 // If we have empty structures inside a union, we can assign both
Rafael Espindola7bcde192010-12-29 23:02:58 +0000211 // the same offset. Just avoid pushing them twice in the list.
David Majnemerc964b4b2014-07-16 06:04:00 +0000212 ClassVectorTy &Classes = EmptyClassOffsets[Offset];
Rafael Espindola7bcde192010-12-29 23:02:58 +0000213 if (std::find(Classes.begin(), Classes.end(), RD) != Classes.end())
214 return;
215
Anders Carlssondb319762010-05-27 18:20:57 +0000216 Classes.push_back(RD);
Anders Carlssoncc5de092010-06-08 15:56:03 +0000217
218 // Update the empty class offset.
Anders Carlsson725190f2010-10-31 21:39:24 +0000219 if (Offset > MaxEmptyClassOffset)
220 MaxEmptyClassOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000221}
222
223bool
Anders Carlsson28466ab2010-10-31 22:13:23 +0000224EmptySubobjectMap::CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
225 CharUnits Offset) {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000226 // We don't have to keep looking past the maximum offset that's known to
227 // contain an empty class.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000228 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000229 return true;
230
Anders Carlsson28466ab2010-10-31 22:13:23 +0000231 if (!CanPlaceSubobjectAtOffset(Info->Class, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000232 return false;
233
Anders Carlsson439edd12010-05-27 05:41:06 +0000234 // Traverse all non-virtual bases.
Anders Carlssona7774a62010-05-29 21:10:24 +0000235 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
David Majnemerc964b4b2014-07-16 06:04:00 +0000236 for (const BaseSubobjectInfo *Base : Info->Bases) {
Anders Carlsson439edd12010-05-27 05:41:06 +0000237 if (Base->IsVirtual)
238 continue;
239
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000240 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlsson439edd12010-05-27 05:41:06 +0000241
242 if (!CanPlaceBaseSubobjectAtOffset(Base, BaseOffset))
243 return false;
244 }
245
Anders Carlssone3c24c72010-05-29 17:35:14 +0000246 if (Info->PrimaryVirtualBaseInfo) {
247 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
Anders Carlsson439edd12010-05-27 05:41:06 +0000248
249 if (Info == PrimaryVirtualBaseInfo->Derived) {
250 if (!CanPlaceBaseSubobjectAtOffset(PrimaryVirtualBaseInfo, Offset))
251 return false;
252 }
253 }
254
Anders Carlssondb319762010-05-27 18:20:57 +0000255 // Traverse all member variables.
256 unsigned FieldNo = 0;
257 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
258 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000259 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000260 continue;
David Majnemerc964b4b2014-07-16 06:04:00 +0000261
Anders Carlsson28466ab2010-10-31 22:13:23 +0000262 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
David Blaikie40ed2972012-06-06 20:45:41 +0000263 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000264 return false;
265 }
David Majnemerc964b4b2014-07-16 06:04:00 +0000266
Anders Carlsson439edd12010-05-27 05:41:06 +0000267 return true;
268}
269
Anders Carlssona7f3cdb2010-05-28 21:24:37 +0000270void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000271 CharUnits Offset,
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000272 bool PlacingEmptyBase) {
273 if (!PlacingEmptyBase && Offset >= SizeOfLargestEmptySubobject) {
274 // We know that the only empty subobjects that can conflict with empty
275 // subobject of non-empty bases, are empty bases that can be placed at
276 // offset zero. Because of this, we only need to keep track of empty base
277 // subobjects with offsets less than the size of the largest empty
278 // subobject for our class.
279 return;
280 }
281
Anders Carlsson28466ab2010-10-31 22:13:23 +0000282 AddSubobjectAtOffset(Info->Class, Offset);
Anders Carlssona7774a62010-05-29 21:10:24 +0000283
Anders Carlsson439edd12010-05-27 05:41:06 +0000284 // Traverse all non-virtual bases.
Anders Carlssona7774a62010-05-29 21:10:24 +0000285 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
David Majnemerc964b4b2014-07-16 06:04:00 +0000286 for (const BaseSubobjectInfo *Base : Info->Bases) {
Anders Carlsson439edd12010-05-27 05:41:06 +0000287 if (Base->IsVirtual)
288 continue;
Anders Carlssona7774a62010-05-29 21:10:24 +0000289
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000290 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000291 UpdateEmptyBaseSubobjects(Base, BaseOffset, PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +0000292 }
293
Anders Carlssone3c24c72010-05-29 17:35:14 +0000294 if (Info->PrimaryVirtualBaseInfo) {
295 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
Anders Carlsson439edd12010-05-27 05:41:06 +0000296
297 if (Info == PrimaryVirtualBaseInfo->Derived)
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000298 UpdateEmptyBaseSubobjects(PrimaryVirtualBaseInfo, Offset,
299 PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +0000300 }
Anders Carlssondb319762010-05-27 18:20:57 +0000301
Anders Carlssondb319762010-05-27 18:20:57 +0000302 // Traverse all member variables.
303 unsigned FieldNo = 0;
304 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
305 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000306 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000307 continue;
Anders Carlssona7774a62010-05-29 21:10:24 +0000308
Anders Carlsson28466ab2010-10-31 22:13:23 +0000309 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
David Blaikie40ed2972012-06-06 20:45:41 +0000310 UpdateEmptyFieldSubobjects(*I, FieldOffset);
Anders Carlssondb319762010-05-27 18:20:57 +0000311 }
Anders Carlsson439edd12010-05-27 05:41:06 +0000312}
313
Anders Carlssona60b86a2010-05-29 20:49:49 +0000314bool EmptySubobjectMap::CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000315 CharUnits Offset) {
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000316 // If we know this class doesn't have any empty subobjects we don't need to
317 // bother checking.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000318 if (SizeOfLargestEmptySubobject.isZero())
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000319 return true;
320
Anders Carlsson439edd12010-05-27 05:41:06 +0000321 if (!CanPlaceBaseSubobjectAtOffset(Info, Offset))
322 return false;
Anders Carlssondb319762010-05-27 18:20:57 +0000323
324 // We are able to place the base at this offset. Make sure to update the
325 // empty base subobject map.
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000326 UpdateEmptyBaseSubobjects(Info, Offset, Info->Class->isEmpty());
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000327 return true;
328}
329
Anders Carlssondb319762010-05-27 18:20:57 +0000330bool
331EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
332 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000333 CharUnits Offset) const {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000334 // We don't have to keep looking past the maximum offset that's known to
335 // contain an empty class.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000336 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000337 return true;
338
Anders Carlsson28466ab2010-10-31 22:13:23 +0000339 if (!CanPlaceSubobjectAtOffset(RD, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000340 return false;
341
342 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
343
344 // Traverse all non-virtual bases.
David Majnemerc964b4b2014-07-16 06:04:00 +0000345 for (const CXXBaseSpecifier &Base : RD->bases()) {
346 if (Base.isVirtual())
Anders Carlssondb319762010-05-27 18:20:57 +0000347 continue;
348
David Majnemerc964b4b2014-07-16 06:04:00 +0000349 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Anders Carlssondb319762010-05-27 18:20:57 +0000350
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000351 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
Anders Carlssondb319762010-05-27 18:20:57 +0000352 if (!CanPlaceFieldSubobjectAtOffset(BaseDecl, Class, BaseOffset))
353 return false;
354 }
355
Anders Carlsson44687202010-06-08 19:09:24 +0000356 if (RD == Class) {
357 // This is the most derived class, traverse virtual bases as well.
David Majnemerc964b4b2014-07-16 06:04:00 +0000358 for (const CXXBaseSpecifier &Base : RD->vbases()) {
359 const CXXRecordDecl *VBaseDecl = Base.getType()->getAsCXXRecordDecl();
Reid Klecknercd612ab2014-04-11 16:57:42 +0000360
Anders Carlsson3f018712010-10-31 23:45:59 +0000361 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
Anders Carlsson44687202010-06-08 19:09:24 +0000362 if (!CanPlaceFieldSubobjectAtOffset(VBaseDecl, Class, VBaseOffset))
363 return false;
364 }
365 }
366
Anders Carlssondb319762010-05-27 18:20:57 +0000367 // Traverse all member variables.
368 unsigned FieldNo = 0;
369 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
370 I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000371 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000372 continue;
373
Anders Carlsson28466ab2010-10-31 22:13:23 +0000374 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
Anders Carlssondb319762010-05-27 18:20:57 +0000375
David Blaikie40ed2972012-06-06 20:45:41 +0000376 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000377 return false;
378 }
379
380 return true;
381}
382
Anders Carlsson233e2722010-10-31 21:54:55 +0000383bool
384EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
385 CharUnits Offset) const {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000386 // We don't have to keep looking past the maximum offset that's known to
387 // contain an empty class.
Anders Carlsson233e2722010-10-31 21:54:55 +0000388 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000389 return true;
390
Anders Carlssondb319762010-05-27 18:20:57 +0000391 QualType T = FD->getType();
Reid Klecknercd612ab2014-04-11 16:57:42 +0000392 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Anders Carlsson28466ab2010-10-31 22:13:23 +0000393 return CanPlaceFieldSubobjectAtOffset(RD, RD, Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000394
395 // If we have an array type we need to look at every element.
396 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
397 QualType ElemTy = Context.getBaseElementType(AT);
398 const RecordType *RT = ElemTy->getAs<RecordType>();
399 if (!RT)
400 return true;
Reid Klecknercd612ab2014-04-11 16:57:42 +0000401
402 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
Anders Carlssondb319762010-05-27 18:20:57 +0000403 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
404
405 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
Anders Carlsson233e2722010-10-31 21:54:55 +0000406 CharUnits ElementOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000407 for (uint64_t I = 0; I != NumElements; ++I) {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000408 // We don't have to keep looking past the maximum offset that's known to
409 // contain an empty class.
Anders Carlsson233e2722010-10-31 21:54:55 +0000410 if (!AnyEmptySubobjectsBeyondOffset(ElementOffset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000411 return true;
412
Anders Carlsson28466ab2010-10-31 22:13:23 +0000413 if (!CanPlaceFieldSubobjectAtOffset(RD, RD, ElementOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000414 return false;
415
Ken Dyckc8ae5502011-02-09 01:59:34 +0000416 ElementOffset += Layout.getSize();
Anders Carlssondb319762010-05-27 18:20:57 +0000417 }
418 }
419
420 return true;
421}
422
423bool
Anders Carlsson28466ab2010-10-31 22:13:23 +0000424EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl *FD,
425 CharUnits Offset) {
426 if (!CanPlaceFieldSubobjectAtOffset(FD, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000427 return false;
428
429 // We are able to place the member variable at this offset.
430 // Make sure to update the empty base subobject map.
431 UpdateEmptyFieldSubobjects(FD, Offset);
432 return true;
433}
434
435void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
436 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000437 CharUnits Offset) {
Anders Carlssonae111dc2010-06-13 17:49:16 +0000438 // We know that the only empty subobjects that can conflict with empty
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000439 // field subobjects are subobjects of empty bases that can be placed at offset
Anders Carlssonae111dc2010-06-13 17:49:16 +0000440 // zero. Because of this, we only need to keep track of empty field
441 // subobjects with offsets less than the size of the largest empty
442 // subobject for our class.
443 if (Offset >= SizeOfLargestEmptySubobject)
444 return;
445
Anders Carlsson28466ab2010-10-31 22:13:23 +0000446 AddSubobjectAtOffset(RD, Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000447
448 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
449
450 // Traverse all non-virtual bases.
David Majnemerc964b4b2014-07-16 06:04:00 +0000451 for (const CXXBaseSpecifier &Base : RD->bases()) {
452 if (Base.isVirtual())
Anders Carlssondb319762010-05-27 18:20:57 +0000453 continue;
454
David Majnemerc964b4b2014-07-16 06:04:00 +0000455 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Anders Carlssondb319762010-05-27 18:20:57 +0000456
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000457 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
Anders Carlssondb319762010-05-27 18:20:57 +0000458 UpdateEmptyFieldSubobjects(BaseDecl, Class, BaseOffset);
459 }
460
Anders Carlsson44687202010-06-08 19:09:24 +0000461 if (RD == Class) {
462 // This is the most derived class, traverse virtual bases as well.
David Majnemerc964b4b2014-07-16 06:04:00 +0000463 for (const CXXBaseSpecifier &Base : RD->vbases()) {
464 const CXXRecordDecl *VBaseDecl = Base.getType()->getAsCXXRecordDecl();
Reid Klecknercd612ab2014-04-11 16:57:42 +0000465
Anders Carlsson3f018712010-10-31 23:45:59 +0000466 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
Anders Carlsson44687202010-06-08 19:09:24 +0000467 UpdateEmptyFieldSubobjects(VBaseDecl, Class, VBaseOffset);
468 }
469 }
470
Anders Carlssondb319762010-05-27 18:20:57 +0000471 // Traverse all member variables.
472 unsigned FieldNo = 0;
473 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
474 I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000475 if (I->isBitField())
Anders Carlsson09814d32010-11-01 15:14:51 +0000476 continue;
477
Anders Carlsson28466ab2010-10-31 22:13:23 +0000478 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
Anders Carlssondb319762010-05-27 18:20:57 +0000479
David Blaikie40ed2972012-06-06 20:45:41 +0000480 UpdateEmptyFieldSubobjects(*I, FieldOffset);
Anders Carlssondb319762010-05-27 18:20:57 +0000481 }
482}
483
484void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const FieldDecl *FD,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000485 CharUnits Offset) {
Anders Carlssondb319762010-05-27 18:20:57 +0000486 QualType T = FD->getType();
Reid Klecknercd612ab2014-04-11 16:57:42 +0000487 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
Anders Carlssondb319762010-05-27 18:20:57 +0000488 UpdateEmptyFieldSubobjects(RD, RD, Offset);
489 return;
490 }
491
492 // If we have an array type we need to update every element.
493 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
494 QualType ElemTy = Context.getBaseElementType(AT);
495 const RecordType *RT = ElemTy->getAs<RecordType>();
496 if (!RT)
497 return;
Reid Klecknercd612ab2014-04-11 16:57:42 +0000498
499 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
Anders Carlssondb319762010-05-27 18:20:57 +0000500 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
501
502 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
Anders Carlsson28466ab2010-10-31 22:13:23 +0000503 CharUnits ElementOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000504
505 for (uint64_t I = 0; I != NumElements; ++I) {
Anders Carlssonae111dc2010-06-13 17:49:16 +0000506 // We know that the only empty subobjects that can conflict with empty
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000507 // field subobjects are subobjects of empty bases that can be placed at
Anders Carlssonae111dc2010-06-13 17:49:16 +0000508 // offset zero. Because of this, we only need to keep track of empty field
509 // subobjects with offsets less than the size of the largest empty
510 // subobject for our class.
511 if (ElementOffset >= SizeOfLargestEmptySubobject)
512 return;
513
Anders Carlssondb319762010-05-27 18:20:57 +0000514 UpdateEmptyFieldSubobjects(RD, RD, ElementOffset);
Ken Dyckc8ae5502011-02-09 01:59:34 +0000515 ElementOffset += Layout.getSize();
Anders Carlssondb319762010-05-27 18:20:57 +0000516 }
517 }
518}
519
John McCalle42a3362012-05-01 08:55:32 +0000520typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> ClassSetTy;
521
Anders Carlssonc2226202010-05-26 05:58:59 +0000522class RecordLayoutBuilder {
Charles Davisc2c576a2010-08-19 00:55:19 +0000523protected:
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000524 // FIXME: Remove this and make the appropriate fields public.
525 friend class clang::ASTContext;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000526
Jay Foad39c79802011-01-12 09:06:06 +0000527 const ASTContext &Context;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000528
Anders Carlssonf58de112010-05-26 15:32:58 +0000529 EmptySubobjectMap *EmptySubobjects;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000530
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000531 /// Size - The current size of the record layout.
532 uint64_t Size;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000533
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000534 /// Alignment - The current alignment of the record layout.
Ken Dyck4731d5b2011-02-16 02:05:21 +0000535 CharUnits Alignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000536
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000537 /// \brief The alignment if attribute packed is not used.
Ken Dyck1300b3b2011-02-16 02:11:31 +0000538 CharUnits UnpackedAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000539
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000540 SmallVector<uint64_t, 16> FieldOffsets;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000541
Douglas Gregore9fc3772012-01-26 07:55:45 +0000542 /// \brief Whether the external AST source has provided a layout for this
543 /// record.
544 unsigned ExternalLayout : 1;
Douglas Gregor44ba7892012-01-28 00:53:29 +0000545
546 /// \brief Whether we need to infer alignment, even when we have an
547 /// externally-provided layout.
548 unsigned InferAlignment : 1;
Douglas Gregore9fc3772012-01-26 07:55:45 +0000549
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000550 /// Packed - Whether the record is packed or not.
Daniel Dunbar6da10982010-05-27 05:45:51 +0000551 unsigned Packed : 1;
552
553 unsigned IsUnion : 1;
554
555 unsigned IsMac68kAlign : 1;
Fariborz Jahanianbcb23a12011-04-26 23:52:16 +0000556
557 unsigned IsMsStruct : 1;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000558
Eli Friedman2782dac2013-06-26 20:50:34 +0000559 /// UnfilledBitsInLastUnit - If the last field laid out was a bitfield,
560 /// this contains the number of bits in the last unit that can be used for
561 /// an adjacent bitfield if necessary. The unit in question is usually
562 /// a byte, but larger units are used if IsMsStruct.
563 unsigned char UnfilledBitsInLastUnit;
564 /// LastBitfieldTypeSize - If IsMsStruct, represents the size of the type
565 /// of the previous field if it was a bitfield.
566 unsigned char LastBitfieldTypeSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000567
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000568 /// MaxFieldAlignment - The maximum allowed field alignment. This is set by
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000569 /// #pragma pack.
Ken Dyck02ced6f2011-02-17 01:49:42 +0000570 CharUnits MaxFieldAlignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000571
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000572 /// DataSize - The data size of the record being laid out.
573 uint64_t DataSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000574
Ken Dyckaf1c83f2011-02-16 01:52:01 +0000575 CharUnits NonVirtualSize;
Ken Dycka2d3dda2011-02-16 01:43:15 +0000576 CharUnits NonVirtualAlignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000577
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000578 /// PrimaryBase - the primary base class (if one exists) of the class
579 /// we're laying out.
580 const CXXRecordDecl *PrimaryBase;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000581
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000582 /// PrimaryBaseIsVirtual - Whether the primary base of the class we're laying
583 /// out is virtual.
584 bool PrimaryBaseIsVirtual;
585
John McCalle42a3362012-05-01 08:55:32 +0000586 /// HasOwnVFPtr - Whether the class provides its own vtable/vftbl
587 /// pointer, as opposed to inheriting one from a primary base class.
588 bool HasOwnVFPtr;
Eli Friedman43114f92011-10-21 22:49:56 +0000589
Anders Carlsson22f57202010-10-31 21:01:46 +0000590 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000591
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000592 /// Bases - base classes and their offsets in the record.
593 BaseOffsetsMapTy Bases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000594
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000595 // VBases - virtual base classes and their offsets in the record.
John McCalle42a3362012-05-01 08:55:32 +0000596 ASTRecordLayout::VBaseOffsetsMapTy VBases;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000597
598 /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are
599 /// primary base classes for some other direct or indirect base class.
Anders Carlsson5adde292010-11-24 22:55:48 +0000600 CXXIndirectPrimaryBaseSet IndirectPrimaryBases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000601
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000602 /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in
603 /// inheritance graph order. Used for determining the primary base class.
604 const CXXRecordDecl *FirstNearlyEmptyVBase;
605
606 /// VisitedVirtualBases - A set of all the visited virtual bases, used to
607 /// avoid visiting virtual bases more than once.
608 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000609
Douglas Gregore9fc3772012-01-26 07:55:45 +0000610 /// \brief Externally-provided size.
611 uint64_t ExternalSize;
612
613 /// \brief Externally-provided alignment.
614 uint64_t ExternalAlign;
615
616 /// \brief Externally-provided field offsets.
617 llvm::DenseMap<const FieldDecl *, uint64_t> ExternalFieldOffsets;
618
619 /// \brief Externally-provided direct, non-virtual base offsets.
620 llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalBaseOffsets;
621
622 /// \brief Externally-provided virtual base offsets.
623 llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalVirtualBaseOffsets;
624
John McCall0153cd32011-11-08 04:01:03 +0000625 RecordLayoutBuilder(const ASTContext &Context,
626 EmptySubobjectMap *EmptySubobjects)
Ken Dyck4731d5b2011-02-16 02:05:21 +0000627 : Context(Context), EmptySubobjects(EmptySubobjects), Size(0),
John McCall0153cd32011-11-08 04:01:03 +0000628 Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()),
Douglas Gregor44ba7892012-01-28 00:53:29 +0000629 ExternalLayout(false), InferAlignment(false),
630 Packed(false), IsUnion(false), IsMac68kAlign(false), IsMsStruct(false),
Eli Friedman2782dac2013-06-26 20:50:34 +0000631 UnfilledBitsInLastUnit(0), LastBitfieldTypeSize(0),
632 MaxFieldAlignment(CharUnits::Zero()),
Ken Dyck02ced6f2011-02-17 01:49:42 +0000633 DataSize(0), NonVirtualSize(CharUnits::Zero()),
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000634 NonVirtualAlignment(CharUnits::One()),
Craig Topper36250ad2014-05-12 05:36:57 +0000635 PrimaryBase(nullptr), PrimaryBaseIsVirtual(false),
John McCalle42a3362012-05-01 08:55:32 +0000636 HasOwnVFPtr(false),
Craig Topper36250ad2014-05-12 05:36:57 +0000637 FirstNearlyEmptyVBase(nullptr) {}
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000638
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000639 void Layout(const RecordDecl *D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000640 void Layout(const CXXRecordDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000641 void Layout(const ObjCInterfaceDecl *D);
642
643 void LayoutFields(const RecordDecl *D);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000644 void LayoutField(const FieldDecl *D, bool InsertExtraPadding);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000645 void LayoutWideBitField(uint64_t FieldSize, uint64_t TypeSize,
646 bool FieldPacked, const FieldDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000647 void LayoutBitField(const FieldDecl *D);
John McCall0153cd32011-11-08 04:01:03 +0000648
John McCall359b8852013-01-25 22:30:49 +0000649 TargetCXXABI getCXXABI() const {
650 return Context.getTargetInfo().getCXXABI();
651 }
652
Anders Carlssone3c24c72010-05-29 17:35:14 +0000653 /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects.
654 llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator;
655
656 typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *>
657 BaseSubobjectInfoMapTy;
658
659 /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases
660 /// of the class we're laying out to their base subobject info.
661 BaseSubobjectInfoMapTy VirtualBaseInfo;
662
663 /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the
664 /// class we're laying out to their base subobject info.
665 BaseSubobjectInfoMapTy NonVirtualBaseInfo;
666
667 /// ComputeBaseSubobjectInfo - Compute the base subobject information for the
668 /// bases of the given class.
669 void ComputeBaseSubobjectInfo(const CXXRecordDecl *RD);
670
671 /// ComputeBaseSubobjectInfo - Compute the base subobject information for a
672 /// single class and all of its base classes.
673 BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
674 bool IsVirtual,
675 BaseSubobjectInfo *Derived);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000676
677 /// DeterminePrimaryBase - Determine the primary base of the given class.
678 void DeterminePrimaryBase(const CXXRecordDecl *RD);
679
680 void SelectPrimaryVBase(const CXXRecordDecl *RD);
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000681
Eli Friedman43114f92011-10-21 22:49:56 +0000682 void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign);
Charles Davisc2c576a2010-08-19 00:55:19 +0000683
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000684 /// LayoutNonVirtualBases - Determines the primary base class (if any) and
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000685 /// lays it out. Will then proceed to lay out all non-virtual base clasess.
686 void LayoutNonVirtualBases(const CXXRecordDecl *RD);
687
688 /// LayoutNonVirtualBase - Lays out a single non-virtual base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +0000689 void LayoutNonVirtualBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000690
Anders Carlssona2f8e412010-10-31 22:20:42 +0000691 void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
692 CharUnits Offset);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000693
694 /// LayoutVirtualBases - Lays out all the virtual bases.
695 void LayoutVirtualBases(const CXXRecordDecl *RD,
696 const CXXRecordDecl *MostDerivedClass);
697
698 /// LayoutVirtualBase - Lays out a single virtual base.
Warren Hunt55d8e822013-10-23 23:53:07 +0000699 void LayoutVirtualBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000700
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000701 /// LayoutBase - Will lay out a base and return the offset where it was
Anders Carlssona2f8e412010-10-31 22:20:42 +0000702 /// placed, in chars.
703 CharUnits LayoutBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000704
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000705 /// InitializeLayout - Initialize record layout for the given record decl.
Daniel Dunbar6da10982010-05-27 05:45:51 +0000706 void InitializeLayout(const Decl *D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000707
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000708 /// FinishLayout - Finalize record layout. Adjust record size based on the
709 /// alignment.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000710 void FinishLayout(const NamedDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000711
Ken Dyck85ef0432011-02-19 18:58:07 +0000712 void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment);
713 void UpdateAlignment(CharUnits NewAlignment) {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000714 UpdateAlignment(NewAlignment, NewAlignment);
715 }
716
Douglas Gregor44ba7892012-01-28 00:53:29 +0000717 /// \brief Retrieve the externally-supplied field offset for the given
718 /// field.
719 ///
720 /// \param Field The field whose offset is being queried.
721 /// \param ComputedOffset The offset that we've computed for this field.
722 uint64_t updateExternalFieldOffset(const FieldDecl *Field,
723 uint64_t ComputedOffset);
724
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000725 void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset,
726 uint64_t UnpackedOffset, unsigned UnpackedAlign,
727 bool isPacked, const FieldDecl *D);
728
729 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000730
Ken Dyckecfc7552011-02-24 01:13:28 +0000731 CharUnits getSize() const {
Ken Dyck3c215f22011-02-24 01:33:05 +0000732 assert(Size % Context.getCharWidth() == 0);
Ken Dyckecfc7552011-02-24 01:13:28 +0000733 return Context.toCharUnitsFromBits(Size);
734 }
735 uint64_t getSizeInBits() const { return Size; }
736
737 void setSize(CharUnits NewSize) { Size = Context.toBits(NewSize); }
738 void setSize(uint64_t NewSize) { Size = NewSize; }
739
Eli Friedman84d2d3a2011-09-27 19:12:27 +0000740 CharUnits getAligment() const { return Alignment; }
741
Ken Dyckecfc7552011-02-24 01:13:28 +0000742 CharUnits getDataSize() const {
Ken Dyck3c215f22011-02-24 01:33:05 +0000743 assert(DataSize % Context.getCharWidth() == 0);
Ken Dyckecfc7552011-02-24 01:13:28 +0000744 return Context.toCharUnitsFromBits(DataSize);
745 }
746 uint64_t getDataSizeInBits() const { return DataSize; }
747
748 void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); }
749 void setDataSize(uint64_t NewSize) { DataSize = NewSize; }
750
Aaron Ballmanabc18922015-02-15 22:54:08 +0000751 RecordLayoutBuilder(const RecordLayoutBuilder &) = delete;
752 void operator=(const RecordLayoutBuilder &) = delete;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000753};
Benjamin Kramerc7656cd2010-05-26 09:58:31 +0000754} // end anonymous namespace
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000755
Anders Carlsson81430692009-09-22 03:02:06 +0000756void
Anders Carlssonc2226202010-05-26 05:58:59 +0000757RecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000758 for (const auto &I : RD->bases()) {
759 assert(!I.getType()->isDependentType() &&
Sebastian Redl1054fae2009-10-25 17:03:50 +0000760 "Cannot layout class with dependent bases.");
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000761
Reid Klecknercd612ab2014-04-11 16:57:42 +0000762 const CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000763
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000764 // Check if this is a nearly empty virtual base.
Aaron Ballman574705e2014-03-13 15:41:46 +0000765 if (I.isVirtual() && Context.isNearlyEmpty(Base)) {
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000766 // If it's not an indirect primary base, then we've found our primary
767 // base.
Anders Carlsson81430692009-09-22 03:02:06 +0000768 if (!IndirectPrimaryBases.count(Base)) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000769 PrimaryBase = Base;
770 PrimaryBaseIsVirtual = true;
Mike Stump6f3793b2009-08-12 21:50:08 +0000771 return;
772 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000773
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000774 // Is this the first nearly empty virtual base?
775 if (!FirstNearlyEmptyVBase)
776 FirstNearlyEmptyVBase = Base;
Mike Stump6f3793b2009-08-12 21:50:08 +0000777 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000778
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000779 SelectPrimaryVBase(Base);
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000780 if (PrimaryBase)
Zhongxing Xuec345b72010-02-15 04:28:35 +0000781 return;
Mike Stump6f3793b2009-08-12 21:50:08 +0000782 }
783}
784
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000785/// DeterminePrimaryBase - Determine the primary base of the given class.
Anders Carlssonc2226202010-05-26 05:58:59 +0000786void RecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) {
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000787 // If the class isn't dynamic, it won't have a primary base.
788 if (!RD->isDynamicClass())
789 return;
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000790
Anders Carlsson81430692009-09-22 03:02:06 +0000791 // Compute all the primary virtual bases for all of our direct and
Mike Stump590a7c72009-08-13 23:26:06 +0000792 // indirect bases, and record all their primary virtual base classes.
Anders Carlsson5adde292010-11-24 22:55:48 +0000793 RD->getIndirectPrimaryBases(IndirectPrimaryBases);
Mike Stump590a7c72009-08-13 23:26:06 +0000794
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000795 // If the record has a dynamic base class, attempt to choose a primary base
796 // class. It is the first (in direct base class order) non-virtual dynamic
Anders Carlsson81430692009-09-22 03:02:06 +0000797 // base class, if one exists.
Aaron Ballman574705e2014-03-13 15:41:46 +0000798 for (const auto &I : RD->bases()) {
Anders Carlsson03ff3792009-11-27 22:05:05 +0000799 // Ignore virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000800 if (I.isVirtual())
Anders Carlsson03ff3792009-11-27 22:05:05 +0000801 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000802
Reid Klecknercd612ab2014-04-11 16:57:42 +0000803 const CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Anders Carlsson03ff3792009-11-27 22:05:05 +0000804
Warren Hunt55d8e822013-10-23 23:53:07 +0000805 if (Base->isDynamicClass()) {
Anders Carlsson03ff3792009-11-27 22:05:05 +0000806 // We found it.
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000807 PrimaryBase = Base;
808 PrimaryBaseIsVirtual = false;
Anders Carlsson03ff3792009-11-27 22:05:05 +0000809 return;
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000810 }
811 }
812
Eli Friedman5e9534b2011-10-18 00:55:28 +0000813 // Under the Itanium ABI, if there is no non-virtual primary base class,
814 // try to compute the primary virtual base. The primary virtual base is
815 // the first nearly empty virtual base that is not an indirect primary
816 // virtual base class, if one exists.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000817 if (RD->getNumVBases() != 0) {
818 SelectPrimaryVBase(RD);
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000819 if (PrimaryBase)
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000820 return;
821 }
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000822
Eli Friedman5e9534b2011-10-18 00:55:28 +0000823 // Otherwise, it is the first indirect primary base class, if one exists.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000824 if (FirstNearlyEmptyVBase) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000825 PrimaryBase = FirstNearlyEmptyVBase;
826 PrimaryBaseIsVirtual = true;
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000827 return;
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000828 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000829
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000830 assert(!PrimaryBase && "Should not get here with a primary base!");
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000831}
832
Anders Carlssone3c24c72010-05-29 17:35:14 +0000833BaseSubobjectInfo *
834RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
835 bool IsVirtual,
836 BaseSubobjectInfo *Derived) {
837 BaseSubobjectInfo *Info;
838
839 if (IsVirtual) {
840 // Check if we already have info about this virtual base.
841 BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD];
842 if (InfoSlot) {
843 assert(InfoSlot->Class == RD && "Wrong class for virtual base info!");
844 return InfoSlot;
845 }
846
847 // We don't, create it.
848 InfoSlot = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
849 Info = InfoSlot;
850 } else {
851 Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
852 }
853
854 Info->Class = RD;
855 Info->IsVirtual = IsVirtual;
Craig Topper36250ad2014-05-12 05:36:57 +0000856 Info->Derived = nullptr;
857 Info->PrimaryVirtualBaseInfo = nullptr;
858
859 const CXXRecordDecl *PrimaryVirtualBase = nullptr;
860 BaseSubobjectInfo *PrimaryVirtualBaseInfo = nullptr;
Anders Carlssone3c24c72010-05-29 17:35:14 +0000861
862 // Check if this base has a primary virtual base.
863 if (RD->getNumVBases()) {
864 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlsson7f95cd12010-11-24 23:12:57 +0000865 if (Layout.isPrimaryBaseVirtual()) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000866 // This base does have a primary virtual base.
867 PrimaryVirtualBase = Layout.getPrimaryBase();
868 assert(PrimaryVirtualBase && "Didn't have a primary virtual base!");
869
870 // Now check if we have base subobject info about this primary base.
871 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
872
873 if (PrimaryVirtualBaseInfo) {
874 if (PrimaryVirtualBaseInfo->Derived) {
875 // We did have info about this primary base, and it turns out that it
876 // has already been claimed as a primary virtual base for another
Craig Topper36250ad2014-05-12 05:36:57 +0000877 // base.
878 PrimaryVirtualBase = nullptr;
Anders Carlssone3c24c72010-05-29 17:35:14 +0000879 } else {
880 // We can claim this base as our primary base.
881 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
882 PrimaryVirtualBaseInfo->Derived = Info;
883 }
884 }
885 }
886 }
887
888 // Now go through all direct bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000889 for (const auto &I : RD->bases()) {
890 bool IsVirtual = I.isVirtual();
Reid Klecknercd612ab2014-04-11 16:57:42 +0000891
892 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
893
Anders Carlssone3c24c72010-05-29 17:35:14 +0000894 Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info));
895 }
896
897 if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) {
898 // Traversing the bases must have created the base info for our primary
899 // virtual base.
900 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
901 assert(PrimaryVirtualBaseInfo &&
902 "Did not create a primary virtual base!");
903
904 // Claim the primary virtual base as our primary virtual base.
905 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
906 PrimaryVirtualBaseInfo->Derived = Info;
907 }
908
909 return Info;
910}
911
912void RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000913 for (const auto &I : RD->bases()) {
914 bool IsVirtual = I.isVirtual();
Anders Carlssone3c24c72010-05-29 17:35:14 +0000915
Reid Klecknercd612ab2014-04-11 16:57:42 +0000916 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
917
Anders Carlssone3c24c72010-05-29 17:35:14 +0000918 // Compute the base subobject info for this base.
Craig Topper36250ad2014-05-12 05:36:57 +0000919 BaseSubobjectInfo *Info = ComputeBaseSubobjectInfo(BaseDecl, IsVirtual,
920 nullptr);
Anders Carlssone3c24c72010-05-29 17:35:14 +0000921
922 if (IsVirtual) {
923 // ComputeBaseInfo has already added this base for us.
924 assert(VirtualBaseInfo.count(BaseDecl) &&
925 "Did not add virtual base!");
926 } else {
927 // Add the base info to the map of non-virtual bases.
928 assert(!NonVirtualBaseInfo.count(BaseDecl) &&
929 "Non-virtual base already exists!");
930 NonVirtualBaseInfo.insert(std::make_pair(BaseDecl, Info));
931 }
932 }
933}
934
Anders Carlsson09ffa322010-03-10 22:21:28 +0000935void
Eli Friedman43114f92011-10-21 22:49:56 +0000936RecordLayoutBuilder::EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign) {
Eli Friedman5e9534b2011-10-18 00:55:28 +0000937 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
938
939 // The maximum field alignment overrides base align.
940 if (!MaxFieldAlignment.isZero()) {
941 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
942 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
943 }
944
945 // Round up the current record size to pointer alignment.
Eli Friedman43114f92011-10-21 22:49:56 +0000946 setSize(getSize().RoundUpToAlignment(BaseAlign));
947 setDataSize(getSize());
Eli Friedman5e9534b2011-10-18 00:55:28 +0000948
949 // Update the alignment.
950 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
951}
952
953void
Anders Carlssonc2226202010-05-26 05:58:59 +0000954RecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl *RD) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000955 // Then, determine the primary base class.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000956 DeterminePrimaryBase(RD);
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000957
Anders Carlssone3c24c72010-05-29 17:35:14 +0000958 // Compute base subobject info.
959 ComputeBaseSubobjectInfo(RD);
960
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000961 // If we have a primary base class, lay it out.
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000962 if (PrimaryBase) {
963 if (PrimaryBaseIsVirtual) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000964 // If the primary virtual base was a primary virtual base of some other
965 // base class we'll have to steal it.
966 BaseSubobjectInfo *PrimaryBaseInfo = VirtualBaseInfo.lookup(PrimaryBase);
Craig Topper36250ad2014-05-12 05:36:57 +0000967 PrimaryBaseInfo->Derived = nullptr;
968
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000969 // We have a virtual primary base, insert it as an indirect primary base.
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000970 IndirectPrimaryBases.insert(PrimaryBase);
Anders Carlssonfe900962010-03-11 05:42:17 +0000971
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000972 assert(!VisitedVirtualBases.count(PrimaryBase) &&
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000973 "vbase already visited!");
974 VisitedVirtualBases.insert(PrimaryBase);
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000975
Anders Carlssond6ff5d72010-05-29 17:48:36 +0000976 LayoutVirtualBase(PrimaryBaseInfo);
Anders Carlssonbb0e6782010-05-29 17:42:25 +0000977 } else {
978 BaseSubobjectInfo *PrimaryBaseInfo =
979 NonVirtualBaseInfo.lookup(PrimaryBase);
980 assert(PrimaryBaseInfo &&
981 "Did not find base info for non-virtual primary base!");
982
983 LayoutNonVirtualBase(PrimaryBaseInfo);
984 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000985
John McCall0153cd32011-11-08 04:01:03 +0000986 // If this class needs a vtable/vf-table and didn't get one from a
987 // primary base, add it in now.
Warren Hunt55d8e822013-10-23 23:53:07 +0000988 } else if (RD->isDynamicClass()) {
Eli Friedman5e9534b2011-10-18 00:55:28 +0000989 assert(DataSize == 0 && "Vtable pointer must be at offset zero!");
Eli Friedman5e9534b2011-10-18 00:55:28 +0000990 CharUnits PtrWidth =
991 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Eli Friedman43114f92011-10-21 22:49:56 +0000992 CharUnits PtrAlign =
993 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
994 EnsureVTablePointerAlignment(PtrAlign);
John McCalle42a3362012-05-01 08:55:32 +0000995 HasOwnVFPtr = true;
Eli Friedman5e9534b2011-10-18 00:55:28 +0000996 setSize(getSize() + PtrWidth);
997 setDataSize(getSize());
998 }
999
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001000 // Now lay out the non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001001 for (const auto &I : RD->bases()) {
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001002
Benjamin Kramer273670a2013-10-25 07:40:50 +00001003 // Ignore virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001004 if (I.isVirtual())
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001005 continue;
1006
Aaron Ballman574705e2014-03-13 15:41:46 +00001007 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001008
John McCall0153cd32011-11-08 04:01:03 +00001009 // Skip the primary base, because we've already laid it out. The
1010 // !PrimaryBaseIsVirtual check is required because we might have a
1011 // non-virtual base of the same type as a primary virtual base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001012 if (BaseDecl == PrimaryBase && !PrimaryBaseIsVirtual)
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001013 continue;
1014
1015 // Lay out the base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001016 BaseSubobjectInfo *BaseInfo = NonVirtualBaseInfo.lookup(BaseDecl);
1017 assert(BaseInfo && "Did not find base info for non-virtual base!");
1018
1019 LayoutNonVirtualBase(BaseInfo);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001020 }
1021}
1022
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001023void RecordLayoutBuilder::LayoutNonVirtualBase(const BaseSubobjectInfo *Base) {
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001024 // Layout the base.
Anders Carlssona2f8e412010-10-31 22:20:42 +00001025 CharUnits Offset = LayoutBase(Base);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001026
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001027 // Add its base class offset.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001028 assert(!Bases.count(Base->Class) && "base offset already exists!");
Anders Carlssona2f8e412010-10-31 22:20:42 +00001029 Bases.insert(std::make_pair(Base->Class, Offset));
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001030
1031 AddPrimaryVirtualBaseOffsets(Base, Offset);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001032}
Mike Stump2b84dd32009-11-05 04:02:15 +00001033
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001034void
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001035RecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
Anders Carlssona2f8e412010-10-31 22:20:42 +00001036 CharUnits Offset) {
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001037 // This base isn't interesting, it has no virtual bases.
1038 if (!Info->Class->getNumVBases())
1039 return;
1040
1041 // First, check if we have a virtual primary base to add offsets for.
1042 if (Info->PrimaryVirtualBaseInfo) {
1043 assert(Info->PrimaryVirtualBaseInfo->IsVirtual &&
1044 "Primary virtual base is not virtual!");
1045 if (Info->PrimaryVirtualBaseInfo->Derived == Info) {
1046 // Add the offset.
1047 assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) &&
1048 "primary vbase offset already exists!");
1049 VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class,
John McCalle42a3362012-05-01 08:55:32 +00001050 ASTRecordLayout::VBaseInfo(Offset, false)));
Anders Carlssonea7b1822010-04-15 16:12:58 +00001051
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001052 // Traverse the primary virtual base.
1053 AddPrimaryVirtualBaseOffsets(Info->PrimaryVirtualBaseInfo, Offset);
1054 }
Anders Carlssonea7b1822010-04-15 16:12:58 +00001055 }
1056
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001057 // Now go through all direct non-virtual bases.
1058 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
David Majnemerc964b4b2014-07-16 06:04:00 +00001059 for (const BaseSubobjectInfo *Base : Info->Bases) {
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001060 if (Base->IsVirtual)
Anders Carlssonea7b1822010-04-15 16:12:58 +00001061 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001062
Anders Carlsson0a14ee92010-11-01 00:21:58 +00001063 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001064 AddPrimaryVirtualBaseOffsets(Base, BaseOffset);
Anders Carlssonea7b1822010-04-15 16:12:58 +00001065 }
1066}
1067
1068void
Anders Carlssonc2226202010-05-26 05:58:59 +00001069RecordLayoutBuilder::LayoutVirtualBases(const CXXRecordDecl *RD,
Anders Carlssonea7b1822010-04-15 16:12:58 +00001070 const CXXRecordDecl *MostDerivedClass) {
Anders Carlssonde710c92010-03-11 04:33:54 +00001071 const CXXRecordDecl *PrimaryBase;
Anders Carlsson291279e2010-04-10 18:42:27 +00001072 bool PrimaryBaseIsVirtual;
Anders Carlssonfe900962010-03-11 05:42:17 +00001073
Anders Carlsson291279e2010-04-10 18:42:27 +00001074 if (MostDerivedClass == RD) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +00001075 PrimaryBase = this->PrimaryBase;
1076 PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual;
Anders Carlsson291279e2010-04-10 18:42:27 +00001077 } else {
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001078 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlssonde710c92010-03-11 04:33:54 +00001079 PrimaryBase = Layout.getPrimaryBase();
Anders Carlsson7f95cd12010-11-24 23:12:57 +00001080 PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
Anders Carlsson291279e2010-04-10 18:42:27 +00001081 }
1082
David Majnemerc964b4b2014-07-16 06:04:00 +00001083 for (const CXXBaseSpecifier &Base : RD->bases()) {
1084 assert(!Base.getType()->isDependentType() &&
Sebastian Redl1054fae2009-10-25 17:03:50 +00001085 "Cannot layout class with dependent bases.");
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001086
David Majnemerc964b4b2014-07-16 06:04:00 +00001087 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001088
David Majnemerc964b4b2014-07-16 06:04:00 +00001089 if (Base.isVirtual()) {
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001090 if (PrimaryBase != BaseDecl || !PrimaryBaseIsVirtual) {
1091 bool IndirectPrimaryBase = IndirectPrimaryBases.count(BaseDecl);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001092
Anders Carlsson291279e2010-04-10 18:42:27 +00001093 // Only lay out the virtual base if it's not an indirect primary base.
1094 if (!IndirectPrimaryBase) {
1095 // Only visit virtual bases once.
David Blaikie82e95a32014-11-19 07:49:47 +00001096 if (!VisitedVirtualBases.insert(BaseDecl).second)
Anders Carlsson291279e2010-04-10 18:42:27 +00001097 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001098
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001099 const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1100 assert(BaseInfo && "Did not find virtual base info!");
1101 LayoutVirtualBase(BaseInfo);
Anders Carlsson6a848892010-03-11 04:10:39 +00001102 }
Mike Stump2b84dd32009-11-05 04:02:15 +00001103 }
Mike Stumpc2f591b2009-08-13 22:53:07 +00001104 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001105
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001106 if (!BaseDecl->getNumVBases()) {
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001107 // This base isn't interesting since it doesn't have any virtual bases.
1108 continue;
Mike Stump996576f32009-08-16 19:04:13 +00001109 }
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001110
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001111 LayoutVirtualBases(BaseDecl, MostDerivedClass);
Mike Stump6b2556f2009-08-06 13:41:24 +00001112 }
1113}
1114
Warren Hunt55d8e822013-10-23 23:53:07 +00001115void RecordLayoutBuilder::LayoutVirtualBase(const BaseSubobjectInfo *Base) {
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001116 assert(!Base->Derived && "Trying to lay out a primary virtual base!");
1117
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001118 // Layout the base.
Anders Carlssona2f8e412010-10-31 22:20:42 +00001119 CharUnits Offset = LayoutBase(Base);
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001120
1121 // Add its base class offset.
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001122 assert(!VBases.count(Base->Class) && "vbase offset already exists!");
John McCalle42a3362012-05-01 08:55:32 +00001123 VBases.insert(std::make_pair(Base->Class,
Warren Hunt55d8e822013-10-23 23:53:07 +00001124 ASTRecordLayout::VBaseInfo(Offset, false)));
John McCalle42a3362012-05-01 08:55:32 +00001125
Warren Hunt55d8e822013-10-23 23:53:07 +00001126 AddPrimaryVirtualBaseOffsets(Base, Offset);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001127}
1128
Anders Carlssona2f8e412010-10-31 22:20:42 +00001129CharUnits RecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) {
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001130 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001131
Douglas Gregore9fc3772012-01-26 07:55:45 +00001132
1133 CharUnits Offset;
1134
1135 // Query the external layout to see if it provides an offset.
1136 bool HasExternalLayout = false;
1137 if (ExternalLayout) {
1138 llvm::DenseMap<const CXXRecordDecl *, CharUnits>::iterator Known;
1139 if (Base->IsVirtual) {
1140 Known = ExternalVirtualBaseOffsets.find(Base->Class);
1141 if (Known != ExternalVirtualBaseOffsets.end()) {
1142 Offset = Known->second;
1143 HasExternalLayout = true;
1144 }
1145 } else {
1146 Known = ExternalBaseOffsets.find(Base->Class);
1147 if (Known != ExternalBaseOffsets.end()) {
1148 Offset = Known->second;
1149 HasExternalLayout = true;
1150 }
1151 }
1152 }
1153
Warren Huntd640d7d2014-01-09 00:30:56 +00001154 CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlignment();
Eli Friedman69d27d22013-07-16 00:21:28 +00001155 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
1156
Anders Carlsson09ffa322010-03-10 22:21:28 +00001157 // If we have an empty base class, try to place it at offset 0.
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001158 if (Base->Class->isEmpty() &&
Douglas Gregore9fc3772012-01-26 07:55:45 +00001159 (!HasExternalLayout || Offset == CharUnits::Zero()) &&
Anders Carlsson28466ab2010-10-31 22:13:23 +00001160 EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) {
Ken Dyck1b4420e2011-02-28 02:01:38 +00001161 setSize(std::max(getSize(), Layout.getSize()));
Eli Friedman69d27d22013-07-16 00:21:28 +00001162 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001163
Anders Carlssona2f8e412010-10-31 22:20:42 +00001164 return CharUnits::Zero();
Anders Carlsson09ffa322010-03-10 22:21:28 +00001165 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001166
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001167 // The maximum field alignment overrides base align.
Ken Dyck02ced6f2011-02-17 01:49:42 +00001168 if (!MaxFieldAlignment.isZero()) {
Ken Dyck85ef0432011-02-19 18:58:07 +00001169 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1170 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001171 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001172
Douglas Gregore9fc3772012-01-26 07:55:45 +00001173 if (!HasExternalLayout) {
1174 // Round up the current record size to the base's alignment boundary.
1175 Offset = getDataSize().RoundUpToAlignment(BaseAlign);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001176
Douglas Gregore9fc3772012-01-26 07:55:45 +00001177 // Try to place the base.
1178 while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset))
1179 Offset += BaseAlign;
1180 } else {
1181 bool Allowed = EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset);
1182 (void)Allowed;
1183 assert(Allowed && "Base subobject externally placed at overlapping offset");
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001184
1185 if (InferAlignment && Offset < getDataSize().RoundUpToAlignment(BaseAlign)){
1186 // The externally-supplied base offset is before the base offset we
1187 // computed. Assume that the structure is packed.
1188 Alignment = CharUnits::One();
1189 InferAlignment = false;
1190 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001191 }
1192
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001193 if (!Base->Class->isEmpty()) {
Anders Carlsson09ffa322010-03-10 22:21:28 +00001194 // Update the data size.
Ken Dyck1b4420e2011-02-28 02:01:38 +00001195 setDataSize(Offset + Layout.getNonVirtualSize());
Anders Carlsson09ffa322010-03-10 22:21:28 +00001196
Ken Dyck1b4420e2011-02-28 02:01:38 +00001197 setSize(std::max(getSize(), getDataSize()));
Anders Carlsson09ffa322010-03-10 22:21:28 +00001198 } else
Ken Dyck1b4420e2011-02-28 02:01:38 +00001199 setSize(std::max(getSize(), Offset + Layout.getSize()));
Anders Carlsson09ffa322010-03-10 22:21:28 +00001200
1201 // Remember max struct/class alignment.
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001202 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001203
Ken Dyck1b4420e2011-02-28 02:01:38 +00001204 return Offset;
Anders Carlsson09ffa322010-03-10 22:21:28 +00001205}
1206
Daniel Dunbar6da10982010-05-27 05:45:51 +00001207void RecordLayoutBuilder::InitializeLayout(const Decl *D) {
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001208 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Daniel Dunbar6da10982010-05-27 05:45:51 +00001209 IsUnion = RD->isUnion();
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001210 IsMsStruct = RD->isMsStruct(Context);
1211 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001212
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001213 Packed = D->hasAttr<PackedAttr>();
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001214
Daniel Dunbar096ed292011-10-05 21:04:55 +00001215 // Honor the default struct packing maximum alignment flag.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001216 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) {
Daniel Dunbar096ed292011-10-05 21:04:55 +00001217 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
1218 }
1219
Daniel Dunbar6da10982010-05-27 05:45:51 +00001220 // mac68k alignment supersedes maximum field alignment and attribute aligned,
1221 // and forces all structures to have 2-byte alignment. The IBM docs on it
1222 // allude to additional (more complicated) semantics, especially with regard
1223 // to bit-fields, but gcc appears not to follow that.
1224 if (D->hasAttr<AlignMac68kAttr>()) {
1225 IsMac68kAlign = true;
Ken Dyck02ced6f2011-02-17 01:49:42 +00001226 MaxFieldAlignment = CharUnits::fromQuantity(2);
Ken Dyck4731d5b2011-02-16 02:05:21 +00001227 Alignment = CharUnits::fromQuantity(2);
Daniel Dunbar6da10982010-05-27 05:45:51 +00001228 } else {
1229 if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>())
Ken Dyck02ced6f2011-02-17 01:49:42 +00001230 MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001231
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001232 if (unsigned MaxAlign = D->getMaxAlignment())
Ken Dyck85ef0432011-02-19 18:58:07 +00001233 UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign));
Daniel Dunbar6da10982010-05-27 05:45:51 +00001234 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001235
1236 // If there is an external AST source, ask it for the various offsets.
1237 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
1238 if (ExternalASTSource *External = Context.getExternalSource()) {
1239 ExternalLayout = External->layoutRecordType(RD,
1240 ExternalSize,
1241 ExternalAlign,
1242 ExternalFieldOffsets,
1243 ExternalBaseOffsets,
1244 ExternalVirtualBaseOffsets);
1245
1246 // Update based on external alignment.
1247 if (ExternalLayout) {
Douglas Gregor44ba7892012-01-28 00:53:29 +00001248 if (ExternalAlign > 0) {
1249 Alignment = Context.toCharUnitsFromBits(ExternalAlign);
Douglas Gregor44ba7892012-01-28 00:53:29 +00001250 } else {
1251 // The external source didn't have alignment information; infer it.
1252 InferAlignment = true;
1253 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001254 }
1255 }
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001256}
Anders Carlsson6d9f6f32009-07-19 00:18:47 +00001257
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001258void RecordLayoutBuilder::Layout(const RecordDecl *D) {
1259 InitializeLayout(D);
Anders Carlsson118ce162009-07-18 21:48:39 +00001260 LayoutFields(D);
Mike Stump11289f42009-09-09 15:08:12 +00001261
Anders Carlsson79474332009-07-18 20:20:21 +00001262 // Finally, round the size of the total struct up to the alignment of the
1263 // struct itself.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001264 FinishLayout(D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001265}
1266
1267void RecordLayoutBuilder::Layout(const CXXRecordDecl *RD) {
1268 InitializeLayout(RD);
1269
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001270 // Lay out the vtable and the non-virtual bases.
1271 LayoutNonVirtualBases(RD);
1272
1273 LayoutFields(RD);
1274
Ken Dycke7380752011-03-10 01:53:59 +00001275 NonVirtualSize = Context.toCharUnitsFromBits(
1276 llvm::RoundUpToAlignment(getSizeInBits(),
Douglas Gregore8bbc122011-09-02 00:18:52 +00001277 Context.getTargetInfo().getCharAlign()));
Ken Dyck4731d5b2011-02-16 02:05:21 +00001278 NonVirtualAlignment = Alignment;
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001279
Warren Hunt55d8e822013-10-23 23:53:07 +00001280 // Lay out the virtual bases and add the primary virtual base offsets.
1281 LayoutVirtualBases(RD, RD);
John McCall0153cd32011-11-08 04:01:03 +00001282
1283 // Finally, round the size of the total struct up to the alignment
Eli Friedman83a12582011-12-01 00:37:01 +00001284 // of the struct itself.
1285 FinishLayout(RD);
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001286
Anders Carlsson5b441d72010-04-10 21:24:48 +00001287#ifndef NDEBUG
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001288 // Check that we have base offsets for all bases.
David Majnemerc964b4b2014-07-16 06:04:00 +00001289 for (const CXXBaseSpecifier &Base : RD->bases()) {
1290 if (Base.isVirtual())
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001291 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001292
David Majnemerc964b4b2014-07-16 06:04:00 +00001293 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001294
1295 assert(Bases.count(BaseDecl) && "Did not find base offset!");
1296 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001297
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001298 // And all virtual bases.
David Majnemerc964b4b2014-07-16 06:04:00 +00001299 for (const CXXBaseSpecifier &Base : RD->vbases()) {
1300 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001301
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001302 assert(VBases.count(BaseDecl) && "Did not find base offset!");
Anders Carlsson5b441d72010-04-10 21:24:48 +00001303 }
1304#endif
Anders Carlsson79474332009-07-18 20:20:21 +00001305}
1306
Anders Carlssonc2226202010-05-26 05:58:59 +00001307void RecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) {
Anders Carlsson4f516282009-07-18 20:50:59 +00001308 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001309 const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD);
Anders Carlsson4f516282009-07-18 20:50:59 +00001310
Ken Dyck85ef0432011-02-19 18:58:07 +00001311 UpdateAlignment(SL.getAlignment());
Mike Stump11289f42009-09-09 15:08:12 +00001312
Anders Carlsson4f516282009-07-18 20:50:59 +00001313 // We start laying out ivars not at the end of the superclass
1314 // structure, but at the next byte following the last field.
Ken Dyckecfc7552011-02-24 01:13:28 +00001315 setSize(SL.getDataSize());
Ken Dyck1b4420e2011-02-28 02:01:38 +00001316 setDataSize(getSize());
Anders Carlsson4f516282009-07-18 20:50:59 +00001317 }
Mike Stump11289f42009-09-09 15:08:12 +00001318
Daniel Dunbar6da10982010-05-27 05:45:51 +00001319 InitializeLayout(D);
Anders Carlsson4f516282009-07-18 20:50:59 +00001320 // Layout each ivar sequentially.
Jordy Rosea91768e2011-07-22 02:08:32 +00001321 for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD;
1322 IVD = IVD->getNextIvar())
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001323 LayoutField(IVD, false);
Mike Stump11289f42009-09-09 15:08:12 +00001324
Anders Carlsson4f516282009-07-18 20:50:59 +00001325 // Finally, round the size of the total struct up to the alignment of the
1326 // struct itself.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001327 FinishLayout(D);
Anders Carlsson4f516282009-07-18 20:50:59 +00001328}
1329
Anders Carlssonc2226202010-05-26 05:58:59 +00001330void RecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
Anders Carlsson118ce162009-07-18 21:48:39 +00001331 // Layout each field, for now, just sequentially, respecting alignment. In
1332 // the future, this will need to be tweakable by targets.
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001333 bool InsertExtraPadding = D->mayInsertExtraPadding(/*EmitRemark=*/true);
Kostya Serebryany68c29da2014-10-27 19:34:10 +00001334 bool HasFlexibleArrayMember = D->hasFlexibleArrayMember();
1335 for (auto I = D->field_begin(), End = D->field_end(); I != End; ++I) {
1336 auto Next(I);
1337 ++Next;
1338 LayoutField(*I,
1339 InsertExtraPadding && (Next != End || !HasFlexibleArrayMember));
1340 }
Anders Carlsson118ce162009-07-18 21:48:39 +00001341}
1342
Artyom Skrobov5e63acc2014-10-17 10:22:03 +00001343// Rounds the specified size to have it a multiple of the char size.
1344static uint64_t
1345roundUpSizeToCharAlignment(uint64_t Size,
1346 const ASTContext &Context) {
1347 uint64_t CharAlignment = Context.getTargetInfo().getCharAlign();
1348 return llvm::RoundUpToAlignment(Size, CharAlignment);
1349}
1350
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001351void RecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize,
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001352 uint64_t TypeSize,
1353 bool FieldPacked,
1354 const FieldDecl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001355 assert(Context.getLangOpts().CPlusPlus &&
Anders Carlsson57235162010-04-16 15:57:11 +00001356 "Can only have wide bit-fields in C++!");
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001357
Anders Carlsson57235162010-04-16 15:57:11 +00001358 // Itanium C++ ABI 2.4:
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001359 // If sizeof(T)*8 < n, let T' be the largest integral POD type with
Anders Carlsson57235162010-04-16 15:57:11 +00001360 // sizeof(T')*8 <= n.
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001361
Anders Carlsson57235162010-04-16 15:57:11 +00001362 QualType IntegralPODTypes[] = {
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001363 Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy,
Anders Carlsson57235162010-04-16 15:57:11 +00001364 Context.UnsignedLongTy, Context.UnsignedLongLongTy
1365 };
1366
Anders Carlsson57235162010-04-16 15:57:11 +00001367 QualType Type;
David Majnemerc964b4b2014-07-16 06:04:00 +00001368 for (const QualType &QT : IntegralPODTypes) {
1369 uint64_t Size = Context.getTypeSize(QT);
Anders Carlsson57235162010-04-16 15:57:11 +00001370
1371 if (Size > FieldSize)
1372 break;
1373
David Majnemerc964b4b2014-07-16 06:04:00 +00001374 Type = QT;
Anders Carlsson57235162010-04-16 15:57:11 +00001375 }
1376 assert(!Type.isNull() && "Did not find a type!");
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001377
Ken Dyckdbe37f32011-03-01 01:36:00 +00001378 CharUnits TypeAlign = Context.getTypeAlignInChars(Type);
Anders Carlsson57235162010-04-16 15:57:11 +00001379
1380 // We're not going to use any of the unfilled bits in the last byte.
Eli Friedman2782dac2013-06-26 20:50:34 +00001381 UnfilledBitsInLastUnit = 0;
1382 LastBitfieldTypeSize = 0;
Anders Carlsson57235162010-04-16 15:57:11 +00001383
Anders Carlssonaad5fa82010-04-17 20:21:41 +00001384 uint64_t FieldOffset;
Eli Friedman2782dac2013-06-26 20:50:34 +00001385 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001386
Anders Carlsson57235162010-04-16 15:57:11 +00001387 if (IsUnion) {
Artyom Skrobov5e63acc2014-10-17 10:22:03 +00001388 uint64_t RoundedFieldSize = roundUpSizeToCharAlignment(FieldSize,
1389 Context);
1390 setDataSize(std::max(getDataSizeInBits(), RoundedFieldSize));
Anders Carlssonaad5fa82010-04-17 20:21:41 +00001391 FieldOffset = 0;
Anders Carlsson57235162010-04-16 15:57:11 +00001392 } else {
Chad Rosiere1a6a0e2011-08-05 22:38:04 +00001393 // The bitfield is allocated starting at the next offset aligned
1394 // appropriately for T', with length n bits.
Ken Dyckdbe37f32011-03-01 01:36:00 +00001395 FieldOffset = llvm::RoundUpToAlignment(getDataSizeInBits(),
1396 Context.toBits(TypeAlign));
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001397
Anders Carlsson57235162010-04-16 15:57:11 +00001398 uint64_t NewSizeInBits = FieldOffset + FieldSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001399
Ken Dycka1a2e8d2011-03-10 02:00:35 +00001400 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
Douglas Gregore8bbc122011-09-02 00:18:52 +00001401 Context.getTargetInfo().getCharAlign()));
Eli Friedman2782dac2013-06-26 20:50:34 +00001402 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
Anders Carlsson57235162010-04-16 15:57:11 +00001403 }
1404
1405 // Place this field at the current location.
1406 FieldOffsets.push_back(FieldOffset);
1407
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001408 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset,
Ken Dyckdbe37f32011-03-01 01:36:00 +00001409 Context.toBits(TypeAlign), FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001410
Anders Carlsson57235162010-04-16 15:57:11 +00001411 // Update the size.
Ken Dyckecfc7552011-02-24 01:13:28 +00001412 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001413
Anders Carlsson57235162010-04-16 15:57:11 +00001414 // Remember max struct/class alignment.
Ken Dyckdbe37f32011-03-01 01:36:00 +00001415 UpdateAlignment(TypeAlign);
Anders Carlsson57235162010-04-16 15:57:11 +00001416}
1417
Anders Carlssonc2226202010-05-26 05:58:59 +00001418void RecordLayoutBuilder::LayoutBitField(const FieldDecl *D) {
Anders Carlsson07209442009-11-22 17:37:31 +00001419 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
Richard Smithcaf33902011-10-10 18:28:20 +00001420 uint64_t FieldSize = D->getBitWidthValue(Context);
David Majnemer34b57492014-07-30 01:30:47 +00001421 TypeInfo FieldInfo = Context.getTypeInfo(D->getType());
1422 uint64_t TypeSize = FieldInfo.Width;
1423 unsigned FieldAlign = FieldInfo.Align;
Eli Friedman2782dac2013-06-26 20:50:34 +00001424
John McCall30268ca2014-01-29 07:53:44 +00001425 // UnfilledBitsInLastUnit is the difference between the end of the
1426 // last allocated bitfield (i.e. the first bit offset available for
1427 // bitfields) and the end of the current data size in bits (i.e. the
1428 // first bit offset available for non-bitfields). The current data
1429 // size in bits is always a multiple of the char size; additionally,
1430 // for ms_struct records it's also a multiple of the
1431 // LastBitfieldTypeSize (if set).
1432
John McCall76e1818a2014-02-13 00:50:08 +00001433 // The struct-layout algorithm is dictated by the platform ABI,
1434 // which in principle could use almost any rules it likes. In
1435 // practice, UNIXy targets tend to inherit the algorithm described
1436 // in the System V generic ABI. The basic bitfield layout rule in
1437 // System V is to place bitfields at the next available bit offset
1438 // where the entire bitfield would fit in an aligned storage unit of
1439 // the declared type; it's okay if an earlier or later non-bitfield
1440 // is allocated in the same storage unit. However, some targets
1441 // (those that !useBitFieldTypeAlignment(), e.g. ARM APCS) don't
1442 // require this storage unit to be aligned, and therefore always put
1443 // the bitfield at the next available bit offset.
John McCall30268ca2014-01-29 07:53:44 +00001444
John McCall76e1818a2014-02-13 00:50:08 +00001445 // ms_struct basically requests a complete replacement of the
1446 // platform ABI's struct-layout algorithm, with the high-level goal
1447 // of duplicating MSVC's layout. For non-bitfields, this follows
1448 // the the standard algorithm. The basic bitfield layout rule is to
1449 // allocate an entire unit of the bitfield's declared type
1450 // (e.g. 'unsigned long'), then parcel it up among successive
1451 // bitfields whose declared types have the same size, making a new
1452 // unit as soon as the last can no longer store the whole value.
1453 // Since it completely replaces the platform ABI's algorithm,
1454 // settings like !useBitFieldTypeAlignment() do not apply.
1455
1456 // A zero-width bitfield forces the use of a new storage unit for
1457 // later bitfields. In general, this occurs by rounding up the
1458 // current size of the struct as if the algorithm were about to
1459 // place a non-bitfield of the field's formal type. Usually this
1460 // does not change the alignment of the struct itself, but it does
1461 // on some targets (those that useZeroLengthBitfieldAlignment(),
1462 // e.g. ARM). In ms_struct layout, zero-width bitfields are
1463 // ignored unless they follow a non-zero-width bitfield.
1464
1465 // A field alignment restriction (e.g. from #pragma pack) or
1466 // specification (e.g. from __attribute__((aligned))) changes the
1467 // formal alignment of the field. For System V, this alters the
1468 // required alignment of the notional storage unit that must contain
1469 // the bitfield. For ms_struct, this only affects the placement of
1470 // new storage units. In both cases, the effect of #pragma pack is
1471 // ignored on zero-width bitfields.
1472
1473 // On System V, a packed field (e.g. from #pragma pack or
1474 // __attribute__((packed))) always uses the next available bit
1475 // offset.
1476
John McCall95833f32014-02-27 20:30:49 +00001477 // In an ms_struct struct, the alignment of a fundamental type is
1478 // always equal to its size. This is necessary in order to mimic
1479 // the i386 alignment rules on targets which might not fully align
1480 // all types (e.g. Darwin PPC32, where alignof(long long) == 4).
John McCall30268ca2014-01-29 07:53:44 +00001481
1482 // First, some simple bookkeeping to perform for ms_struct structs.
Eli Friedman2782dac2013-06-26 20:50:34 +00001483 if (IsMsStruct) {
John McCall30268ca2014-01-29 07:53:44 +00001484 // The field alignment for integer types is always the size.
Fariborz Jahanian7adbed62011-05-09 22:03:17 +00001485 FieldAlign = TypeSize;
John McCall30268ca2014-01-29 07:53:44 +00001486
1487 // If the previous field was not a bitfield, or was a bitfield
1488 // with a different storage unit size, we're done with that
1489 // storage unit.
Eli Friedman2782dac2013-06-26 20:50:34 +00001490 if (LastBitfieldTypeSize != TypeSize) {
John McCall30268ca2014-01-29 07:53:44 +00001491 // Also, ignore zero-length bitfields after non-bitfields.
1492 if (!LastBitfieldTypeSize && !FieldSize)
1493 FieldAlign = 1;
1494
Eli Friedman2782dac2013-06-26 20:50:34 +00001495 UnfilledBitsInLastUnit = 0;
1496 LastBitfieldTypeSize = 0;
1497 }
1498 }
1499
John McCall30268ca2014-01-29 07:53:44 +00001500 // If the field is wider than its declared type, it follows
1501 // different rules in all cases.
Anders Carlsson57235162010-04-16 15:57:11 +00001502 if (FieldSize > TypeSize) {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001503 LayoutWideBitField(FieldSize, TypeSize, FieldPacked, D);
Anders Carlsson57235162010-04-16 15:57:11 +00001504 return;
1505 }
1506
John McCall30268ca2014-01-29 07:53:44 +00001507 // Compute the next available bit offset.
1508 uint64_t FieldOffset =
1509 IsUnion ? 0 : (getDataSizeInBits() - UnfilledBitsInLastUnit);
1510
1511 // Handle targets that don't honor bitfield type alignment.
John McCall76e1818a2014-02-13 00:50:08 +00001512 if (!IsMsStruct && !Context.getTargetInfo().useBitFieldTypeAlignment()) {
John McCall30268ca2014-01-29 07:53:44 +00001513 // Some such targets do honor it on zero-width bitfields.
1514 if (FieldSize == 0 &&
1515 Context.getTargetInfo().useZeroLengthBitfieldAlignment()) {
1516 // The alignment to round up to is the max of the field's natural
1517 // alignment and a target-specific fixed value (sometimes zero).
1518 unsigned ZeroLengthBitfieldBoundary =
1519 Context.getTargetInfo().getZeroLengthBitfieldBoundary();
1520 FieldAlign = std::max(FieldAlign, ZeroLengthBitfieldBoundary);
1521
1522 // If that doesn't apply, just ignore the field alignment.
1523 } else {
1524 FieldAlign = 1;
1525 }
1526 }
1527
1528 // Remember the alignment we would have used if the field were not packed.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001529 unsigned UnpackedFieldAlign = FieldAlign;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001530
Yunzhong Gao5fd0c9d2014-02-13 02:45:10 +00001531 // Ignore the field alignment if the field is packed unless it has zero-size.
1532 if (!IsMsStruct && FieldPacked && FieldSize != 0)
Anders Carlsson07209442009-11-22 17:37:31 +00001533 FieldAlign = 1;
Anders Carlsson07209442009-11-22 17:37:31 +00001534
John McCall30268ca2014-01-29 07:53:44 +00001535 // But, if there's an 'aligned' attribute on the field, honor that.
1536 if (unsigned ExplicitFieldAlign = D->getMaxAlignment()) {
1537 FieldAlign = std::max(FieldAlign, ExplicitFieldAlign);
1538 UnpackedFieldAlign = std::max(UnpackedFieldAlign, ExplicitFieldAlign);
1539 }
1540
1541 // But, if there's a #pragma pack in play, that takes precedent over
1542 // even the 'aligned' attribute, for non-zero-width bitfields.
1543 if (!MaxFieldAlignment.isZero() && FieldSize) {
Ken Dyck02ced6f2011-02-17 01:49:42 +00001544 unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment);
1545 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1546 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001547 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001548
John McCall30268ca2014-01-29 07:53:44 +00001549 // For purposes of diagnostics, we're going to simultaneously
1550 // compute the field offsets that we would have used if we weren't
1551 // adding any alignment padding or if the field weren't packed.
1552 uint64_t UnpaddedFieldOffset = FieldOffset;
1553 uint64_t UnpackedFieldOffset = FieldOffset;
1554
1555 // Check if we need to add padding to fit the bitfield within an
1556 // allocation unit with the right size and alignment. The rules are
1557 // somewhat different here for ms_struct structs.
1558 if (IsMsStruct) {
1559 // If it's not a zero-width bitfield, and we can fit the bitfield
1560 // into the active storage unit (and we haven't already decided to
1561 // start a new storage unit), just do so, regardless of any other
1562 // other consideration. Otherwise, round up to the right alignment.
1563 if (FieldSize == 0 || FieldSize > UnfilledBitsInLastUnit) {
1564 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
1565 UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1566 UnpackedFieldAlign);
1567 UnfilledBitsInLastUnit = 0;
1568 }
1569
1570 } else {
1571 // #pragma pack, with any value, suppresses the insertion of padding.
1572 bool AllowPadding = MaxFieldAlignment.isZero();
1573
1574 // Compute the real offset.
1575 if (FieldSize == 0 ||
1576 (AllowPadding &&
1577 (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)) {
1578 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
1579 }
1580
1581 // Repeat the computation for diagnostic purposes.
1582 if (FieldSize == 0 ||
1583 (AllowPadding &&
1584 (UnpackedFieldOffset & (UnpackedFieldAlign-1)) + FieldSize > TypeSize))
1585 UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1586 UnpackedFieldAlign);
Eli Friedman2782dac2013-06-26 20:50:34 +00001587 }
1588
John McCall30268ca2014-01-29 07:53:44 +00001589 // If we're using external layout, give the external layout a chance
1590 // to override this information.
Douglas Gregor44ba7892012-01-28 00:53:29 +00001591 if (ExternalLayout)
1592 FieldOffset = updateExternalFieldOffset(D, FieldOffset);
1593
John McCall30268ca2014-01-29 07:53:44 +00001594 // Okay, place the bitfield at the calculated offset.
Anders Carlsson07209442009-11-22 17:37:31 +00001595 FieldOffsets.push_back(FieldOffset);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001596
John McCall30268ca2014-01-29 07:53:44 +00001597 // Bookkeeping:
1598
1599 // Anonymous members don't affect the overall record alignment,
1600 // except on targets where they do.
1601 if (!IsMsStruct &&
1602 !Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
1603 !D->getIdentifier())
1604 FieldAlign = UnpackedFieldAlign = 1;
1605
1606 // Diagnose differences in layout due to padding or packing.
Douglas Gregore9fc3772012-01-26 07:55:45 +00001607 if (!ExternalLayout)
1608 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset,
1609 UnpackedFieldAlign, FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001610
Anders Carlssonba958402009-11-22 19:13:51 +00001611 // Update DataSize to include the last byte containing (part of) the bitfield.
John McCall30268ca2014-01-29 07:53:44 +00001612
1613 // For unions, this is just a max operation, as usual.
Anders Carlssonba958402009-11-22 19:13:51 +00001614 if (IsUnion) {
Artyom Skrobov5e63acc2014-10-17 10:22:03 +00001615 uint64_t RoundedFieldSize = roundUpSizeToCharAlignment(FieldSize,
1616 Context);
1617 setDataSize(std::max(getDataSizeInBits(), RoundedFieldSize));
John McCall30268ca2014-01-29 07:53:44 +00001618 // For non-zero-width bitfields in ms_struct structs, allocate a new
1619 // storage unit if necessary.
1620 } else if (IsMsStruct && FieldSize) {
1621 // We should have cleared UnfilledBitsInLastUnit in every case
1622 // where we changed storage units.
1623 if (!UnfilledBitsInLastUnit) {
1624 setDataSize(FieldOffset + TypeSize);
1625 UnfilledBitsInLastUnit = TypeSize;
Eli Friedman2782dac2013-06-26 20:50:34 +00001626 }
John McCall30268ca2014-01-29 07:53:44 +00001627 UnfilledBitsInLastUnit -= FieldSize;
1628 LastBitfieldTypeSize = TypeSize;
1629
1630 // Otherwise, bump the data size up to include the bitfield,
1631 // including padding up to char alignment, and then remember how
1632 // bits we didn't use.
1633 } else {
1634 uint64_t NewSizeInBits = FieldOffset + FieldSize;
1635 uint64_t CharAlignment = Context.getTargetInfo().getCharAlign();
1636 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits, CharAlignment));
1637 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
1638
1639 // The only time we can get here for an ms_struct is if this is a
1640 // zero-width bitfield, which doesn't count as anything for the
1641 // purposes of unfilled bits.
1642 LastBitfieldTypeSize = 0;
Anders Carlssonba958402009-11-22 19:13:51 +00001643 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001644
Anders Carlssonba958402009-11-22 19:13:51 +00001645 // Update the size.
Ken Dyckecfc7552011-02-24 01:13:28 +00001646 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001647
Anders Carlsson07209442009-11-22 17:37:31 +00001648 // Remember max struct/class alignment.
Ken Dyck85ef0432011-02-19 18:58:07 +00001649 UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign),
1650 Context.toCharUnitsFromBits(UnpackedFieldAlign));
Anders Carlsson07209442009-11-22 17:37:31 +00001651}
1652
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001653void RecordLayoutBuilder::LayoutField(const FieldDecl *D,
1654 bool InsertExtraPadding) {
Anders Carlsson07209442009-11-22 17:37:31 +00001655 if (D->isBitField()) {
1656 LayoutBitField(D);
1657 return;
1658 }
1659
Eli Friedman2782dac2013-06-26 20:50:34 +00001660 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001661
Anders Carlssonba958402009-11-22 19:13:51 +00001662 // Reset the unfilled bits.
Eli Friedman2782dac2013-06-26 20:50:34 +00001663 UnfilledBitsInLastUnit = 0;
1664 LastBitfieldTypeSize = 0;
Anders Carlssonba958402009-11-22 19:13:51 +00001665
Anders Carlsson07209442009-11-22 17:37:31 +00001666 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
Ken Dyck6d90e892011-02-20 02:06:09 +00001667 CharUnits FieldOffset =
Ken Dyckecfc7552011-02-24 01:13:28 +00001668 IsUnion ? CharUnits::Zero() : getDataSize();
Ken Dyck6d90e892011-02-20 02:06:09 +00001669 CharUnits FieldSize;
1670 CharUnits FieldAlign;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001671
Anders Carlsson07209442009-11-22 17:37:31 +00001672 if (D->getType()->isIncompleteArrayType()) {
1673 // This is a flexible array member; we can't directly
1674 // query getTypeInfo about these, so we figure it out here.
1675 // Flexible array members don't have any size, but they
1676 // have to be aligned appropriately for their element type.
Ken Dyck6d90e892011-02-20 02:06:09 +00001677 FieldSize = CharUnits::Zero();
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001678 const ArrayType* ATy = Context.getAsArrayType(D->getType());
Ken Dyck6d90e892011-02-20 02:06:09 +00001679 FieldAlign = Context.getTypeAlignInChars(ATy->getElementType());
Anders Carlsson07209442009-11-22 17:37:31 +00001680 } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) {
1681 unsigned AS = RT->getPointeeType().getAddressSpace();
Ken Dyck6d90e892011-02-20 02:06:09 +00001682 FieldSize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001683 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(AS));
Ken Dyck6d90e892011-02-20 02:06:09 +00001684 FieldAlign =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001685 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(AS));
Anders Carlsson79474332009-07-18 20:20:21 +00001686 } else {
Ken Dyck6d90e892011-02-20 02:06:09 +00001687 std::pair<CharUnits, CharUnits> FieldInfo =
1688 Context.getTypeInfoInChars(D->getType());
Anders Carlsson07209442009-11-22 17:37:31 +00001689 FieldSize = FieldInfo.first;
1690 FieldAlign = FieldInfo.second;
Chad Rosier18903ee2011-08-04 01:21:14 +00001691
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001692 if (IsMsStruct) {
Douglas Gregordbe39272011-02-01 15:15:22 +00001693 // If MS bitfield layout is required, figure out what type is being
1694 // laid out and align the field to the width of that type.
1695
1696 // Resolve all typedefs down to their base type and round up the field
1697 // alignment if necessary.
1698 QualType T = Context.getBaseElementType(D->getType());
1699 if (const BuiltinType *BTy = T->getAs<BuiltinType>()) {
Ken Dyck6d90e892011-02-20 02:06:09 +00001700 CharUnits TypeSize = Context.getTypeSizeInChars(BTy);
Douglas Gregordbe39272011-02-01 15:15:22 +00001701 if (TypeSize > FieldAlign)
1702 FieldAlign = TypeSize;
1703 }
1704 }
Anders Carlsson79474332009-07-18 20:20:21 +00001705 }
Mike Stump11289f42009-09-09 15:08:12 +00001706
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001707 // The align if the field is not packed. This is to check if the attribute
1708 // was unnecessary (-Wpacked).
Ken Dyck6d90e892011-02-20 02:06:09 +00001709 CharUnits UnpackedFieldAlign = FieldAlign;
1710 CharUnits UnpackedFieldOffset = FieldOffset;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001711
Anders Carlsson07209442009-11-22 17:37:31 +00001712 if (FieldPacked)
Ken Dyck6d90e892011-02-20 02:06:09 +00001713 FieldAlign = CharUnits::One();
1714 CharUnits MaxAlignmentInChars =
1715 Context.toCharUnitsFromBits(D->getMaxAlignment());
1716 FieldAlign = std::max(FieldAlign, MaxAlignmentInChars);
1717 UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars);
Anders Carlsson07209442009-11-22 17:37:31 +00001718
1719 // The maximum field alignment overrides the aligned attribute.
Ken Dyck02ced6f2011-02-17 01:49:42 +00001720 if (!MaxFieldAlignment.isZero()) {
Ken Dyck6d90e892011-02-20 02:06:09 +00001721 FieldAlign = std::min(FieldAlign, MaxFieldAlignment);
1722 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001723 }
Anders Carlsson07209442009-11-22 17:37:31 +00001724
Douglas Gregor44ba7892012-01-28 00:53:29 +00001725 // Round up the current record size to the field's alignment boundary.
1726 FieldOffset = FieldOffset.RoundUpToAlignment(FieldAlign);
1727 UnpackedFieldOffset =
1728 UnpackedFieldOffset.RoundUpToAlignment(UnpackedFieldAlign);
1729
1730 if (ExternalLayout) {
1731 FieldOffset = Context.toCharUnitsFromBits(
1732 updateExternalFieldOffset(D, Context.toBits(FieldOffset)));
1733
1734 if (!IsUnion && EmptySubobjects) {
1735 // Record the fact that we're placing a field at this offset.
1736 bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset);
1737 (void)Allowed;
1738 assert(Allowed && "Externally-placed field cannot be placed here");
1739 }
1740 } else {
Douglas Gregore9fc3772012-01-26 07:55:45 +00001741 if (!IsUnion && EmptySubobjects) {
1742 // Check if we can place the field at this offset.
1743 while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) {
1744 // We couldn't place the field at the offset. Try again at a new offset.
1745 FieldOffset += FieldAlign;
1746 }
Anders Carlsson07209442009-11-22 17:37:31 +00001747 }
Anders Carlsson07209442009-11-22 17:37:31 +00001748 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001749
Anders Carlsson79474332009-07-18 20:20:21 +00001750 // Place this field at the current location.
Ken Dyck6d90e892011-02-20 02:06:09 +00001751 FieldOffsets.push_back(Context.toBits(FieldOffset));
Mike Stump11289f42009-09-09 15:08:12 +00001752
Douglas Gregore9fc3772012-01-26 07:55:45 +00001753 if (!ExternalLayout)
1754 CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset,
1755 Context.toBits(UnpackedFieldOffset),
1756 Context.toBits(UnpackedFieldAlign), FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001757
Kostya Serebryany68c29da2014-10-27 19:34:10 +00001758 if (InsertExtraPadding) {
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001759 CharUnits ASanAlignment = CharUnits::fromQuantity(8);
1760 CharUnits ExtraSizeForAsan = ASanAlignment;
1761 if (FieldSize % ASanAlignment)
1762 ExtraSizeForAsan +=
1763 ASanAlignment - CharUnits::fromQuantity(FieldSize % ASanAlignment);
1764 FieldSize += ExtraSizeForAsan;
1765 }
1766
Anders Carlsson79474332009-07-18 20:20:21 +00001767 // Reserve space for this field.
Eli Friedman43f18342012-01-12 23:27:03 +00001768 uint64_t FieldSizeInBits = Context.toBits(FieldSize);
Anders Carlsson79474332009-07-18 20:20:21 +00001769 if (IsUnion)
Eli Friedman2e108372012-01-12 23:48:56 +00001770 setDataSize(std::max(getDataSizeInBits(), FieldSizeInBits));
Anders Carlsson79474332009-07-18 20:20:21 +00001771 else
Eli Friedman2e108372012-01-12 23:48:56 +00001772 setDataSize(FieldOffset + FieldSize);
Mike Stump11289f42009-09-09 15:08:12 +00001773
Eli Friedman2e108372012-01-12 23:48:56 +00001774 // Update the size.
1775 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Mike Stump11289f42009-09-09 15:08:12 +00001776
Anders Carlsson79474332009-07-18 20:20:21 +00001777 // Remember max struct/class alignment.
Ken Dyck6d90e892011-02-20 02:06:09 +00001778 UpdateAlignment(FieldAlign, UnpackedFieldAlign);
Anders Carlsson79474332009-07-18 20:20:21 +00001779}
1780
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001781void RecordLayoutBuilder::FinishLayout(const NamedDecl *D) {
Anders Carlsson79474332009-07-18 20:20:21 +00001782 // In C++, records cannot be of size 0.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001783 if (Context.getLangOpts().CPlusPlus && getSizeInBits() == 0) {
Fariborz Jahanian09b23312011-02-02 19:36:18 +00001784 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
1785 // Compatibility with gcc requires a class (pod or non-pod)
1786 // which is not empty but of size 0; such as having fields of
1787 // array of zero-length, remains of Size 0
1788 if (RD->isEmpty())
Ken Dyck1b4420e2011-02-28 02:01:38 +00001789 setSize(CharUnits::One());
Fariborz Jahanian09b23312011-02-02 19:36:18 +00001790 }
1791 else
Ken Dyck1b4420e2011-02-28 02:01:38 +00001792 setSize(CharUnits::One());
Fariborz Jahanian09b23312011-02-02 19:36:18 +00001793 }
Eli Friedman83a12582011-12-01 00:37:01 +00001794
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001795 // Finally, round the size of the record up to the alignment of the
1796 // record itself.
Eli Friedman2782dac2013-06-26 20:50:34 +00001797 uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastUnit;
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001798 uint64_t UnpackedSizeInBits =
1799 llvm::RoundUpToAlignment(getSizeInBits(),
1800 Context.toBits(UnpackedAlignment));
1801 CharUnits UnpackedSize = Context.toCharUnitsFromBits(UnpackedSizeInBits);
1802 uint64_t RoundedSize
1803 = llvm::RoundUpToAlignment(getSizeInBits(), Context.toBits(Alignment));
1804
1805 if (ExternalLayout) {
1806 // If we're inferring alignment, and the external size is smaller than
1807 // our size after we've rounded up to alignment, conservatively set the
1808 // alignment to 1.
1809 if (InferAlignment && ExternalSize < RoundedSize) {
1810 Alignment = CharUnits::One();
1811 InferAlignment = false;
1812 }
1813 setSize(ExternalSize);
1814 return;
1815 }
1816
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001817 // Set the size to the final size.
1818 setSize(RoundedSize);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001819
Douglas Gregore8bbc122011-09-02 00:18:52 +00001820 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001821 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1822 // Warn if padding was introduced to the struct/class/union.
Ken Dyckecfc7552011-02-24 01:13:28 +00001823 if (getSizeInBits() > UnpaddedSize) {
1824 unsigned PadSize = getSizeInBits() - UnpaddedSize;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001825 bool InBits = true;
1826 if (PadSize % CharBitNum == 0) {
1827 PadSize = PadSize / CharBitNum;
1828 InBits = false;
1829 }
1830 Diag(RD->getLocation(), diag::warn_padded_struct_size)
1831 << Context.getTypeDeclType(RD)
1832 << PadSize
1833 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
1834 }
1835
1836 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
1837 // bother since there won't be alignment issues.
Ken Dyckecfc7552011-02-24 01:13:28 +00001838 if (Packed && UnpackedAlignment > CharUnits::One() &&
Ken Dyck1b4420e2011-02-28 02:01:38 +00001839 getSize() == UnpackedSize)
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001840 Diag(D->getLocation(), diag::warn_unnecessary_packed)
1841 << Context.getTypeDeclType(RD);
1842 }
Anders Carlsson79474332009-07-18 20:20:21 +00001843}
1844
Ken Dyck85ef0432011-02-19 18:58:07 +00001845void RecordLayoutBuilder::UpdateAlignment(CharUnits NewAlignment,
1846 CharUnits UnpackedNewAlignment) {
Douglas Gregore9fc3772012-01-26 07:55:45 +00001847 // The alignment is not modified when using 'mac68k' alignment or when
Douglas Gregor44ba7892012-01-28 00:53:29 +00001848 // we have an externally-supplied layout that also provides overall alignment.
1849 if (IsMac68kAlign || (ExternalLayout && !InferAlignment))
Daniel Dunbar6da10982010-05-27 05:45:51 +00001850 return;
1851
Ken Dyck85ef0432011-02-19 18:58:07 +00001852 if (NewAlignment > Alignment) {
1853 assert(llvm::isPowerOf2_32(NewAlignment.getQuantity() &&
1854 "Alignment not a power of 2"));
1855 Alignment = NewAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001856 }
1857
Ken Dyck85ef0432011-02-19 18:58:07 +00001858 if (UnpackedNewAlignment > UnpackedAlignment) {
1859 assert(llvm::isPowerOf2_32(UnpackedNewAlignment.getQuantity() &&
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001860 "Alignment not a power of 2"));
Ken Dyck85ef0432011-02-19 18:58:07 +00001861 UnpackedAlignment = UnpackedNewAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001862 }
1863}
1864
Douglas Gregor44ba7892012-01-28 00:53:29 +00001865uint64_t
1866RecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field,
1867 uint64_t ComputedOffset) {
1868 assert(ExternalFieldOffsets.find(Field) != ExternalFieldOffsets.end() &&
1869 "Field does not have an external offset");
1870
1871 uint64_t ExternalFieldOffset = ExternalFieldOffsets[Field];
1872
1873 if (InferAlignment && ExternalFieldOffset < ComputedOffset) {
1874 // The externally-supplied field offset is before the field offset we
1875 // computed. Assume that the structure is packed.
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001876 Alignment = CharUnits::One();
Douglas Gregor44ba7892012-01-28 00:53:29 +00001877 InferAlignment = false;
1878 }
1879
1880 // Use the externally-supplied field offset.
Benjamin Kramer648e68b2012-08-31 22:14:25 +00001881 return ExternalFieldOffset;
1882}
1883
1884/// \brief Get diagnostic %select index for tag kind for
1885/// field padding diagnostic message.
1886/// WARNING: Indexes apply to particular diagnostics only!
1887///
1888/// \returns diagnostic %select index.
1889static unsigned getPaddingDiagFromTagKind(TagTypeKind Tag) {
1890 switch (Tag) {
1891 case TTK_Struct: return 0;
1892 case TTK_Interface: return 1;
1893 case TTK_Class: return 2;
1894 default: llvm_unreachable("Invalid tag kind for field padding diagnostic!");
1895 }
1896}
1897
1898void RecordLayoutBuilder::CheckFieldPadding(uint64_t Offset,
1899 uint64_t UnpaddedOffset,
1900 uint64_t UnpackedOffset,
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001901 unsigned UnpackedAlign,
1902 bool isPacked,
1903 const FieldDecl *D) {
1904 // We let objc ivars without warning, objc interfaces generally are not used
1905 // for padding tricks.
1906 if (isa<ObjCIvarDecl>(D))
Anders Carlsson79474332009-07-18 20:20:21 +00001907 return;
Mike Stump11289f42009-09-09 15:08:12 +00001908
Ted Kremenekfed48af2011-09-06 19:40:45 +00001909 // Don't warn about structs created without a SourceLocation. This can
1910 // be done by clients of the AST, such as codegen.
1911 if (D->getLocation().isInvalid())
1912 return;
1913
Douglas Gregore8bbc122011-09-02 00:18:52 +00001914 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
Mike Stump11289f42009-09-09 15:08:12 +00001915
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001916 // Warn if padding was introduced to the struct/class.
1917 if (!IsUnion && Offset > UnpaddedOffset) {
1918 unsigned PadSize = Offset - UnpaddedOffset;
1919 bool InBits = true;
1920 if (PadSize % CharBitNum == 0) {
1921 PadSize = PadSize / CharBitNum;
1922 InBits = false;
Benjamin Kramer648e68b2012-08-31 22:14:25 +00001923 }
1924 if (D->getIdentifier())
1925 Diag(D->getLocation(), diag::warn_padded_struct_field)
1926 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
1927 << Context.getTypeDeclType(D->getParent())
1928 << PadSize
1929 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1) // plural or not
1930 << D->getIdentifier();
1931 else
1932 Diag(D->getLocation(), diag::warn_padded_struct_anon_field)
1933 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
1934 << Context.getTypeDeclType(D->getParent())
1935 << PadSize
1936 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001937 }
1938
1939 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
1940 // bother since there won't be alignment issues.
1941 if (isPacked && UnpackedAlign > CharBitNum && Offset == UnpackedOffset)
1942 Diag(D->getLocation(), diag::warn_unnecessary_packed)
1943 << D->getIdentifier();
Anders Carlsson79474332009-07-18 20:20:21 +00001944}
Mike Stump11289f42009-09-09 15:08:12 +00001945
John McCall6bd2a892013-01-25 22:31:03 +00001946static const CXXMethodDecl *computeKeyFunction(ASTContext &Context,
1947 const CXXRecordDecl *RD) {
Daniel Dunbarccabe482010-04-19 20:44:53 +00001948 // If a class isn't polymorphic it doesn't have a key function.
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00001949 if (!RD->isPolymorphic())
Craig Topper36250ad2014-05-12 05:36:57 +00001950 return nullptr;
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001951
Eli Friedman300f55d2011-06-10 21:53:06 +00001952 // A class that is not externally visible doesn't have a key function. (Or
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001953 // at least, there's no point to assigning a key function to such a class;
1954 // this doesn't affect the ABI.)
Rafael Espindola3ae00052013-05-13 00:12:11 +00001955 if (!RD->isExternallyVisible())
Craig Topper36250ad2014-05-12 05:36:57 +00001956 return nullptr;
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001957
Richard Smith750f5112014-03-24 23:54:09 +00001958 // Template instantiations don't have key functions per Itanium C++ ABI 5.2.6.
Argyrios Kyrtzidis8c64bbe2010-10-13 02:39:41 +00001959 // Same behavior as GCC.
1960 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
1961 if (TSK == TSK_ImplicitInstantiation ||
Richard Smith750f5112014-03-24 23:54:09 +00001962 TSK == TSK_ExplicitInstantiationDeclaration ||
Argyrios Kyrtzidis8c64bbe2010-10-13 02:39:41 +00001963 TSK == TSK_ExplicitInstantiationDefinition)
Craig Topper36250ad2014-05-12 05:36:57 +00001964 return nullptr;
Argyrios Kyrtzidis8c64bbe2010-10-13 02:39:41 +00001965
John McCall6bd2a892013-01-25 22:31:03 +00001966 bool allowInlineFunctions =
1967 Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline();
1968
David Majnemerc964b4b2014-07-16 06:04:00 +00001969 for (const CXXMethodDecl *MD : RD->methods()) {
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001970 if (!MD->isVirtual())
1971 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001972
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001973 if (MD->isPure())
1974 continue;
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001975
Anders Carlssonf98849e2009-12-02 17:15:43 +00001976 // Ignore implicit member functions, they are always marked as inline, but
1977 // they don't have a body until they're defined.
1978 if (MD->isImplicit())
1979 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001980
Douglas Gregora318efd2010-01-05 19:06:31 +00001981 if (MD->isInlineSpecified())
1982 continue;
Eli Friedman71a26d82009-12-06 20:50:05 +00001983
1984 if (MD->hasInlineBody())
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001985 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001986
Benjamin Kramer4a902082012-08-03 15:43:22 +00001987 // Ignore inline deleted or defaulted functions.
Benjamin Kramer73d1be72012-08-03 08:39:58 +00001988 if (!MD->isUserProvided())
1989 continue;
1990
John McCall6bd2a892013-01-25 22:31:03 +00001991 // In certain ABIs, ignore functions with out-of-line inline definitions.
1992 if (!allowInlineFunctions) {
1993 const FunctionDecl *Def;
1994 if (MD->hasBody(Def) && Def->isInlineSpecified())
1995 continue;
1996 }
1997
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001998 // We found it.
1999 return MD;
2000 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002001
Craig Topper36250ad2014-05-12 05:36:57 +00002002 return nullptr;
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002003}
2004
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002005DiagnosticBuilder
2006RecordLayoutBuilder::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +00002007 return Context.getDiagnostics().Report(Loc, DiagID);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002008}
2009
John McCall5c1f1d02013-01-29 01:14:22 +00002010/// Does the target C++ ABI require us to skip over the tail-padding
2011/// of the given class (considering it as a base class) when allocating
2012/// objects?
2013static bool mustSkipTailPadding(TargetCXXABI ABI, const CXXRecordDecl *RD) {
2014 switch (ABI.getTailPaddingUseRules()) {
2015 case TargetCXXABI::AlwaysUseTailPadding:
2016 return false;
2017
2018 case TargetCXXABI::UseTailPaddingUnlessPOD03:
2019 // FIXME: To the extent that this is meant to cover the Itanium ABI
2020 // rules, we should implement the restrictions about over-sized
2021 // bitfields:
2022 //
2023 // http://mentorembedded.github.com/cxx-abi/abi.html#POD :
2024 // In general, a type is considered a POD for the purposes of
2025 // layout if it is a POD type (in the sense of ISO C++
2026 // [basic.types]). However, a POD-struct or POD-union (in the
2027 // sense of ISO C++ [class]) with a bitfield member whose
2028 // declared width is wider than the declared type of the
2029 // bitfield is not a POD for the purpose of layout. Similarly,
2030 // an array type is not a POD for the purpose of layout if the
2031 // element type of the array is not a POD for the purpose of
2032 // layout.
2033 //
2034 // Where references to the ISO C++ are made in this paragraph,
2035 // the Technical Corrigendum 1 version of the standard is
2036 // intended.
2037 return RD->isPOD();
2038
2039 case TargetCXXABI::UseTailPaddingUnlessPOD11:
2040 // This is equivalent to RD->getTypeForDecl().isCXX11PODType(),
2041 // but with a lot of abstraction penalty stripped off. This does
2042 // assume that these properties are set correctly even in C++98
2043 // mode; fortunately, that is true because we want to assign
2044 // consistently semantics to the type-traits intrinsics (or at
2045 // least as many of them as possible).
2046 return RD->isTrivial() && RD->isStandardLayout();
2047 }
2048
2049 llvm_unreachable("bad tail-padding use kind");
2050}
2051
Warren Hunt8f8bad72013-10-11 20:19:00 +00002052static bool isMsLayout(const RecordDecl* D) {
Warren Hunt55d8e822013-10-23 23:53:07 +00002053 return D->getASTContext().getTargetInfo().getCXXABI().isMicrosoft();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002054}
2055
2056// This section contains an implementation of struct layout that is, up to the
Warren Hunt917f97f2014-04-11 00:54:15 +00002057// included tests, compatible with cl.exe (2013). The layout produced is
Warren Hunt8f8bad72013-10-11 20:19:00 +00002058// significantly different than those produced by the Itanium ABI. Here we note
2059// the most important differences.
2060//
2061// * The alignment of bitfields in unions is ignored when computing the
2062// alignment of the union.
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002063// * The existence of zero-width bitfield that occurs after anything other than
Warren Hunt8f8bad72013-10-11 20:19:00 +00002064// a non-zero length bitfield is ignored.
Warren Hunt917f97f2014-04-11 00:54:15 +00002065// * There is no explicit primary base for the purposes of layout. All bases
2066// with vfptrs are laid out first, followed by all bases without vfptrs.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002067// * The Itanium equivalent vtable pointers are split into a vfptr (virtual
2068// function pointer) and a vbptr (virtual base pointer). They can each be
Warren Hunt55d8e822013-10-23 23:53:07 +00002069// shared with a, non-virtual bases. These bases need not be the same. vfptrs
Warren Hunt917f97f2014-04-11 00:54:15 +00002070// always occur at offset 0. vbptrs can occur at an arbitrary offset and are
2071// placed after the lexiographically last non-virtual base. This placement
2072// is always before fields but can be in the middle of the non-virtual bases
2073// due to the two-pass layout scheme for non-virtual-bases.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002074// * Virtual bases sometimes require a 'vtordisp' field that is laid out before
2075// the virtual base and is used in conjunction with virtual overrides during
Warren Hunt917f97f2014-04-11 00:54:15 +00002076// construction and destruction. This is always a 4 byte value and is used as
2077// an alternative to constructor vtables.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002078// * vtordisps are allocated in a block of memory with size and alignment equal
2079// to the alignment of the completed structure (before applying __declspec(
Warren Hunt55d8e822013-10-23 23:53:07 +00002080// align())). The vtordisp always occur at the end of the allocation block,
2081// immediately prior to the virtual base.
Warren Hunt917f97f2014-04-11 00:54:15 +00002082// * vfptrs are injected after all bases and fields have been laid out. In
2083// order to guarantee proper alignment of all fields, the vfptr injection
2084// pushes all bases and fields back by the alignment imposed by those bases
2085// and fields. This can potentially add a significant amount of padding.
2086// vfptrs are always injected at offset 0.
2087// * vbptrs are injected after all bases and fields have been laid out. In
2088// order to guarantee proper alignment of all fields, the vfptr injection
2089// pushes all bases and fields back by the alignment imposed by those bases
2090// and fields. This can potentially add a significant amount of padding.
2091// vbptrs are injected immediately after the last non-virtual base as
2092// lexiographically ordered in the code. If this site isn't pointer aligned
2093// the vbptr is placed at the next properly aligned location. Enough padding
2094// is added to guarantee a fit.
2095// * The last zero sized non-virtual base can be placed at the end of the
2096// struct (potentially aliasing another object), or may alias with the first
2097// field, even if they are of the same type.
2098// * The last zero size virtual base may be placed at the end of the struct
2099// potentially aliasing another object.
Warren Hunt049f6732013-12-06 19:54:25 +00002100// * The ABI attempts to avoid aliasing of zero sized bases by adding padding
2101// between bases or vbases with specific properties. The criteria for
2102// additional padding between two bases is that the first base is zero sized
Warren Hunt39a907b2014-04-09 21:57:24 +00002103// or ends with a zero sized subobject and the second base is zero sized or
Warren Hunt917f97f2014-04-11 00:54:15 +00002104// trails with a zero sized base or field (sharing of vfptrs can reorder the
2105// layout of the so the leading base is not always the first one declared).
2106// This rule does take into account fields that are not records, so padding
2107// will occur even if the last field is, e.g. an int. The padding added for
2108// bases is 1 byte. The padding added between vbases depends on the alignment
2109// of the object but is at least 4 bytes (in both 32 and 64 bit modes).
2110// * There is no concept of non-virtual alignment, non-virtual alignment and
2111// alignment are always identical.
2112// * There is a distinction between alignment and required alignment.
2113// __declspec(align) changes the required alignment of a struct. This
2114// alignment is _always_ obeyed, even in the presence of #pragma pack. A
Justin Bogner2ca9a4a2014-10-08 05:45:39 +00002115// record inherits required alignment from all of its fields and bases.
Warren Huntf4518def2014-01-10 01:28:05 +00002116// * __declspec(align) on bitfields has the effect of changing the bitfield's
Warren Hunt917f97f2014-04-11 00:54:15 +00002117// alignment instead of its required alignment. This is the only known way
2118// to make the alignment of a struct bigger than 8. Interestingly enough
2119// this alignment is also immune to the effects of #pragma pack and can be
2120// used to create structures with large alignment under #pragma pack.
2121// However, because it does not impact required alignment, such a structure,
2122// when used as a field or base, will not be aligned if #pragma pack is
2123// still active at the time of use.
2124//
Alp Toker08f6e9e2014-05-05 19:53:42 +00002125// Known incompatibilities:
Warren Hunt917f97f2014-04-11 00:54:15 +00002126// * all: #pragma pack between fields in a record
2127// * 2010 and back: If the last field in a record is a bitfield, every object
2128// laid out after the record will have extra padding inserted before it. The
2129// extra padding will have size equal to the size of the storage class of the
2130// bitfield. 0 sized bitfields don't exhibit this behavior and the extra
2131// padding can be avoided by adding a 0 sized bitfield after the non-zero-
2132// sized bitfield.
2133// * 2012 and back: In 64-bit mode, if the alignment of a record is 16 or
2134// greater due to __declspec(align()) then a second layout phase occurs after
2135// The locations of the vf and vb pointers are known. This layout phase
2136// suffers from the "last field is a bitfield" bug in 2010 and results in
2137// _every_ field getting padding put in front of it, potentially including the
2138// vfptr, leaving the vfprt at a non-zero location which results in a fault if
2139// anything tries to read the vftbl. The second layout phase also treats
Alp Toker08f6e9e2014-05-05 19:53:42 +00002140// bitfields as separate entities and gives them each storage rather than
Warren Hunt917f97f2014-04-11 00:54:15 +00002141// packing them. Additionally, because this phase appears to perform a
2142// (an unstable) sort on the members before laying them out and because merged
2143// bitfields have the same address, the bitfields end up in whatever order
2144// the sort left them in, a behavior we could never hope to replicate.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002145
2146namespace {
2147struct MicrosoftRecordLayoutBuilder {
Warren Huntd640d7d2014-01-09 00:30:56 +00002148 struct ElementInfo {
2149 CharUnits Size;
2150 CharUnits Alignment;
2151 };
Warren Hunt8f8bad72013-10-11 20:19:00 +00002152 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
2153 MicrosoftRecordLayoutBuilder(const ASTContext &Context) : Context(Context) {}
2154private:
Aaron Ballmanabc18922015-02-15 22:54:08 +00002155 MicrosoftRecordLayoutBuilder(const MicrosoftRecordLayoutBuilder &) = delete;
2156 void operator=(const MicrosoftRecordLayoutBuilder &) = delete;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002157public:
Warren Hunt8f8bad72013-10-11 20:19:00 +00002158 void layout(const RecordDecl *RD);
2159 void cxxLayout(const CXXRecordDecl *RD);
2160 /// \brief Initializes size and alignment and honors some flags.
2161 void initializeLayout(const RecordDecl *RD);
2162 /// \brief Initialized C++ layout, compute alignment and virtual alignment and
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002163 /// existence of vfptrs and vbptrs. Alignment is needed before the vfptr is
Warren Hunt8f8bad72013-10-11 20:19:00 +00002164 /// laid out.
2165 void initializeCXXLayout(const CXXRecordDecl *RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002166 void layoutNonVirtualBases(const CXXRecordDecl *RD);
Warren Huntd640d7d2014-01-09 00:30:56 +00002167 void layoutNonVirtualBase(const CXXRecordDecl *BaseDecl,
2168 const ASTRecordLayout &BaseLayout,
2169 const ASTRecordLayout *&PreviousBaseLayout);
2170 void injectVFPtr(const CXXRecordDecl *RD);
2171 void injectVBPtr(const CXXRecordDecl *RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002172 /// \brief Lays out the fields of the record. Also rounds size up to
2173 /// alignment.
2174 void layoutFields(const RecordDecl *RD);
2175 void layoutField(const FieldDecl *FD);
2176 void layoutBitField(const FieldDecl *FD);
2177 /// \brief Lays out a single zero-width bit-field in the record and handles
2178 /// special cases associated with zero-width bit-fields.
2179 void layoutZeroWidthBitField(const FieldDecl *FD);
2180 void layoutVirtualBases(const CXXRecordDecl *RD);
Warren Hunt1603e522013-12-10 01:44:39 +00002181 void finalizeLayout(const RecordDecl *RD);
Warren Huntd640d7d2014-01-09 00:30:56 +00002182 /// \brief Gets the size and alignment of a base taking pragma pack and
2183 /// __declspec(align) into account.
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002184 ElementInfo getAdjustedElementInfo(const ASTRecordLayout &Layout);
Warren Huntd640d7d2014-01-09 00:30:56 +00002185 /// \brief Gets the size and alignment of a field taking pragma pack and
2186 /// __declspec(align) into account. It also updates RequiredAlignment as a
2187 /// side effect because it is most convenient to do so here.
2188 ElementInfo getAdjustedElementInfo(const FieldDecl *FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002189 /// \brief Places a field at an offset in CharUnits.
2190 void placeFieldAtOffset(CharUnits FieldOffset) {
2191 FieldOffsets.push_back(Context.toBits(FieldOffset));
2192 }
2193 /// \brief Places a bitfield at a bit offset.
2194 void placeFieldAtBitOffset(uint64_t FieldOffset) {
2195 FieldOffsets.push_back(FieldOffset);
2196 }
2197 /// \brief Compute the set of virtual bases for which vtordisps are required.
David Majnemerc2e67532014-09-23 22:58:15 +00002198 void computeVtorDispSet(
2199 llvm::SmallPtrSetImpl<const CXXRecordDecl *> &HasVtorDispSet,
2200 const CXXRecordDecl *RD) const;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002201 const ASTContext &Context;
2202 /// \brief The size of the record being laid out.
2203 CharUnits Size;
Warren Huntf6ec7482014-02-21 01:40:35 +00002204 /// \brief The non-virtual size of the record layout.
2205 CharUnits NonVirtualSize;
2206 /// \brief The data size of the record layout.
Warren Huntd640d7d2014-01-09 00:30:56 +00002207 CharUnits DataSize;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002208 /// \brief The current alignment of the record layout.
2209 CharUnits Alignment;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002210 /// \brief The maximum allowed field alignment. This is set by #pragma pack.
2211 CharUnits MaxFieldAlignment;
Warren Hunt7b252d22013-12-06 00:01:17 +00002212 /// \brief The alignment that this record must obey. This is imposed by
2213 /// __declspec(align()) on the record itself or one of its fields or bases.
2214 CharUnits RequiredAlignment;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002215 /// \brief The size of the allocation of the currently active bitfield.
2216 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield
2217 /// is true.
2218 CharUnits CurrentBitfieldSize;
Warren Huntd640d7d2014-01-09 00:30:56 +00002219 /// \brief Offset to the virtual base table pointer (if one exists).
2220 CharUnits VBPtrOffset;
David Majnemer00a061d2014-09-30 06:45:43 +00002221 /// \brief Minimum record size possible.
2222 CharUnits MinEmptyStructSize;
Warren Huntd640d7d2014-01-09 00:30:56 +00002223 /// \brief The size and alignment info of a pointer.
2224 ElementInfo PointerInfo;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002225 /// \brief The primary base class (if one exists).
2226 const CXXRecordDecl *PrimaryBase;
2227 /// \brief The class we share our vb-pointer with.
2228 const CXXRecordDecl *SharedVBPtrBase;
Warren Huntd640d7d2014-01-09 00:30:56 +00002229 /// \brief The collection of field offsets.
2230 SmallVector<uint64_t, 16> FieldOffsets;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002231 /// \brief Base classes and their offsets in the record.
2232 BaseOffsetsMapTy Bases;
2233 /// \brief virtual base classes and their offsets in the record.
2234 ASTRecordLayout::VBaseOffsetsMapTy VBases;
Warren Huntd640d7d2014-01-09 00:30:56 +00002235 /// \brief The number of remaining bits in our last bitfield allocation.
2236 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield is
2237 /// true.
2238 unsigned RemainingBitsInField;
2239 bool IsUnion : 1;
2240 /// \brief True if the last field laid out was a bitfield and was not 0
2241 /// width.
2242 bool LastFieldIsNonZeroWidthBitfield : 1;
2243 /// \brief True if the class has its own vftable pointer.
2244 bool HasOwnVFPtr : 1;
2245 /// \brief True if the class has a vbtable pointer.
2246 bool HasVBPtr : 1;
Warren Hunt39a907b2014-04-09 21:57:24 +00002247 /// \brief True if the last sub-object within the type is zero sized or the
2248 /// object itself is zero sized. This *does not* count members that are not
2249 /// records. Only used for MS-ABI.
2250 bool EndsWithZeroSizedObject : 1;
Warren Hunt049f6732013-12-06 19:54:25 +00002251 /// \brief True if this class is zero sized or first base is zero sized or
2252 /// has this property. Only used for MS-ABI.
2253 bool LeadsWithZeroSizedBase : 1;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002254};
2255} // namespace
2256
Warren Huntd640d7d2014-01-09 00:30:56 +00002257MicrosoftRecordLayoutBuilder::ElementInfo
2258MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002259 const ASTRecordLayout &Layout) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002260 ElementInfo Info;
2261 Info.Alignment = Layout.getAlignment();
2262 // Respect pragma pack.
Warren Hunt7b252d22013-12-06 00:01:17 +00002263 if (!MaxFieldAlignment.isZero())
Warren Huntd640d7d2014-01-09 00:30:56 +00002264 Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
2265 // Track zero-sized subobjects here where it's already available.
Warren Hunt39a907b2014-04-09 21:57:24 +00002266 EndsWithZeroSizedObject = Layout.hasZeroSizedSubObject();
Warren Huntd640d7d2014-01-09 00:30:56 +00002267 // Respect required alignment, this is necessary because we may have adjusted
Warren Hunt94258912014-01-11 01:16:40 +00002268 // the alignment in the case of pragam pack. Note that the required alignment
2269 // doesn't actually apply to the struct alignment at this point.
2270 Alignment = std::max(Alignment, Info.Alignment);
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002271 RequiredAlignment = std::max(RequiredAlignment, Layout.getRequiredAlignment());
Warren Huntd640d7d2014-01-09 00:30:56 +00002272 Info.Alignment = std::max(Info.Alignment, Layout.getRequiredAlignment());
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002273 Info.Size = Layout.getNonVirtualSize();
Warren Huntd640d7d2014-01-09 00:30:56 +00002274 return Info;
Warren Hunt7b252d22013-12-06 00:01:17 +00002275}
2276
Warren Huntd640d7d2014-01-09 00:30:56 +00002277MicrosoftRecordLayoutBuilder::ElementInfo
2278MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
2279 const FieldDecl *FD) {
David Majnemer34b57492014-07-30 01:30:47 +00002280 // Get the alignment of the field type's natural alignment, ignore any
2281 // alignment attributes.
Warren Huntd640d7d2014-01-09 00:30:56 +00002282 ElementInfo Info;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002283 std::tie(Info.Size, Info.Alignment) =
David Majnemer34b57492014-07-30 01:30:47 +00002284 Context.getTypeInfoInChars(FD->getType()->getUnqualifiedDesugaredType());
2285 // Respect align attributes on the field.
2286 CharUnits FieldRequiredAlignment =
Warren Huntf4518def2014-01-10 01:28:05 +00002287 Context.toCharUnitsFromBits(FD->getMaxAlignment());
David Majnemer34b57492014-07-30 01:30:47 +00002288 // Respect align attributes on the type.
2289 if (Context.isAlignmentRequired(FD->getType()))
2290 FieldRequiredAlignment = std::max(
2291 Context.getTypeAlignInChars(FD->getType()), FieldRequiredAlignment);
Warren Hunt049f6732013-12-06 19:54:25 +00002292 // Respect attributes applied to subobjects of the field.
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002293 if (FD->isBitField())
2294 // For some reason __declspec align impacts alignment rather than required
2295 // alignment when it is applied to bitfields.
Warren Huntf4518def2014-01-10 01:28:05 +00002296 Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002297 else {
2298 if (auto RT =
2299 FD->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
2300 auto const &Layout = Context.getASTRecordLayout(RT->getDecl());
2301 EndsWithZeroSizedObject = Layout.hasZeroSizedSubObject();
2302 FieldRequiredAlignment = std::max(FieldRequiredAlignment,
2303 Layout.getRequiredAlignment());
2304 }
Warren Huntf4518def2014-01-10 01:28:05 +00002305 // Capture required alignment as a side-effect.
2306 RequiredAlignment = std::max(RequiredAlignment, FieldRequiredAlignment);
2307 }
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002308 // Respect pragma pack, attribute pack and declspec align
2309 if (!MaxFieldAlignment.isZero())
2310 Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
2311 if (FD->hasAttr<PackedAttr>())
2312 Info.Alignment = CharUnits::One();
2313 Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002314 return Info;
2315}
2316
2317void MicrosoftRecordLayoutBuilder::layout(const RecordDecl *RD) {
David Majnemer00a061d2014-09-30 06:45:43 +00002318 // For C record layout, zero-sized records always have size 4.
2319 MinEmptyStructSize = CharUnits::fromQuantity(4);
Warren Huntd640d7d2014-01-09 00:30:56 +00002320 initializeLayout(RD);
2321 layoutFields(RD);
2322 DataSize = Size = Size.RoundUpToAlignment(Alignment);
David Majnemer79a1c892014-02-12 00:43:02 +00002323 RequiredAlignment = std::max(
2324 RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
Warren Huntd640d7d2014-01-09 00:30:56 +00002325 finalizeLayout(RD);
2326}
2327
2328void MicrosoftRecordLayoutBuilder::cxxLayout(const CXXRecordDecl *RD) {
David Majnemer00a061d2014-09-30 06:45:43 +00002329 // The C++ standard says that empty structs have size 1.
2330 MinEmptyStructSize = CharUnits::One();
Warren Huntd640d7d2014-01-09 00:30:56 +00002331 initializeLayout(RD);
2332 initializeCXXLayout(RD);
2333 layoutNonVirtualBases(RD);
2334 layoutFields(RD);
Warren Huntc89450e2014-03-24 21:37:27 +00002335 injectVBPtr(RD);
2336 injectVFPtr(RD);
2337 if (HasOwnVFPtr || (HasVBPtr && !SharedVBPtrBase))
2338 Alignment = std::max(Alignment, PointerInfo.Alignment);
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002339 auto RoundingAlignment = Alignment;
2340 if (!MaxFieldAlignment.isZero())
2341 RoundingAlignment = std::min(RoundingAlignment, MaxFieldAlignment);
2342 NonVirtualSize = Size = Size.RoundUpToAlignment(RoundingAlignment);
David Majnemer79a1c892014-02-12 00:43:02 +00002343 RequiredAlignment = std::max(
2344 RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
Warren Huntd640d7d2014-01-09 00:30:56 +00002345 layoutVirtualBases(RD);
2346 finalizeLayout(RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002347}
2348
2349void MicrosoftRecordLayoutBuilder::initializeLayout(const RecordDecl *RD) {
2350 IsUnion = RD->isUnion();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002351 Size = CharUnits::Zero();
2352 Alignment = CharUnits::One();
Warren Hunt7b252d22013-12-06 00:01:17 +00002353 // In 64-bit mode we always perform an alignment step after laying out vbases.
2354 // In 32-bit mode we do not. The check to see if we need to perform alignment
2355 // checks the RequiredAlignment field and performs alignment if it isn't 0.
Warren Huntbb9c3c32014-04-10 23:23:34 +00002356 RequiredAlignment = Context.getTargetInfo().getPointerWidth(0) == 64 ?
2357 CharUnits::One() : CharUnits::Zero();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002358 // Compute the maximum field alignment.
2359 MaxFieldAlignment = CharUnits::Zero();
2360 // Honor the default struct packing maximum alignment flag.
2361 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct)
Warren Huntf4518def2014-01-10 01:28:05 +00002362 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
2363 // Honor the packing attribute. The MS-ABI ignores pragma pack if its larger
2364 // than the pointer size.
2365 if (const MaxFieldAlignmentAttr *MFAA = RD->getAttr<MaxFieldAlignmentAttr>()){
2366 unsigned PackedAlignment = MFAA->getAlignment();
2367 if (PackedAlignment <= Context.getTargetInfo().getPointerWidth(0))
2368 MaxFieldAlignment = Context.toCharUnitsFromBits(PackedAlignment);
2369 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002370 // Packed attribute forces max field alignment to be 1.
2371 if (RD->hasAttr<PackedAttr>())
2372 MaxFieldAlignment = CharUnits::One();
2373}
2374
Warren Hunt8f8bad72013-10-11 20:19:00 +00002375void
2376MicrosoftRecordLayoutBuilder::initializeCXXLayout(const CXXRecordDecl *RD) {
Warren Hunt39a907b2014-04-09 21:57:24 +00002377 EndsWithZeroSizedObject = false;
Warren Hunt049f6732013-12-06 19:54:25 +00002378 LeadsWithZeroSizedBase = false;
Warren Huntd640d7d2014-01-09 00:30:56 +00002379 HasOwnVFPtr = false;
2380 HasVBPtr = false;
Craig Topper36250ad2014-05-12 05:36:57 +00002381 PrimaryBase = nullptr;
2382 SharedVBPtrBase = nullptr;
Warren Huntd640d7d2014-01-09 00:30:56 +00002383 // Calculate pointer size and alignment. These are used for vfptr and vbprt
2384 // injection.
2385 PointerInfo.Size =
2386 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
2387 PointerInfo.Alignment = PointerInfo.Size;
2388 // Respect pragma pack.
2389 if (!MaxFieldAlignment.isZero())
2390 PointerInfo.Alignment = std::min(PointerInfo.Alignment, MaxFieldAlignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002391}
2392
2393void
2394MicrosoftRecordLayoutBuilder::layoutNonVirtualBases(const CXXRecordDecl *RD) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002395 // The MS-ABI lays out all bases that contain leading vfptrs before it lays
2396 // out any bases that do not contain vfptrs. We implement this as two passes
2397 // over the bases. This approach guarantees that the primary base is laid out
2398 // first. We use these passes to calculate some additional aggregated
2399 // information about the bases, such as reqruied alignment and the presence of
2400 // zero sized members.
Craig Topper36250ad2014-05-12 05:36:57 +00002401 const ASTRecordLayout *PreviousBaseLayout = nullptr;
Warren Huntd640d7d2014-01-09 00:30:56 +00002402 // Iterate through the bases and lay out the non-virtual ones.
David Majnemerc964b4b2014-07-16 06:04:00 +00002403 for (const CXXBaseSpecifier &Base : RD->bases()) {
2404 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002405 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
Warren Huntd640d7d2014-01-09 00:30:56 +00002406 // Mark and skip virtual bases.
David Majnemerc964b4b2014-07-16 06:04:00 +00002407 if (Base.isVirtual()) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002408 HasVBPtr = true;
2409 continue;
2410 }
2411 // Check fo a base to share a VBPtr with.
2412 if (!SharedVBPtrBase && BaseLayout.hasVBPtr()) {
2413 SharedVBPtrBase = BaseDecl;
2414 HasVBPtr = true;
2415 }
2416 // Only lay out bases with extendable VFPtrs on the first pass.
2417 if (!BaseLayout.hasExtendableVFPtr())
2418 continue;
2419 // If we don't have a primary base, this one qualifies.
Warren Huntbadf9e02014-01-13 19:55:52 +00002420 if (!PrimaryBase) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002421 PrimaryBase = BaseDecl;
Warren Huntbadf9e02014-01-13 19:55:52 +00002422 LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
2423 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002424 // Lay out the base.
2425 layoutNonVirtualBase(BaseDecl, BaseLayout, PreviousBaseLayout);
2426 }
2427 // Figure out if we need a fresh VFPtr for this class.
2428 if (!PrimaryBase && RD->isDynamicClass())
2429 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2430 e = RD->method_end();
2431 !HasOwnVFPtr && i != e; ++i)
2432 HasOwnVFPtr = i->isVirtual() && i->size_overridden_methods() == 0;
2433 // If we don't have a primary base then we have a leading object that could
2434 // itself lead with a zero-sized object, something we track.
2435 bool CheckLeadingLayout = !PrimaryBase;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002436 // Iterate through the bases and lay out the non-virtual ones.
David Majnemerc964b4b2014-07-16 06:04:00 +00002437 for (const CXXBaseSpecifier &Base : RD->bases()) {
2438 if (Base.isVirtual())
Warren Hunt8f8bad72013-10-11 20:19:00 +00002439 continue;
David Majnemerc964b4b2014-07-16 06:04:00 +00002440 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002441 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2442 // Only lay out bases without extendable VFPtrs on the second pass.
Warren Huntbb9c3c32014-04-10 23:23:34 +00002443 if (BaseLayout.hasExtendableVFPtr()) {
2444 VBPtrOffset = Bases[BaseDecl] + BaseLayout.getNonVirtualSize();
Warren Hunt4431fe62013-12-12 22:33:37 +00002445 continue;
Warren Huntbb9c3c32014-04-10 23:23:34 +00002446 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002447 // If this is the first layout, check to see if it leads with a zero sized
2448 // object. If it does, so do we.
2449 if (CheckLeadingLayout) {
2450 CheckLeadingLayout = false;
2451 LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
Warren Hunt049f6732013-12-06 19:54:25 +00002452 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002453 // Lay out the base.
2454 layoutNonVirtualBase(BaseDecl, BaseLayout, PreviousBaseLayout);
Warren Huntbb9c3c32014-04-10 23:23:34 +00002455 VBPtrOffset = Bases[BaseDecl] + BaseLayout.getNonVirtualSize();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002456 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002457 // Set our VBPtroffset if we know it at this point.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002458 if (!HasVBPtr)
2459 VBPtrOffset = CharUnits::fromQuantity(-1);
Warren Hunt6eba9072014-01-14 00:31:30 +00002460 else if (SharedVBPtrBase) {
2461 const ASTRecordLayout &Layout = Context.getASTRecordLayout(SharedVBPtrBase);
2462 VBPtrOffset = Bases[SharedVBPtrBase] + Layout.getVBPtrOffset();
2463 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002464}
2465
2466void MicrosoftRecordLayoutBuilder::layoutNonVirtualBase(
2467 const CXXRecordDecl *BaseDecl,
2468 const ASTRecordLayout &BaseLayout,
2469 const ASTRecordLayout *&PreviousBaseLayout) {
Warren Huntf4518def2014-01-10 01:28:05 +00002470 // Insert padding between two bases if the left first one is zero sized or
2471 // contains a zero sized subobject and the right is zero sized or one leads
2472 // with a zero sized base.
2473 if (PreviousBaseLayout && PreviousBaseLayout->hasZeroSizedSubObject() &&
2474 BaseLayout.leadsWithZeroSizedBase())
2475 Size++;
2476 ElementInfo Info = getAdjustedElementInfo(BaseLayout);
2477 CharUnits BaseOffset = Size.RoundUpToAlignment(Info.Alignment);
2478 Bases.insert(std::make_pair(BaseDecl, BaseOffset));
Warren Huntf6ec7482014-02-21 01:40:35 +00002479 Size = BaseOffset + BaseLayout.getNonVirtualSize();
Warren Huntf4518def2014-01-10 01:28:05 +00002480 PreviousBaseLayout = &BaseLayout;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002481}
2482
2483void MicrosoftRecordLayoutBuilder::layoutFields(const RecordDecl *RD) {
2484 LastFieldIsNonZeroWidthBitfield = false;
David Majnemerc964b4b2014-07-16 06:04:00 +00002485 for (const FieldDecl *Field : RD->fields())
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002486 layoutField(Field);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002487}
2488
2489void MicrosoftRecordLayoutBuilder::layoutField(const FieldDecl *FD) {
2490 if (FD->isBitField()) {
2491 layoutBitField(FD);
2492 return;
2493 }
2494 LastFieldIsNonZeroWidthBitfield = false;
Warren Huntd640d7d2014-01-09 00:30:56 +00002495 ElementInfo Info = getAdjustedElementInfo(FD);
David Majnemeradc45bb2014-04-13 08:15:50 +00002496 Alignment = std::max(Alignment, Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002497 if (IsUnion) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002498 placeFieldAtOffset(CharUnits::Zero());
2499 Size = std::max(Size, Info.Size);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002500 } else {
Warren Huntd640d7d2014-01-09 00:30:56 +00002501 CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002502 placeFieldAtOffset(FieldOffset);
Warren Huntd640d7d2014-01-09 00:30:56 +00002503 Size = FieldOffset + Info.Size;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002504 }
2505}
2506
2507void MicrosoftRecordLayoutBuilder::layoutBitField(const FieldDecl *FD) {
2508 unsigned Width = FD->getBitWidthValue(Context);
2509 if (Width == 0) {
2510 layoutZeroWidthBitField(FD);
2511 return;
2512 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002513 ElementInfo Info = getAdjustedElementInfo(FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002514 // Clamp the bitfield to a containable size for the sake of being able
2515 // to lay them out. Sema will throw an error.
Warren Huntd640d7d2014-01-09 00:30:56 +00002516 if (Width > Context.toBits(Info.Size))
2517 Width = Context.toBits(Info.Size);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002518 // Check to see if this bitfield fits into an existing allocation. Note:
2519 // MSVC refuses to pack bitfields of formal types with different sizes
2520 // into the same allocation.
2521 if (!IsUnion && LastFieldIsNonZeroWidthBitfield &&
Warren Huntd640d7d2014-01-09 00:30:56 +00002522 CurrentBitfieldSize == Info.Size && Width <= RemainingBitsInField) {
Warren Hunt8f8bad72013-10-11 20:19:00 +00002523 placeFieldAtBitOffset(Context.toBits(Size) - RemainingBitsInField);
2524 RemainingBitsInField -= Width;
2525 return;
2526 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002527 LastFieldIsNonZeroWidthBitfield = true;
Warren Huntd640d7d2014-01-09 00:30:56 +00002528 CurrentBitfieldSize = Info.Size;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002529 if (IsUnion) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002530 placeFieldAtOffset(CharUnits::Zero());
2531 Size = std::max(Size, Info.Size);
David Majnemeradc45bb2014-04-13 08:15:50 +00002532 // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002533 } else {
2534 // Allocate a new block of memory and place the bitfield in it.
Warren Huntd640d7d2014-01-09 00:30:56 +00002535 CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002536 placeFieldAtOffset(FieldOffset);
Warren Huntd640d7d2014-01-09 00:30:56 +00002537 Size = FieldOffset + Info.Size;
David Majnemeradc45bb2014-04-13 08:15:50 +00002538 Alignment = std::max(Alignment, Info.Alignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002539 RemainingBitsInField = Context.toBits(Info.Size) - Width;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002540 }
2541}
2542
2543void
2544MicrosoftRecordLayoutBuilder::layoutZeroWidthBitField(const FieldDecl *FD) {
2545 // Zero-width bitfields are ignored unless they follow a non-zero-width
2546 // bitfield.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002547 if (!LastFieldIsNonZeroWidthBitfield) {
2548 placeFieldAtOffset(IsUnion ? CharUnits::Zero() : Size);
2549 // TODO: Add a Sema warning that MS ignores alignment for zero
Alp Tokerd4733632013-12-05 04:47:09 +00002550 // sized bitfields that occur after zero-size bitfields or non-bitfields.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002551 return;
2552 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002553 LastFieldIsNonZeroWidthBitfield = false;
Warren Huntd640d7d2014-01-09 00:30:56 +00002554 ElementInfo Info = getAdjustedElementInfo(FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002555 if (IsUnion) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002556 placeFieldAtOffset(CharUnits::Zero());
2557 Size = std::max(Size, Info.Size);
David Majnemeradc45bb2014-04-13 08:15:50 +00002558 // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002559 } else {
2560 // Round up the current record size to the field's alignment boundary.
Warren Huntd640d7d2014-01-09 00:30:56 +00002561 CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002562 placeFieldAtOffset(FieldOffset);
2563 Size = FieldOffset;
David Majnemeradc45bb2014-04-13 08:15:50 +00002564 Alignment = std::max(Alignment, Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002565 }
2566}
2567
Warren Huntd640d7d2014-01-09 00:30:56 +00002568void MicrosoftRecordLayoutBuilder::injectVBPtr(const CXXRecordDecl *RD) {
Warren Hunt6eba9072014-01-14 00:31:30 +00002569 if (!HasVBPtr || SharedVBPtrBase)
Warren Huntd640d7d2014-01-09 00:30:56 +00002570 return;
Warren Huntd640d7d2014-01-09 00:30:56 +00002571 // Inject the VBPointer at the injection site.
2572 CharUnits InjectionSite = VBPtrOffset;
2573 // But before we do, make sure it's properly aligned.
2574 VBPtrOffset = VBPtrOffset.RoundUpToAlignment(PointerInfo.Alignment);
2575 // Determine where the first field should be laid out after the vbptr.
2576 CharUnits FieldStart = VBPtrOffset + PointerInfo.Size;
2577 // Make sure that the amount we push the fields back by is a multiple of the
2578 // alignment.
David Majnemer79a1c892014-02-12 00:43:02 +00002579 CharUnits Offset = (FieldStart - InjectionSite).RoundUpToAlignment(
2580 std::max(RequiredAlignment, Alignment));
Warren Huntd640d7d2014-01-09 00:30:56 +00002581 // Increase the size of the object and push back all fields by the offset
2582 // amount.
2583 Size += Offset;
David Majnemerc964b4b2014-07-16 06:04:00 +00002584 for (uint64_t &FieldOffset : FieldOffsets)
2585 FieldOffset += Context.toBits(Offset);
2586 for (BaseOffsetsMapTy::value_type &Base : Bases)
2587 if (Base.second >= InjectionSite)
2588 Base.second += Offset;
Warren Huntd640d7d2014-01-09 00:30:56 +00002589}
2590
2591void MicrosoftRecordLayoutBuilder::injectVFPtr(const CXXRecordDecl *RD) {
2592 if (!HasOwnVFPtr)
2593 return;
2594 // Make sure that the amount we push the struct back by is a multiple of the
2595 // alignment.
David Majnemer79a1c892014-02-12 00:43:02 +00002596 CharUnits Offset = PointerInfo.Size.RoundUpToAlignment(
2597 std::max(RequiredAlignment, Alignment));
Warren Huntd640d7d2014-01-09 00:30:56 +00002598 // Increase the size of the object and push back all fields, the vbptr and all
2599 // bases by the offset amount.
2600 Size += Offset;
David Majnemerc964b4b2014-07-16 06:04:00 +00002601 for (uint64_t &FieldOffset : FieldOffsets)
2602 FieldOffset += Context.toBits(Offset);
Warren Huntd640d7d2014-01-09 00:30:56 +00002603 if (HasVBPtr)
2604 VBPtrOffset += Offset;
David Majnemerc964b4b2014-07-16 06:04:00 +00002605 for (BaseOffsetsMapTy::value_type &Base : Bases)
2606 Base.second += Offset;
Warren Huntd640d7d2014-01-09 00:30:56 +00002607}
2608
Warren Hunt8f8bad72013-10-11 20:19:00 +00002609void MicrosoftRecordLayoutBuilder::layoutVirtualBases(const CXXRecordDecl *RD) {
2610 if (!HasVBPtr)
2611 return;
Warren Huntd640d7d2014-01-09 00:30:56 +00002612 // Vtordisps are always 4 bytes (even in 64-bit mode)
2613 CharUnits VtorDispSize = CharUnits::fromQuantity(4);
2614 CharUnits VtorDispAlignment = VtorDispSize;
2615 // vtordisps respect pragma pack.
2616 if (!MaxFieldAlignment.isZero())
2617 VtorDispAlignment = std::min(VtorDispAlignment, MaxFieldAlignment);
2618 // The alignment of the vtordisp is at least the required alignment of the
2619 // entire record. This requirement may be present to support vtordisp
2620 // injection.
David Majnemerc964b4b2014-07-16 06:04:00 +00002621 for (const CXXBaseSpecifier &VBase : RD->vbases()) {
2622 const CXXRecordDecl *BaseDecl = VBase.getType()->getAsCXXRecordDecl();
David Majnemer79a1c892014-02-12 00:43:02 +00002623 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2624 RequiredAlignment =
2625 std::max(RequiredAlignment, BaseLayout.getRequiredAlignment());
2626 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002627 VtorDispAlignment = std::max(VtorDispAlignment, RequiredAlignment);
2628 // Compute the vtordisp set.
David Majnemerc2e67532014-09-23 22:58:15 +00002629 llvm::SmallPtrSet<const CXXRecordDecl *, 2> HasVtorDispSet;
2630 computeVtorDispSet(HasVtorDispSet, RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002631 // Iterate through the virtual bases and lay them out.
Craig Topper36250ad2014-05-12 05:36:57 +00002632 const ASTRecordLayout *PreviousBaseLayout = nullptr;
David Majnemerc964b4b2014-07-16 06:04:00 +00002633 for (const CXXBaseSpecifier &VBase : RD->vbases()) {
2634 const CXXRecordDecl *BaseDecl = VBase.getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002635 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
David Majnemerc2e67532014-09-23 22:58:15 +00002636 bool HasVtordisp = HasVtorDispSet.count(BaseDecl) > 0;
Warren Huntd640d7d2014-01-09 00:30:56 +00002637 // Insert padding between two bases if the left first one is zero sized or
2638 // contains a zero sized subobject and the right is zero sized or one leads
2639 // with a zero sized base. The padding between virtual bases is 4
2640 // bytes (in both 32 and 64 bits modes) and always involves rounding up to
2641 // the required alignment, we don't know why.
Warren Hunt4f7efb72014-04-12 00:20:50 +00002642 if ((PreviousBaseLayout && PreviousBaseLayout->hasZeroSizedSubObject() &&
David Majnemerbf3d4302014-07-16 07:16:58 +00002643 BaseLayout.leadsWithZeroSizedBase()) || HasVtordisp) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002644 Size = Size.RoundUpToAlignment(VtorDispAlignment) + VtorDispSize;
David Majnemera2464682014-07-17 00:55:19 +00002645 Alignment = std::max(VtorDispAlignment, Alignment);
David Majnemerbf3d4302014-07-16 07:16:58 +00002646 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002647 // Insert the virtual base.
2648 ElementInfo Info = getAdjustedElementInfo(BaseLayout);
Warren Huntf4518def2014-01-10 01:28:05 +00002649 CharUnits BaseOffset = Size.RoundUpToAlignment(Info.Alignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002650 VBases.insert(std::make_pair(BaseDecl,
2651 ASTRecordLayout::VBaseInfo(BaseOffset, HasVtordisp)));
Warren Huntf6ec7482014-02-21 01:40:35 +00002652 Size = BaseOffset + BaseLayout.getNonVirtualSize();
Warren Huntd640d7d2014-01-09 00:30:56 +00002653 PreviousBaseLayout = &BaseLayout;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002654 }
2655}
2656
Warren Huntc3384312013-12-11 22:28:32 +00002657void MicrosoftRecordLayoutBuilder::finalizeLayout(const RecordDecl *RD) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002658 // Respect required alignment. Note that in 32-bit mode Required alignment
David Majnemer00a061d2014-09-30 06:45:43 +00002659 // may be 0 and cause size not to be updated.
Warren Huntf6ec7482014-02-21 01:40:35 +00002660 DataSize = Size;
Warren Huntd640d7d2014-01-09 00:30:56 +00002661 if (!RequiredAlignment.isZero()) {
2662 Alignment = std::max(Alignment, RequiredAlignment);
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002663 auto RoundingAlignment = Alignment;
2664 if (!MaxFieldAlignment.isZero())
2665 RoundingAlignment = std::min(RoundingAlignment, MaxFieldAlignment);
2666 RoundingAlignment = std::max(RoundingAlignment, RequiredAlignment);
2667 Size = Size.RoundUpToAlignment(RoundingAlignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002668 }
Warren Hunt049f6732013-12-06 19:54:25 +00002669 if (Size.isZero()) {
Warren Hunt39a907b2014-04-09 21:57:24 +00002670 EndsWithZeroSizedObject = true;
Warren Hunt049f6732013-12-06 19:54:25 +00002671 LeadsWithZeroSizedBase = true;
David Majnemer00a061d2014-09-30 06:45:43 +00002672 // Zero-sized structures have size equal to their alignment if a
2673 // __declspec(align) came into play.
2674 if (RequiredAlignment >= MinEmptyStructSize)
2675 Size = Alignment;
2676 else
2677 Size = MinEmptyStructSize;
Warren Hunt049f6732013-12-06 19:54:25 +00002678 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002679}
2680
Warren Hunt73f43982014-04-11 22:05:28 +00002681// Recursively walks the non-virtual bases of a class and determines if any of
2682// them are in the bases with overridden methods set.
David Majnemer12727642014-07-16 06:30:31 +00002683static bool
2684RequiresVtordisp(const llvm::SmallPtrSetImpl<const CXXRecordDecl *> &
2685 BasesWithOverriddenMethods,
2686 const CXXRecordDecl *RD) {
Warren Hunt73f43982014-04-11 22:05:28 +00002687 if (BasesWithOverriddenMethods.count(RD))
Warren Hunt8f8bad72013-10-11 20:19:00 +00002688 return true;
2689 // If any of a virtual bases non-virtual bases (recursively) requires a
2690 // vtordisp than so does this virtual base.
David Majnemerc964b4b2014-07-16 06:04:00 +00002691 for (const CXXBaseSpecifier &Base : RD->bases())
2692 if (!Base.isVirtual() &&
Warren Hunt73f43982014-04-11 22:05:28 +00002693 RequiresVtordisp(BasesWithOverriddenMethods,
David Majnemerc964b4b2014-07-16 06:04:00 +00002694 Base.getType()->getAsCXXRecordDecl()))
Warren Hunt8f8bad72013-10-11 20:19:00 +00002695 return true;
2696 return false;
2697}
2698
David Majnemerc2e67532014-09-23 22:58:15 +00002699void MicrosoftRecordLayoutBuilder::computeVtorDispSet(
2700 llvm::SmallPtrSetImpl<const CXXRecordDecl *> &HasVtordispSet,
2701 const CXXRecordDecl *RD) const {
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00002702 // /vd2 or #pragma vtordisp(2): Always use vtordisps for virtual bases with
2703 // vftables.
2704 if (RD->getMSVtorDispMode() == MSVtorDispAttr::ForVFTable) {
David Majnemerc964b4b2014-07-16 06:04:00 +00002705 for (const CXXBaseSpecifier &Base : RD->vbases()) {
2706 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00002707 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
2708 if (Layout.hasExtendableVFPtr())
2709 HasVtordispSet.insert(BaseDecl);
2710 }
David Majnemerc2e67532014-09-23 22:58:15 +00002711 return;
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00002712 }
2713
Warren Hunt8f8bad72013-10-11 20:19:00 +00002714 // If any of our bases need a vtordisp for this type, so do we. Check our
2715 // direct bases for vtordisp requirements.
David Majnemerc964b4b2014-07-16 06:04:00 +00002716 for (const CXXBaseSpecifier &Base : RD->bases()) {
2717 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002718 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
Reid Klecknercd612ab2014-04-11 16:57:42 +00002719 for (const auto &bi : Layout.getVBaseOffsetsMap())
2720 if (bi.second.hasVtorDisp())
2721 HasVtordispSet.insert(bi.first);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002722 }
David Majnemerd43388c2014-04-13 02:27:32 +00002723 // We don't introduce any additional vtordisps if either:
2724 // * A user declared constructor or destructor aren't declared.
2725 // * #pragma vtordisp(0) or the /vd0 flag are in use.
2726 if ((!RD->hasUserDeclaredConstructor() && !RD->hasUserDeclaredDestructor()) ||
2727 RD->getMSVtorDispMode() == MSVtorDispAttr::Never)
David Majnemerc2e67532014-09-23 22:58:15 +00002728 return;
David Majnemerd43388c2014-04-13 02:27:32 +00002729 // /vd1 or #pragma vtordisp(1): Try to guess based on whether we think it's
2730 // possible for a partially constructed object with virtual base overrides to
2731 // escape a non-trivial constructor.
2732 assert(RD->getMSVtorDispMode() == MSVtorDispAttr::ForVBaseOverride);
Warren Hunt73f43982014-04-11 22:05:28 +00002733 // Compute a set of base classes which define methods we override. A virtual
2734 // base in this set will require a vtordisp. A virtual base that transitively
2735 // contains one of these bases as a non-virtual base will also require a
2736 // vtordisp.
2737 llvm::SmallPtrSet<const CXXMethodDecl *, 8> Work;
2738 llvm::SmallPtrSet<const CXXRecordDecl *, 2> BasesWithOverriddenMethods;
David Majnemerc2e67532014-09-23 22:58:15 +00002739 // Seed the working set with our non-destructor, non-pure virtual methods.
David Majnemerc964b4b2014-07-16 06:04:00 +00002740 for (const CXXMethodDecl *MD : RD->methods())
David Majnemerc2e67532014-09-23 22:58:15 +00002741 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD) && !MD->isPure())
David Majnemerc964b4b2014-07-16 06:04:00 +00002742 Work.insert(MD);
Warren Hunt73f43982014-04-11 22:05:28 +00002743 while (!Work.empty()) {
2744 const CXXMethodDecl *MD = *Work.begin();
2745 CXXMethodDecl::method_iterator i = MD->begin_overridden_methods(),
2746 e = MD->end_overridden_methods();
2747 // If a virtual method has no-overrides it lives in its parent's vtable.
2748 if (i == e)
2749 BasesWithOverriddenMethods.insert(MD->getParent());
2750 else
2751 Work.insert(i, e);
2752 // We've finished processing this element, remove it from the working set.
2753 Work.erase(MD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002754 }
Warren Hunt73f43982014-04-11 22:05:28 +00002755 // For each of our virtual bases, check if it is in the set of overridden
2756 // bases or if it transitively contains a non-virtual base that is.
David Majnemerc964b4b2014-07-16 06:04:00 +00002757 for (const CXXBaseSpecifier &Base : RD->vbases()) {
2758 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002759 if (!HasVtordispSet.count(BaseDecl) &&
Warren Hunt73f43982014-04-11 22:05:28 +00002760 RequiresVtordisp(BasesWithOverriddenMethods, BaseDecl))
Warren Huntd640d7d2014-01-09 00:30:56 +00002761 HasVtordispSet.insert(BaseDecl);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002762 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002763}
2764
2765/// \brief Get or compute information about the layout of the specified record
2766/// (struct/union/class), which indicates its size and field position
2767/// information.
2768const ASTRecordLayout *
2769ASTContext::BuildMicrosoftASTRecordLayout(const RecordDecl *D) const {
2770 MicrosoftRecordLayoutBuilder Builder(*this);
2771 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2772 Builder.cxxLayout(RD);
2773 return new (*this) ASTRecordLayout(
Warren Hunt7b252d22013-12-06 00:01:17 +00002774 *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment,
Warren Huntd640d7d2014-01-09 00:30:56 +00002775 Builder.HasOwnVFPtr,
2776 Builder.HasOwnVFPtr || Builder.PrimaryBase,
Warren Huntf6ec7482014-02-21 01:40:35 +00002777 Builder.VBPtrOffset, Builder.NonVirtualSize, Builder.FieldOffsets.data(),
2778 Builder.FieldOffsets.size(), Builder.NonVirtualSize,
Warren Huntd640d7d2014-01-09 00:30:56 +00002779 Builder.Alignment, CharUnits::Zero(), Builder.PrimaryBase,
Warren Hunt049f6732013-12-06 19:54:25 +00002780 false, Builder.SharedVBPtrBase,
Warren Hunt39a907b2014-04-09 21:57:24 +00002781 Builder.EndsWithZeroSizedObject, Builder.LeadsWithZeroSizedBase,
Warren Hunt049f6732013-12-06 19:54:25 +00002782 Builder.Bases, Builder.VBases);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002783 } else {
2784 Builder.layout(D);
2785 return new (*this) ASTRecordLayout(
Warren Hunt7b252d22013-12-06 00:01:17 +00002786 *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment,
2787 Builder.Size, Builder.FieldOffsets.data(), Builder.FieldOffsets.size());
Warren Hunt8f8bad72013-10-11 20:19:00 +00002788 }
2789}
2790
Anders Carlssondf291d82010-05-26 04:56:53 +00002791/// getASTRecordLayout - Get or compute information about the layout of the
2792/// specified record (struct/union/class), which indicates its size and field
2793/// position information.
Jay Foad39c79802011-01-12 09:06:06 +00002794const ASTRecordLayout &
2795ASTContext::getASTRecordLayout(const RecordDecl *D) const {
John McCall0710e552011-10-07 02:39:22 +00002796 // These asserts test different things. A record has a definition
2797 // as soon as we begin to parse the definition. That definition is
2798 // not a complete definition (which is what isDefinition() tests)
2799 // until we *finish* parsing the definition.
Sean Callanan56c19892012-02-08 00:04:52 +00002800
2801 if (D->hasExternalLexicalStorage() && !D->getDefinition())
2802 getExternalSource()->CompleteType(const_cast<RecordDecl*>(D));
2803
Anders Carlssondf291d82010-05-26 04:56:53 +00002804 D = D->getDefinition();
2805 assert(D && "Cannot get layout of forward declarations!");
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00002806 assert(!D->isInvalidDecl() && "Cannot get layout of invalid decl!");
John McCallf937c022011-10-07 06:10:15 +00002807 assert(D->isCompleteDefinition() && "Cannot layout type before complete!");
Anders Carlssondf291d82010-05-26 04:56:53 +00002808
2809 // Look up this layout, if already laid out, return what we have.
2810 // Note that we can't save a reference to the entry because this function
2811 // is recursive.
2812 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
2813 if (Entry) return *Entry;
2814
Craig Topper36250ad2014-05-12 05:36:57 +00002815 const ASTRecordLayout *NewEntry = nullptr;
Anders Carlssond2954862010-05-26 05:10:47 +00002816
Reid Kleckneraf1465c2014-02-20 23:07:29 +00002817 if (isMsLayout(D) && !D->getASTContext().getExternalSource()) {
Warren Hunt8f8bad72013-10-11 20:19:00 +00002818 NewEntry = BuildMicrosoftASTRecordLayout(D);
2819 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
Anders Carlssonc121b4e2010-05-27 00:07:01 +00002820 EmptySubobjectMap EmptySubobjects(*this, RD);
John McCall0153cd32011-11-08 04:01:03 +00002821 RecordLayoutBuilder Builder(*this, &EmptySubobjects);
2822 Builder.Layout(RD);
Anders Carlsson439edd12010-05-27 05:41:06 +00002823
John McCall5c1f1d02013-01-29 01:14:22 +00002824 // In certain situations, we are allowed to lay out objects in the
2825 // tail-padding of base classes. This is ABI-dependent.
2826 // FIXME: this should be stored in the record layout.
2827 bool skipTailPadding =
2828 mustSkipTailPadding(getTargetInfo().getCXXABI(), cast<CXXRecordDecl>(D));
Anders Carlssond2954862010-05-26 05:10:47 +00002829
2830 // FIXME: This should be done in FinalizeLayout.
Ken Dyck1b4420e2011-02-28 02:01:38 +00002831 CharUnits DataSize =
John McCall5c1f1d02013-01-29 01:14:22 +00002832 skipTailPadding ? Builder.getSize() : Builder.getDataSize();
Ken Dyck1b4420e2011-02-28 02:01:38 +00002833 CharUnits NonVirtualSize =
John McCall5c1f1d02013-01-29 01:14:22 +00002834 skipTailPadding ? DataSize : Builder.NonVirtualSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002835 NewEntry =
John McCall0153cd32011-11-08 04:01:03 +00002836 new (*this) ASTRecordLayout(*this, Builder.getSize(),
2837 Builder.Alignment,
Warren Hunt7b252d22013-12-06 00:01:17 +00002838 /*RequiredAlignment : used by MS-ABI)*/
2839 Builder.Alignment,
John McCalle42a3362012-05-01 08:55:32 +00002840 Builder.HasOwnVFPtr,
Warren Hunt8f8bad72013-10-11 20:19:00 +00002841 RD->isDynamicClass(),
Warren Hunt55d8e822013-10-23 23:53:07 +00002842 CharUnits::fromQuantity(-1),
Ken Dyck1b4420e2011-02-28 02:01:38 +00002843 DataSize,
John McCall0153cd32011-11-08 04:01:03 +00002844 Builder.FieldOffsets.data(),
2845 Builder.FieldOffsets.size(),
Ken Dyckaf1c83f2011-02-16 01:52:01 +00002846 NonVirtualSize,
John McCall0153cd32011-11-08 04:01:03 +00002847 Builder.NonVirtualAlignment,
Anders Carlssonc121b4e2010-05-27 00:07:01 +00002848 EmptySubobjects.SizeOfLargestEmptySubobject,
John McCall0153cd32011-11-08 04:01:03 +00002849 Builder.PrimaryBase,
2850 Builder.PrimaryBaseIsVirtual,
Craig Topper36250ad2014-05-12 05:36:57 +00002851 nullptr, false, false,
John McCall0153cd32011-11-08 04:01:03 +00002852 Builder.Bases, Builder.VBases);
Anders Carlssond2954862010-05-26 05:10:47 +00002853 } else {
Craig Topper36250ad2014-05-12 05:36:57 +00002854 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/nullptr);
Anders Carlssond2954862010-05-26 05:10:47 +00002855 Builder.Layout(D);
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002856
Anders Carlssond2954862010-05-26 05:10:47 +00002857 NewEntry =
Ken Dyck1b4420e2011-02-28 02:01:38 +00002858 new (*this) ASTRecordLayout(*this, Builder.getSize(),
Ken Dyck4731d5b2011-02-16 02:05:21 +00002859 Builder.Alignment,
Warren Hunt7b252d22013-12-06 00:01:17 +00002860 /*RequiredAlignment : used by MS-ABI)*/
2861 Builder.Alignment,
Ken Dyck1b4420e2011-02-28 02:01:38 +00002862 Builder.getSize(),
Anders Carlssond2954862010-05-26 05:10:47 +00002863 Builder.FieldOffsets.data(),
2864 Builder.FieldOffsets.size());
2865 }
2866
Anders Carlssondf291d82010-05-26 04:56:53 +00002867 ASTRecordLayouts[D] = NewEntry;
2868
David Blaikiebbafb8a2012-03-11 07:00:24 +00002869 if (getLangOpts().DumpRecordLayouts) {
Argyrios Kyrtzidis8ade08e2013-07-12 22:30:03 +00002870 llvm::outs() << "\n*** Dumping AST Record Layout\n";
2871 DumpRecordLayout(D, llvm::outs(), getLangOpts().DumpRecordLayoutsSimple);
Anders Carlssondf291d82010-05-26 04:56:53 +00002872 }
2873
2874 return *NewEntry;
2875}
2876
John McCall6bd2a892013-01-25 22:31:03 +00002877const CXXMethodDecl *ASTContext::getCurrentKeyFunction(const CXXRecordDecl *RD) {
Reid Kleckner5d7f2982013-05-29 16:18:30 +00002878 if (!getTargetInfo().getCXXABI().hasKeyFunctions())
Craig Topper36250ad2014-05-12 05:36:57 +00002879 return nullptr;
Reid Kleckner5d7f2982013-05-29 16:18:30 +00002880
John McCall6bd2a892013-01-25 22:31:03 +00002881 assert(RD->getDefinition() && "Cannot get key function for forward decl!");
Anders Carlssondf291d82010-05-26 04:56:53 +00002882 RD = cast<CXXRecordDecl>(RD->getDefinition());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002883
Richard Smitha9a1c682014-07-07 06:38:20 +00002884 // Beware:
2885 // 1) computing the key function might trigger deserialization, which might
2886 // invalidate iterators into KeyFunctions
2887 // 2) 'get' on the LazyDeclPtr might also trigger deserialization and
2888 // invalidate the LazyDeclPtr within the map itself
2889 LazyDeclPtr Entry = KeyFunctions[RD];
2890 const Decl *Result =
2891 Entry ? Entry.get(getExternalSource()) : computeKeyFunction(*this, RD);
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002892
Richard Smitha9a1c682014-07-07 06:38:20 +00002893 // Store it back if it changed.
2894 if (Entry.isOffset() || Entry.isValid() != bool(Result))
2895 KeyFunctions[RD] = const_cast<Decl*>(Result);
2896
2897 return cast_or_null<CXXMethodDecl>(Result);
John McCall6bd2a892013-01-25 22:31:03 +00002898}
2899
Richard Smith676c4042013-08-29 23:59:27 +00002900void ASTContext::setNonKeyFunction(const CXXMethodDecl *Method) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002901 assert(Method == Method->getFirstDecl() &&
John McCall6bd2a892013-01-25 22:31:03 +00002902 "not working with method declaration from class definition");
2903
2904 // Look up the cache entry. Since we're working with the first
2905 // declaration, its parent must be the class definition, which is
2906 // the correct key for the KeyFunctions hash.
Richard Smith676c4042013-08-29 23:59:27 +00002907 llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr>::iterator
2908 I = KeyFunctions.find(Method->getParent());
John McCall6bd2a892013-01-25 22:31:03 +00002909
2910 // If it's not cached, there's nothing to do.
Richard Smith676c4042013-08-29 23:59:27 +00002911 if (I == KeyFunctions.end()) return;
John McCall6bd2a892013-01-25 22:31:03 +00002912
2913 // If it is cached, check whether it's the target method, and if so,
Richard Smitha9a1c682014-07-07 06:38:20 +00002914 // remove it from the cache. Note, the call to 'get' might invalidate
2915 // the iterator and the LazyDeclPtr object within the map.
2916 LazyDeclPtr Ptr = I->second;
2917 if (Ptr.get(getExternalSource()) == Method) {
John McCall6bd2a892013-01-25 22:31:03 +00002918 // FIXME: remember that we did this for module / chained PCH state?
Richard Smitha9a1c682014-07-07 06:38:20 +00002919 KeyFunctions.erase(Method->getParent());
John McCall6bd2a892013-01-25 22:31:03 +00002920 }
Anders Carlssondf291d82010-05-26 04:56:53 +00002921}
2922
Richard Smithdafff942012-01-14 04:30:29 +00002923static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) {
2924 const ASTRecordLayout &Layout = C.getASTRecordLayout(FD->getParent());
2925 return Layout.getFieldOffset(FD->getFieldIndex());
2926}
2927
2928uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const {
2929 uint64_t OffsetInBits;
2930 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
2931 OffsetInBits = ::getFieldOffset(*this, FD);
2932 } else {
2933 const IndirectFieldDecl *IFD = cast<IndirectFieldDecl>(VD);
2934
2935 OffsetInBits = 0;
David Majnemerc964b4b2014-07-16 06:04:00 +00002936 for (const NamedDecl *ND : IFD->chain())
2937 OffsetInBits += ::getFieldOffset(*this, cast<FieldDecl>(ND));
Richard Smithdafff942012-01-14 04:30:29 +00002938 }
2939
2940 return OffsetInBits;
2941}
2942
Eric Christopher8a39a012011-10-05 06:00:51 +00002943/// getObjCLayout - Get or compute information about the layout of the
2944/// given interface.
Anders Carlssondf291d82010-05-26 04:56:53 +00002945///
2946/// \param Impl - If given, also include the layout of the interface's
2947/// implementation. This may differ by including synthesized ivars.
2948const ASTRecordLayout &
2949ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
Jay Foad39c79802011-01-12 09:06:06 +00002950 const ObjCImplementationDecl *Impl) const {
Douglas Gregor64d92572011-12-20 15:50:13 +00002951 // Retrieve the definition
Sean Callanand9a909c2012-03-15 16:33:08 +00002952 if (D->hasExternalLexicalStorage() && !D->getDefinition())
2953 getExternalSource()->CompleteType(const_cast<ObjCInterfaceDecl*>(D));
Douglas Gregor64d92572011-12-20 15:50:13 +00002954 D = D->getDefinition();
2955 assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!");
Anders Carlssondf291d82010-05-26 04:56:53 +00002956
2957 // Look up this layout, if already laid out, return what we have.
Roman Divackye6377112012-09-06 15:59:27 +00002958 const ObjCContainerDecl *Key =
2959 Impl ? (const ObjCContainerDecl*) Impl : (const ObjCContainerDecl*) D;
Anders Carlssondf291d82010-05-26 04:56:53 +00002960 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
2961 return *Entry;
2962
2963 // Add in synthesized ivar count if laying out an implementation.
2964 if (Impl) {
2965 unsigned SynthCount = CountNonClassIvars(D);
2966 // If there aren't any sythesized ivars then reuse the interface
2967 // entry. Note we can't cache this because we simply free all
2968 // entries later; however we shouldn't look up implementations
2969 // frequently.
2970 if (SynthCount == 0)
Craig Topper36250ad2014-05-12 05:36:57 +00002971 return getObjCLayout(D, nullptr);
Anders Carlssondf291d82010-05-26 04:56:53 +00002972 }
2973
Craig Topper36250ad2014-05-12 05:36:57 +00002974 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/nullptr);
Anders Carlsson6ed3a9a2010-05-26 05:04:25 +00002975 Builder.Layout(D);
2976
Anders Carlssondf291d82010-05-26 04:56:53 +00002977 const ASTRecordLayout *NewEntry =
Ken Dyck1b4420e2011-02-28 02:01:38 +00002978 new (*this) ASTRecordLayout(*this, Builder.getSize(),
Ken Dyck4731d5b2011-02-16 02:05:21 +00002979 Builder.Alignment,
Warren Hunt7b252d22013-12-06 00:01:17 +00002980 /*RequiredAlignment : used by MS-ABI)*/
2981 Builder.Alignment,
Ken Dyck1b4420e2011-02-28 02:01:38 +00002982 Builder.getDataSize(),
Anders Carlsson6ed3a9a2010-05-26 05:04:25 +00002983 Builder.FieldOffsets.data(),
2984 Builder.FieldOffsets.size());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002985
Anders Carlssondf291d82010-05-26 04:56:53 +00002986 ObjCLayouts[Key] = NewEntry;
2987
2988 return *NewEntry;
2989}
2990
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002991static void PrintOffset(raw_ostream &OS,
Anders Carlsson3f018712010-10-31 23:45:59 +00002992 CharUnits Offset, unsigned IndentLevel) {
Benjamin Kramer96ad7172011-11-05 09:02:52 +00002993 OS << llvm::format("%4" PRId64 " | ", (int64_t)Offset.getQuantity());
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002994 OS.indent(IndentLevel * 2);
2995}
2996
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00002997static void PrintIndentNoOffset(raw_ostream &OS, unsigned IndentLevel) {
2998 OS << " | ";
2999 OS.indent(IndentLevel * 2);
3000}
3001
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003002static void DumpCXXRecordLayout(raw_ostream &OS,
Jay Foad39c79802011-01-12 09:06:06 +00003003 const CXXRecordDecl *RD, const ASTContext &C,
Anders Carlsson3f018712010-10-31 23:45:59 +00003004 CharUnits Offset,
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003005 unsigned IndentLevel,
3006 const char* Description,
3007 bool IncludeVirtualBases) {
Anders Carlsson3f018712010-10-31 23:45:59 +00003008 const ASTRecordLayout &Layout = C.getASTRecordLayout(RD);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003009
3010 PrintOffset(OS, Offset, IndentLevel);
Dan Gohman145f3f12010-04-19 16:39:44 +00003011 OS << C.getTypeDeclType(const_cast<CXXRecordDecl *>(RD)).getAsString();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003012 if (Description)
3013 OS << ' ' << Description;
3014 if (RD->isEmpty())
3015 OS << " (empty)";
3016 OS << '\n';
3017
3018 IndentLevel++;
3019
Anders Carlsson3f018712010-10-31 23:45:59 +00003020 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
Warren Hunt8f8bad72013-10-11 20:19:00 +00003021 bool HasOwnVFPtr = Layout.hasOwnVFPtr();
3022 bool HasOwnVBPtr = Layout.hasOwnVBPtr();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003023
3024 // Vtable pointer.
Warren Hunt8f8bad72013-10-11 20:19:00 +00003025 if (RD->isDynamicClass() && !PrimaryBase && !isMsLayout(RD)) {
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003026 PrintOffset(OS, Offset, IndentLevel);
Benjamin Kramerb89514a2011-10-14 18:45:37 +00003027 OS << '(' << *RD << " vtable pointer)\n";
Warren Hunt8f8bad72013-10-11 20:19:00 +00003028 } else if (HasOwnVFPtr) {
3029 PrintOffset(OS, Offset, IndentLevel);
3030 // vfptr (for Microsoft C++ ABI)
3031 OS << '(' << *RD << " vftable pointer)\n";
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003032 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00003033
Reid Klecknerad59deb2014-02-28 01:03:09 +00003034 // Collect nvbases.
3035 SmallVector<const CXXRecordDecl *, 4> Bases;
David Majnemerc964b4b2014-07-16 06:04:00 +00003036 for (const CXXBaseSpecifier &Base : RD->bases()) {
3037 assert(!Base.getType()->isDependentType() &&
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003038 "Cannot layout class with dependent bases.");
David Majnemerc964b4b2014-07-16 06:04:00 +00003039 if (!Base.isVirtual())
3040 Bases.push_back(Base.getType()->getAsCXXRecordDecl());
Reid Klecknerad59deb2014-02-28 01:03:09 +00003041 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003042
Reid Klecknerad59deb2014-02-28 01:03:09 +00003043 // Sort nvbases by offset.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00003044 std::stable_sort(Bases.begin(), Bases.end(),
3045 [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
3046 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
3047 });
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003048
Reid Klecknerad59deb2014-02-28 01:03:09 +00003049 // Dump (non-virtual) bases
David Majnemerc964b4b2014-07-16 06:04:00 +00003050 for (const CXXRecordDecl *Base : Bases) {
Anders Carlsson3f018712010-10-31 23:45:59 +00003051 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003052 DumpCXXRecordLayout(OS, Base, C, BaseOffset, IndentLevel,
3053 Base == PrimaryBase ? "(primary base)" : "(base)",
3054 /*IncludeVirtualBases=*/false);
3055 }
Eli Friedman43114f92011-10-21 22:49:56 +00003056
Warren Hunt8f8bad72013-10-11 20:19:00 +00003057 // vbptr (for Microsoft C++ ABI)
3058 if (HasOwnVBPtr) {
Eli Friedman84d2d3a2011-09-27 19:12:27 +00003059 PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel);
Benjamin Kramerb89514a2011-10-14 18:45:37 +00003060 OS << '(' << *RD << " vbtable pointer)\n";
Eli Friedman84d2d3a2011-09-27 19:12:27 +00003061 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003062
3063 // Dump fields.
3064 uint64_t FieldNo = 0;
3065 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
3066 E = RD->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +00003067 const FieldDecl &Field = **I;
Anders Carlsson3f018712010-10-31 23:45:59 +00003068 CharUnits FieldOffset = Offset +
Ken Dyck86a7fcc2011-01-18 01:56:16 +00003069 C.toCharUnitsFromBits(Layout.getFieldOffset(FieldNo));
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003070
Reid Klecknercd612ab2014-04-11 16:57:42 +00003071 if (const CXXRecordDecl *D = Field.getType()->getAsCXXRecordDecl()) {
3072 DumpCXXRecordLayout(OS, D, C, FieldOffset, IndentLevel,
3073 Field.getName().data(),
3074 /*IncludeVirtualBases=*/true);
3075 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003076 }
3077
3078 PrintOffset(OS, FieldOffset, IndentLevel);
David Blaikie2d7c57e2012-04-30 02:36:29 +00003079 OS << Field.getType().getAsString() << ' ' << Field << '\n';
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003080 }
3081
3082 if (!IncludeVirtualBases)
3083 return;
3084
3085 // Dump virtual bases.
John McCalle42a3362012-05-01 08:55:32 +00003086 const ASTRecordLayout::VBaseOffsetsMapTy &vtordisps =
3087 Layout.getVBaseOffsetsMap();
David Majnemerc964b4b2014-07-16 06:04:00 +00003088 for (const CXXBaseSpecifier &Base : RD->vbases()) {
3089 assert(Base.isVirtual() && "Found non-virtual class!");
3090 const CXXRecordDecl *VBase = Base.getType()->getAsCXXRecordDecl();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003091
Anders Carlsson3f018712010-10-31 23:45:59 +00003092 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
John McCalle42a3362012-05-01 08:55:32 +00003093
3094 if (vtordisps.find(VBase)->second.hasVtorDisp()) {
3095 PrintOffset(OS, VBaseOffset - CharUnits::fromQuantity(4), IndentLevel);
3096 OS << "(vtordisp for vbase " << *VBase << ")\n";
3097 }
3098
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003099 DumpCXXRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel,
3100 VBase == PrimaryBase ?
3101 "(primary virtual base)" : "(virtual base)",
3102 /*IncludeVirtualBases=*/false);
3103 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003104
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00003105 PrintIndentNoOffset(OS, IndentLevel - 1);
3106 OS << "[sizeof=" << Layout.getSize().getQuantity();
Warren Hunt8f8bad72013-10-11 20:19:00 +00003107 if (!isMsLayout(RD))
3108 OS << ", dsize=" << Layout.getDataSize().getQuantity();
Ken Dyck7ad11e72011-02-15 02:32:40 +00003109 OS << ", align=" << Layout.getAlignment().getQuantity() << '\n';
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00003110
3111 PrintIndentNoOffset(OS, IndentLevel - 1);
3112 OS << " nvsize=" << Layout.getNonVirtualSize().getQuantity();
Warren Huntd640d7d2014-01-09 00:30:56 +00003113 OS << ", nvalign=" << Layout.getNonVirtualAlignment().getQuantity() << "]\n";
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003114}
Daniel Dunbarccabe482010-04-19 20:44:53 +00003115
3116void ASTContext::DumpRecordLayout(const RecordDecl *RD,
Douglas Gregore9fc3772012-01-26 07:55:45 +00003117 raw_ostream &OS,
3118 bool Simple) const {
Daniel Dunbarccabe482010-04-19 20:44:53 +00003119 const ASTRecordLayout &Info = getASTRecordLayout(RD);
3120
3121 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Douglas Gregore9fc3772012-01-26 07:55:45 +00003122 if (!Simple)
Craig Topper36250ad2014-05-12 05:36:57 +00003123 return DumpCXXRecordLayout(OS, CXXRD, *this, CharUnits(), 0, nullptr,
Douglas Gregore9fc3772012-01-26 07:55:45 +00003124 /*IncludeVirtualBases=*/true);
Daniel Dunbarccabe482010-04-19 20:44:53 +00003125
3126 OS << "Type: " << getTypeDeclType(RD).getAsString() << "\n";
Douglas Gregore9fc3772012-01-26 07:55:45 +00003127 if (!Simple) {
3128 OS << "Record: ";
3129 RD->dump();
3130 }
Daniel Dunbarccabe482010-04-19 20:44:53 +00003131 OS << "\nLayout: ";
3132 OS << "<ASTRecordLayout\n";
Ken Dyckb0fcc592011-02-11 01:54:29 +00003133 OS << " Size:" << toBits(Info.getSize()) << "\n";
Warren Hunt8f8bad72013-10-11 20:19:00 +00003134 if (!isMsLayout(RD))
3135 OS << " DataSize:" << toBits(Info.getDataSize()) << "\n";
Ken Dyck7ad11e72011-02-15 02:32:40 +00003136 OS << " Alignment:" << toBits(Info.getAlignment()) << "\n";
Daniel Dunbarccabe482010-04-19 20:44:53 +00003137 OS << " FieldOffsets: [";
3138 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) {
3139 if (i) OS << ", ";
3140 OS << Info.getFieldOffset(i);
3141 }
3142 OS << "]>\n";
3143}