blob: cb5b1093436c73c7f6954b5c9a55f8dcd807c16f [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.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000068 typedef SmallVector<const CXXRecordDecl *, 1> 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.
Aaron Ballman574705e2014-03-13 15:41:46 +0000143 for (const auto &I : Class->bases()) {
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000144 const CXXRecordDecl *BaseDecl =
Aaron Ballman574705e2014-03-13 15:41:46 +0000145 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000146
Anders Carlsson28466ab2010-10-31 22:13:23 +0000147 CharUnits EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000148 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
149 if (BaseDecl->isEmpty()) {
150 // If the class decl is empty, get its size.
Ken Dyckc8ae5502011-02-09 01:59:34 +0000151 EmptySize = Layout.getSize();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000152 } else {
153 // Otherwise, we get the largest empty subobject for the decl.
154 EmptySize = Layout.getSizeOfLargestEmptySubobject();
155 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000156
Anders Carlsson28466ab2010-10-31 22:13:23 +0000157 if (EmptySize > SizeOfLargestEmptySubobject)
158 SizeOfLargestEmptySubobject = EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000159 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000160
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000161 // Check the fields.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +0000162 for (const auto *I : Class->fields()) {
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000163 const RecordType *RT =
David Blaikie40ed2972012-06-06 20:45:41 +0000164 Context.getBaseElementType(I->getType())->getAs<RecordType>();
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000165
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000166 // We only care about record types.
167 if (!RT)
168 continue;
169
Anders Carlsson28466ab2010-10-31 22:13:23 +0000170 CharUnits EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000171 const CXXRecordDecl *MemberDecl = cast<CXXRecordDecl>(RT->getDecl());
172 const ASTRecordLayout &Layout = Context.getASTRecordLayout(MemberDecl);
173 if (MemberDecl->isEmpty()) {
174 // If the class decl is empty, get its size.
Ken Dyckc8ae5502011-02-09 01:59:34 +0000175 EmptySize = Layout.getSize();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000176 } else {
177 // Otherwise, we get the largest empty subobject for the decl.
178 EmptySize = Layout.getSizeOfLargestEmptySubobject();
179 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000180
Anders Carlsson28466ab2010-10-31 22:13:23 +0000181 if (EmptySize > SizeOfLargestEmptySubobject)
182 SizeOfLargestEmptySubobject = EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000183 }
184}
185
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000186bool
Anders Carlssondb319762010-05-27 18:20:57 +0000187EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
Anders Carlsson725190f2010-10-31 21:39:24 +0000188 CharUnits Offset) const {
Anders Carlssondb319762010-05-27 18:20:57 +0000189 // We only need to check empty bases.
190 if (!RD->isEmpty())
191 return true;
192
Anders Carlsson725190f2010-10-31 21:39:24 +0000193 EmptyClassOffsetsMapTy::const_iterator I = EmptyClassOffsets.find(Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000194 if (I == EmptyClassOffsets.end())
195 return true;
196
197 const ClassVectorTy& Classes = I->second;
198 if (std::find(Classes.begin(), Classes.end(), RD) == Classes.end())
199 return true;
200
201 // There is already an empty class of the same type at this offset.
202 return false;
203}
204
205void EmptySubobjectMap::AddSubobjectAtOffset(const CXXRecordDecl *RD,
Anders Carlsson725190f2010-10-31 21:39:24 +0000206 CharUnits Offset) {
Anders Carlssondb319762010-05-27 18:20:57 +0000207 // We only care about empty bases.
208 if (!RD->isEmpty())
209 return;
210
Reid Kleckner369f3162013-05-14 20:30:42 +0000211 // If we have empty structures inside a union, we can assign both
Rafael Espindola7bcde192010-12-29 23:02:58 +0000212 // the same offset. Just avoid pushing them twice in the list.
Anders Carlsson725190f2010-10-31 21:39:24 +0000213 ClassVectorTy& Classes = EmptyClassOffsets[Offset];
Rafael Espindola7bcde192010-12-29 23:02:58 +0000214 if (std::find(Classes.begin(), Classes.end(), RD) != Classes.end())
215 return;
216
Anders Carlssondb319762010-05-27 18:20:57 +0000217 Classes.push_back(RD);
Anders Carlssoncc5de092010-06-08 15:56:03 +0000218
219 // Update the empty class offset.
Anders Carlsson725190f2010-10-31 21:39:24 +0000220 if (Offset > MaxEmptyClassOffset)
221 MaxEmptyClassOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000222}
223
224bool
Anders Carlsson28466ab2010-10-31 22:13:23 +0000225EmptySubobjectMap::CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
226 CharUnits Offset) {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000227 // We don't have to keep looking past the maximum offset that's known to
228 // contain an empty class.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000229 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000230 return true;
231
Anders Carlsson28466ab2010-10-31 22:13:23 +0000232 if (!CanPlaceSubobjectAtOffset(Info->Class, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000233 return false;
234
Anders Carlsson439edd12010-05-27 05:41:06 +0000235 // Traverse all non-virtual bases.
Anders Carlssona7774a62010-05-29 21:10:24 +0000236 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
Anders Carlsson439edd12010-05-27 05:41:06 +0000237 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
Anders Carlssona7f3cdb2010-05-28 21:24:37 +0000238 BaseSubobjectInfo* Base = Info->Bases[I];
Anders Carlsson439edd12010-05-27 05:41:06 +0000239 if (Base->IsVirtual)
240 continue;
241
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000242 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlsson439edd12010-05-27 05:41:06 +0000243
244 if (!CanPlaceBaseSubobjectAtOffset(Base, BaseOffset))
245 return false;
246 }
247
Anders Carlssone3c24c72010-05-29 17:35:14 +0000248 if (Info->PrimaryVirtualBaseInfo) {
249 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
Anders Carlsson439edd12010-05-27 05:41:06 +0000250
251 if (Info == PrimaryVirtualBaseInfo->Derived) {
252 if (!CanPlaceBaseSubobjectAtOffset(PrimaryVirtualBaseInfo, Offset))
253 return false;
254 }
255 }
256
Anders Carlssondb319762010-05-27 18:20:57 +0000257 // Traverse all member variables.
258 unsigned FieldNo = 0;
259 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
260 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000261 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000262 continue;
263
Anders Carlsson28466ab2010-10-31 22:13:23 +0000264 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
David Blaikie40ed2972012-06-06 20:45:41 +0000265 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000266 return false;
267 }
268
Anders Carlsson439edd12010-05-27 05:41:06 +0000269 return true;
270}
271
Anders Carlssona7f3cdb2010-05-28 21:24:37 +0000272void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000273 CharUnits Offset,
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000274 bool PlacingEmptyBase) {
275 if (!PlacingEmptyBase && Offset >= SizeOfLargestEmptySubobject) {
276 // We know that the only empty subobjects that can conflict with empty
277 // subobject of non-empty bases, are empty bases that can be placed at
278 // offset zero. Because of this, we only need to keep track of empty base
279 // subobjects with offsets less than the size of the largest empty
280 // subobject for our class.
281 return;
282 }
283
Anders Carlsson28466ab2010-10-31 22:13:23 +0000284 AddSubobjectAtOffset(Info->Class, Offset);
Anders Carlssona7774a62010-05-29 21:10:24 +0000285
Anders Carlsson439edd12010-05-27 05:41:06 +0000286 // Traverse all non-virtual bases.
Anders Carlssona7774a62010-05-29 21:10:24 +0000287 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
Anders Carlsson439edd12010-05-27 05:41:06 +0000288 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
Anders Carlssona7f3cdb2010-05-28 21:24:37 +0000289 BaseSubobjectInfo* Base = Info->Bases[I];
Anders Carlsson439edd12010-05-27 05:41:06 +0000290 if (Base->IsVirtual)
291 continue;
Anders Carlssona7774a62010-05-29 21:10:24 +0000292
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000293 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000294 UpdateEmptyBaseSubobjects(Base, BaseOffset, PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +0000295 }
296
Anders Carlssone3c24c72010-05-29 17:35:14 +0000297 if (Info->PrimaryVirtualBaseInfo) {
298 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
Anders Carlsson439edd12010-05-27 05:41:06 +0000299
300 if (Info == PrimaryVirtualBaseInfo->Derived)
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000301 UpdateEmptyBaseSubobjects(PrimaryVirtualBaseInfo, Offset,
302 PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +0000303 }
Anders Carlssondb319762010-05-27 18:20:57 +0000304
Anders Carlssondb319762010-05-27 18:20:57 +0000305 // Traverse all member variables.
306 unsigned FieldNo = 0;
307 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
308 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000309 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000310 continue;
Anders Carlssona7774a62010-05-29 21:10:24 +0000311
Anders Carlsson28466ab2010-10-31 22:13:23 +0000312 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
David Blaikie40ed2972012-06-06 20:45:41 +0000313 UpdateEmptyFieldSubobjects(*I, FieldOffset);
Anders Carlssondb319762010-05-27 18:20:57 +0000314 }
Anders Carlsson439edd12010-05-27 05:41:06 +0000315}
316
Anders Carlssona60b86a2010-05-29 20:49:49 +0000317bool EmptySubobjectMap::CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000318 CharUnits Offset) {
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000319 // If we know this class doesn't have any empty subobjects we don't need to
320 // bother checking.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000321 if (SizeOfLargestEmptySubobject.isZero())
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000322 return true;
323
Anders Carlsson439edd12010-05-27 05:41:06 +0000324 if (!CanPlaceBaseSubobjectAtOffset(Info, Offset))
325 return false;
Anders Carlssondb319762010-05-27 18:20:57 +0000326
327 // We are able to place the base at this offset. Make sure to update the
328 // empty base subobject map.
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000329 UpdateEmptyBaseSubobjects(Info, Offset, Info->Class->isEmpty());
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000330 return true;
331}
332
Anders Carlssondb319762010-05-27 18:20:57 +0000333bool
334EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
335 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000336 CharUnits Offset) const {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000337 // We don't have to keep looking past the maximum offset that's known to
338 // contain an empty class.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000339 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000340 return true;
341
Anders Carlsson28466ab2010-10-31 22:13:23 +0000342 if (!CanPlaceSubobjectAtOffset(RD, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000343 return false;
344
345 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
346
347 // Traverse all non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000348 for (const auto &I : RD->bases()) {
349 if (I.isVirtual())
Anders Carlssondb319762010-05-27 18:20:57 +0000350 continue;
351
352 const CXXRecordDecl *BaseDecl =
Aaron Ballman574705e2014-03-13 15:41:46 +0000353 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlssondb319762010-05-27 18:20:57 +0000354
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000355 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
Anders Carlssondb319762010-05-27 18:20:57 +0000356 if (!CanPlaceFieldSubobjectAtOffset(BaseDecl, Class, BaseOffset))
357 return false;
358 }
359
Anders Carlsson44687202010-06-08 19:09:24 +0000360 if (RD == Class) {
361 // This is the most derived class, traverse virtual bases as well.
Aaron Ballman445a9392014-03-13 16:15:17 +0000362 for (const auto &I : RD->vbases()) {
Anders Carlsson44687202010-06-08 19:09:24 +0000363 const CXXRecordDecl *VBaseDecl =
Aaron Ballman445a9392014-03-13 16:15:17 +0000364 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlsson44687202010-06-08 19:09:24 +0000365
Anders Carlsson3f018712010-10-31 23:45:59 +0000366 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
Anders Carlsson44687202010-06-08 19:09:24 +0000367 if (!CanPlaceFieldSubobjectAtOffset(VBaseDecl, Class, VBaseOffset))
368 return false;
369 }
370 }
371
Anders Carlssondb319762010-05-27 18:20:57 +0000372 // Traverse all member variables.
373 unsigned FieldNo = 0;
374 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
375 I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000376 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000377 continue;
378
Anders Carlsson28466ab2010-10-31 22:13:23 +0000379 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
Anders Carlssondb319762010-05-27 18:20:57 +0000380
David Blaikie40ed2972012-06-06 20:45:41 +0000381 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000382 return false;
383 }
384
385 return true;
386}
387
Anders Carlsson233e2722010-10-31 21:54:55 +0000388bool
389EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
390 CharUnits Offset) const {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000391 // We don't have to keep looking past the maximum offset that's known to
392 // contain an empty class.
Anders Carlsson233e2722010-10-31 21:54:55 +0000393 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000394 return true;
395
Anders Carlssondb319762010-05-27 18:20:57 +0000396 QualType T = FD->getType();
397 if (const RecordType *RT = T->getAs<RecordType>()) {
398 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlsson28466ab2010-10-31 22:13:23 +0000399 return CanPlaceFieldSubobjectAtOffset(RD, RD, Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000400 }
401
402 // If we have an array type we need to look at every element.
403 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
404 QualType ElemTy = Context.getBaseElementType(AT);
405 const RecordType *RT = ElemTy->getAs<RecordType>();
406 if (!RT)
407 return true;
408
409 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
410 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
411
412 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
Anders Carlsson233e2722010-10-31 21:54:55 +0000413 CharUnits ElementOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000414 for (uint64_t I = 0; I != NumElements; ++I) {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000415 // We don't have to keep looking past the maximum offset that's known to
416 // contain an empty class.
Anders Carlsson233e2722010-10-31 21:54:55 +0000417 if (!AnyEmptySubobjectsBeyondOffset(ElementOffset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000418 return true;
419
Anders Carlsson28466ab2010-10-31 22:13:23 +0000420 if (!CanPlaceFieldSubobjectAtOffset(RD, RD, ElementOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000421 return false;
422
Ken Dyckc8ae5502011-02-09 01:59:34 +0000423 ElementOffset += Layout.getSize();
Anders Carlssondb319762010-05-27 18:20:57 +0000424 }
425 }
426
427 return true;
428}
429
430bool
Anders Carlsson28466ab2010-10-31 22:13:23 +0000431EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl *FD,
432 CharUnits Offset) {
433 if (!CanPlaceFieldSubobjectAtOffset(FD, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000434 return false;
435
436 // We are able to place the member variable at this offset.
437 // Make sure to update the empty base subobject map.
438 UpdateEmptyFieldSubobjects(FD, Offset);
439 return true;
440}
441
442void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
443 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000444 CharUnits Offset) {
Anders Carlssonae111dc2010-06-13 17:49:16 +0000445 // We know that the only empty subobjects that can conflict with empty
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000446 // field subobjects are subobjects of empty bases that can be placed at offset
Anders Carlssonae111dc2010-06-13 17:49:16 +0000447 // zero. Because of this, we only need to keep track of empty field
448 // subobjects with offsets less than the size of the largest empty
449 // subobject for our class.
450 if (Offset >= SizeOfLargestEmptySubobject)
451 return;
452
Anders Carlsson28466ab2010-10-31 22:13:23 +0000453 AddSubobjectAtOffset(RD, Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000454
455 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
456
457 // Traverse all non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000458 for (const auto &I : RD->bases()) {
459 if (I.isVirtual())
Anders Carlssondb319762010-05-27 18:20:57 +0000460 continue;
461
462 const CXXRecordDecl *BaseDecl =
Aaron Ballman574705e2014-03-13 15:41:46 +0000463 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlssondb319762010-05-27 18:20:57 +0000464
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000465 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
Anders Carlssondb319762010-05-27 18:20:57 +0000466 UpdateEmptyFieldSubobjects(BaseDecl, Class, BaseOffset);
467 }
468
Anders Carlsson44687202010-06-08 19:09:24 +0000469 if (RD == Class) {
470 // This is the most derived class, traverse virtual bases as well.
Aaron Ballman445a9392014-03-13 16:15:17 +0000471 for (const auto &I : RD->vbases()) {
Anders Carlsson44687202010-06-08 19:09:24 +0000472 const CXXRecordDecl *VBaseDecl =
Aaron Ballman445a9392014-03-13 16:15:17 +0000473 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlsson44687202010-06-08 19:09:24 +0000474
Anders Carlsson3f018712010-10-31 23:45:59 +0000475 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
Anders Carlsson44687202010-06-08 19:09:24 +0000476 UpdateEmptyFieldSubobjects(VBaseDecl, Class, VBaseOffset);
477 }
478 }
479
Anders Carlssondb319762010-05-27 18:20:57 +0000480 // Traverse all member variables.
481 unsigned FieldNo = 0;
482 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
483 I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000484 if (I->isBitField())
Anders Carlsson09814d32010-11-01 15:14:51 +0000485 continue;
486
Anders Carlsson28466ab2010-10-31 22:13:23 +0000487 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
Anders Carlssondb319762010-05-27 18:20:57 +0000488
David Blaikie40ed2972012-06-06 20:45:41 +0000489 UpdateEmptyFieldSubobjects(*I, FieldOffset);
Anders Carlssondb319762010-05-27 18:20:57 +0000490 }
491}
492
493void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const FieldDecl *FD,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000494 CharUnits Offset) {
Anders Carlssondb319762010-05-27 18:20:57 +0000495 QualType T = FD->getType();
496 if (const RecordType *RT = T->getAs<RecordType>()) {
497 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
498 UpdateEmptyFieldSubobjects(RD, RD, Offset);
499 return;
500 }
501
502 // If we have an array type we need to update every element.
503 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
504 QualType ElemTy = Context.getBaseElementType(AT);
505 const RecordType *RT = ElemTy->getAs<RecordType>();
506 if (!RT)
507 return;
508
509 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
510 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
511
512 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
Anders Carlsson28466ab2010-10-31 22:13:23 +0000513 CharUnits ElementOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000514
515 for (uint64_t I = 0; I != NumElements; ++I) {
Anders Carlssonae111dc2010-06-13 17:49:16 +0000516 // We know that the only empty subobjects that can conflict with empty
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000517 // field subobjects are subobjects of empty bases that can be placed at
Anders Carlssonae111dc2010-06-13 17:49:16 +0000518 // offset zero. Because of this, we only need to keep track of empty field
519 // subobjects with offsets less than the size of the largest empty
520 // subobject for our class.
521 if (ElementOffset >= SizeOfLargestEmptySubobject)
522 return;
523
Anders Carlssondb319762010-05-27 18:20:57 +0000524 UpdateEmptyFieldSubobjects(RD, RD, ElementOffset);
Ken Dyckc8ae5502011-02-09 01:59:34 +0000525 ElementOffset += Layout.getSize();
Anders Carlssondb319762010-05-27 18:20:57 +0000526 }
527 }
528}
529
John McCalle42a3362012-05-01 08:55:32 +0000530typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> ClassSetTy;
531
Anders Carlssonc2226202010-05-26 05:58:59 +0000532class RecordLayoutBuilder {
Charles Davisc2c576a2010-08-19 00:55:19 +0000533protected:
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000534 // FIXME: Remove this and make the appropriate fields public.
535 friend class clang::ASTContext;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000536
Jay Foad39c79802011-01-12 09:06:06 +0000537 const ASTContext &Context;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000538
Anders Carlssonf58de112010-05-26 15:32:58 +0000539 EmptySubobjectMap *EmptySubobjects;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000540
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000541 /// Size - The current size of the record layout.
542 uint64_t Size;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000543
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000544 /// Alignment - The current alignment of the record layout.
Ken Dyck4731d5b2011-02-16 02:05:21 +0000545 CharUnits Alignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000546
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000547 /// \brief The alignment if attribute packed is not used.
Ken Dyck1300b3b2011-02-16 02:11:31 +0000548 CharUnits UnpackedAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000549
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000550 SmallVector<uint64_t, 16> FieldOffsets;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000551
Douglas Gregore9fc3772012-01-26 07:55:45 +0000552 /// \brief Whether the external AST source has provided a layout for this
553 /// record.
554 unsigned ExternalLayout : 1;
Douglas Gregor44ba7892012-01-28 00:53:29 +0000555
556 /// \brief Whether we need to infer alignment, even when we have an
557 /// externally-provided layout.
558 unsigned InferAlignment : 1;
Douglas Gregore9fc3772012-01-26 07:55:45 +0000559
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000560 /// Packed - Whether the record is packed or not.
Daniel Dunbar6da10982010-05-27 05:45:51 +0000561 unsigned Packed : 1;
562
563 unsigned IsUnion : 1;
564
565 unsigned IsMac68kAlign : 1;
Fariborz Jahanianbcb23a12011-04-26 23:52:16 +0000566
567 unsigned IsMsStruct : 1;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000568
Eli Friedman2782dac2013-06-26 20:50:34 +0000569 /// UnfilledBitsInLastUnit - If the last field laid out was a bitfield,
570 /// this contains the number of bits in the last unit that can be used for
571 /// an adjacent bitfield if necessary. The unit in question is usually
572 /// a byte, but larger units are used if IsMsStruct.
573 unsigned char UnfilledBitsInLastUnit;
574 /// LastBitfieldTypeSize - If IsMsStruct, represents the size of the type
575 /// of the previous field if it was a bitfield.
576 unsigned char LastBitfieldTypeSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000577
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000578 /// MaxFieldAlignment - The maximum allowed field alignment. This is set by
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000579 /// #pragma pack.
Ken Dyck02ced6f2011-02-17 01:49:42 +0000580 CharUnits MaxFieldAlignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000581
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000582 /// DataSize - The data size of the record being laid out.
583 uint64_t DataSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000584
Ken Dyckaf1c83f2011-02-16 01:52:01 +0000585 CharUnits NonVirtualSize;
Ken Dycka2d3dda2011-02-16 01:43:15 +0000586 CharUnits NonVirtualAlignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000587
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000588 /// PrimaryBase - the primary base class (if one exists) of the class
589 /// we're laying out.
590 const CXXRecordDecl *PrimaryBase;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000591
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000592 /// PrimaryBaseIsVirtual - Whether the primary base of the class we're laying
593 /// out is virtual.
594 bool PrimaryBaseIsVirtual;
595
John McCalle42a3362012-05-01 08:55:32 +0000596 /// HasOwnVFPtr - Whether the class provides its own vtable/vftbl
597 /// pointer, as opposed to inheriting one from a primary base class.
598 bool HasOwnVFPtr;
Eli Friedman43114f92011-10-21 22:49:56 +0000599
Anders Carlsson22f57202010-10-31 21:01:46 +0000600 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000601
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000602 /// Bases - base classes and their offsets in the record.
603 BaseOffsetsMapTy Bases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000604
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000605 // VBases - virtual base classes and their offsets in the record.
John McCalle42a3362012-05-01 08:55:32 +0000606 ASTRecordLayout::VBaseOffsetsMapTy VBases;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000607
608 /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are
609 /// primary base classes for some other direct or indirect base class.
Anders Carlsson5adde292010-11-24 22:55:48 +0000610 CXXIndirectPrimaryBaseSet IndirectPrimaryBases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000611
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000612 /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in
613 /// inheritance graph order. Used for determining the primary base class.
614 const CXXRecordDecl *FirstNearlyEmptyVBase;
615
616 /// VisitedVirtualBases - A set of all the visited virtual bases, used to
617 /// avoid visiting virtual bases more than once.
618 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000619
Douglas Gregore9fc3772012-01-26 07:55:45 +0000620 /// \brief Externally-provided size.
621 uint64_t ExternalSize;
622
623 /// \brief Externally-provided alignment.
624 uint64_t ExternalAlign;
625
626 /// \brief Externally-provided field offsets.
627 llvm::DenseMap<const FieldDecl *, uint64_t> ExternalFieldOffsets;
628
629 /// \brief Externally-provided direct, non-virtual base offsets.
630 llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalBaseOffsets;
631
632 /// \brief Externally-provided virtual base offsets.
633 llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalVirtualBaseOffsets;
634
John McCall0153cd32011-11-08 04:01:03 +0000635 RecordLayoutBuilder(const ASTContext &Context,
636 EmptySubobjectMap *EmptySubobjects)
Ken Dyck4731d5b2011-02-16 02:05:21 +0000637 : Context(Context), EmptySubobjects(EmptySubobjects), Size(0),
John McCall0153cd32011-11-08 04:01:03 +0000638 Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()),
Douglas Gregor44ba7892012-01-28 00:53:29 +0000639 ExternalLayout(false), InferAlignment(false),
640 Packed(false), IsUnion(false), IsMac68kAlign(false), IsMsStruct(false),
Eli Friedman2782dac2013-06-26 20:50:34 +0000641 UnfilledBitsInLastUnit(0), LastBitfieldTypeSize(0),
642 MaxFieldAlignment(CharUnits::Zero()),
Ken Dyck02ced6f2011-02-17 01:49:42 +0000643 DataSize(0), NonVirtualSize(CharUnits::Zero()),
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000644 NonVirtualAlignment(CharUnits::One()),
Eli Friedman481673f2013-06-26 23:47:39 +0000645 PrimaryBase(0), PrimaryBaseIsVirtual(false),
John McCalle42a3362012-05-01 08:55:32 +0000646 HasOwnVFPtr(false),
Eli Friedman84d2d3a2011-09-27 19:12:27 +0000647 FirstNearlyEmptyVBase(0) { }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000648
John McCall0153cd32011-11-08 04:01:03 +0000649 /// Reset this RecordLayoutBuilder to a fresh state, using the given
650 /// alignment as the initial alignment. This is used for the
651 /// correct layout of vb-table pointers in MSVC.
652 void resetWithTargetAlignment(CharUnits TargetAlignment) {
653 const ASTContext &Context = this->Context;
654 EmptySubobjectMap *EmptySubobjects = this->EmptySubobjects;
655 this->~RecordLayoutBuilder();
656 new (this) RecordLayoutBuilder(Context, EmptySubobjects);
657 Alignment = UnpackedAlignment = TargetAlignment;
658 }
659
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000660 void Layout(const RecordDecl *D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000661 void Layout(const CXXRecordDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000662 void Layout(const ObjCInterfaceDecl *D);
663
664 void LayoutFields(const RecordDecl *D);
665 void LayoutField(const FieldDecl *D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000666 void LayoutWideBitField(uint64_t FieldSize, uint64_t TypeSize,
667 bool FieldPacked, const FieldDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000668 void LayoutBitField(const FieldDecl *D);
John McCall0153cd32011-11-08 04:01:03 +0000669
John McCall359b8852013-01-25 22:30:49 +0000670 TargetCXXABI getCXXABI() const {
671 return Context.getTargetInfo().getCXXABI();
672 }
673
Anders Carlssone3c24c72010-05-29 17:35:14 +0000674 /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects.
675 llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator;
676
677 typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *>
678 BaseSubobjectInfoMapTy;
679
680 /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases
681 /// of the class we're laying out to their base subobject info.
682 BaseSubobjectInfoMapTy VirtualBaseInfo;
683
684 /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the
685 /// class we're laying out to their base subobject info.
686 BaseSubobjectInfoMapTy NonVirtualBaseInfo;
687
688 /// ComputeBaseSubobjectInfo - Compute the base subobject information for the
689 /// bases of the given class.
690 void ComputeBaseSubobjectInfo(const CXXRecordDecl *RD);
691
692 /// ComputeBaseSubobjectInfo - Compute the base subobject information for a
693 /// single class and all of its base classes.
694 BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
695 bool IsVirtual,
696 BaseSubobjectInfo *Derived);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000697
698 /// DeterminePrimaryBase - Determine the primary base of the given class.
699 void DeterminePrimaryBase(const CXXRecordDecl *RD);
700
701 void SelectPrimaryVBase(const CXXRecordDecl *RD);
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000702
Eli Friedman43114f92011-10-21 22:49:56 +0000703 void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign);
Charles Davisc2c576a2010-08-19 00:55:19 +0000704
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000705 /// LayoutNonVirtualBases - Determines the primary base class (if any) and
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000706 /// lays it out. Will then proceed to lay out all non-virtual base clasess.
707 void LayoutNonVirtualBases(const CXXRecordDecl *RD);
708
709 /// LayoutNonVirtualBase - Lays out a single non-virtual base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +0000710 void LayoutNonVirtualBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000711
Anders Carlssona2f8e412010-10-31 22:20:42 +0000712 void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
713 CharUnits Offset);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000714
715 /// LayoutVirtualBases - Lays out all the virtual bases.
716 void LayoutVirtualBases(const CXXRecordDecl *RD,
717 const CXXRecordDecl *MostDerivedClass);
718
719 /// LayoutVirtualBase - Lays out a single virtual base.
Warren Hunt55d8e822013-10-23 23:53:07 +0000720 void LayoutVirtualBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000721
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000722 /// LayoutBase - Will lay out a base and return the offset where it was
Anders Carlssona2f8e412010-10-31 22:20:42 +0000723 /// placed, in chars.
724 CharUnits LayoutBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000725
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000726 /// InitializeLayout - Initialize record layout for the given record decl.
Daniel Dunbar6da10982010-05-27 05:45:51 +0000727 void InitializeLayout(const Decl *D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000728
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000729 /// FinishLayout - Finalize record layout. Adjust record size based on the
730 /// alignment.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000731 void FinishLayout(const NamedDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000732
Ken Dyck85ef0432011-02-19 18:58:07 +0000733 void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment);
734 void UpdateAlignment(CharUnits NewAlignment) {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000735 UpdateAlignment(NewAlignment, NewAlignment);
736 }
737
Douglas Gregor44ba7892012-01-28 00:53:29 +0000738 /// \brief Retrieve the externally-supplied field offset for the given
739 /// field.
740 ///
741 /// \param Field The field whose offset is being queried.
742 /// \param ComputedOffset The offset that we've computed for this field.
743 uint64_t updateExternalFieldOffset(const FieldDecl *Field,
744 uint64_t ComputedOffset);
745
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000746 void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset,
747 uint64_t UnpackedOffset, unsigned UnpackedAlign,
748 bool isPacked, const FieldDecl *D);
749
750 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000751
Ken Dyckecfc7552011-02-24 01:13:28 +0000752 CharUnits getSize() const {
Ken Dyck3c215f22011-02-24 01:33:05 +0000753 assert(Size % Context.getCharWidth() == 0);
Ken Dyckecfc7552011-02-24 01:13:28 +0000754 return Context.toCharUnitsFromBits(Size);
755 }
756 uint64_t getSizeInBits() const { return Size; }
757
758 void setSize(CharUnits NewSize) { Size = Context.toBits(NewSize); }
759 void setSize(uint64_t NewSize) { Size = NewSize; }
760
Eli Friedman84d2d3a2011-09-27 19:12:27 +0000761 CharUnits getAligment() const { return Alignment; }
762
Ken Dyckecfc7552011-02-24 01:13:28 +0000763 CharUnits getDataSize() const {
Ken Dyck3c215f22011-02-24 01:33:05 +0000764 assert(DataSize % Context.getCharWidth() == 0);
Ken Dyckecfc7552011-02-24 01:13:28 +0000765 return Context.toCharUnitsFromBits(DataSize);
766 }
767 uint64_t getDataSizeInBits() const { return DataSize; }
768
769 void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); }
770 void setDataSize(uint64_t NewSize) { DataSize = NewSize; }
771
Dmitri Gribenkoa664e5b2012-09-15 20:20:27 +0000772 RecordLayoutBuilder(const RecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
773 void operator=(const RecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000774};
Benjamin Kramerc7656cd2010-05-26 09:58:31 +0000775} // end anonymous namespace
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000776
Anders Carlsson81430692009-09-22 03:02:06 +0000777void
Anders Carlssonc2226202010-05-26 05:58:59 +0000778RecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000779 for (const auto &I : RD->bases()) {
780 assert(!I.getType()->isDependentType() &&
Sebastian Redl1054fae2009-10-25 17:03:50 +0000781 "Cannot layout class with dependent bases.");
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000782
Mike Stump11289f42009-09-09 15:08:12 +0000783 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +0000784 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000785
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000786 // Check if this is a nearly empty virtual base.
Aaron Ballman574705e2014-03-13 15:41:46 +0000787 if (I.isVirtual() && Context.isNearlyEmpty(Base)) {
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000788 // If it's not an indirect primary base, then we've found our primary
789 // base.
Anders Carlsson81430692009-09-22 03:02:06 +0000790 if (!IndirectPrimaryBases.count(Base)) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000791 PrimaryBase = Base;
792 PrimaryBaseIsVirtual = true;
Mike Stump6f3793b2009-08-12 21:50:08 +0000793 return;
794 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000795
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000796 // Is this the first nearly empty virtual base?
797 if (!FirstNearlyEmptyVBase)
798 FirstNearlyEmptyVBase = Base;
Mike Stump6f3793b2009-08-12 21:50:08 +0000799 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000800
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000801 SelectPrimaryVBase(Base);
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000802 if (PrimaryBase)
Zhongxing Xuec345b72010-02-15 04:28:35 +0000803 return;
Mike Stump6f3793b2009-08-12 21:50:08 +0000804 }
805}
806
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000807/// DeterminePrimaryBase - Determine the primary base of the given class.
Anders Carlssonc2226202010-05-26 05:58:59 +0000808void RecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) {
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000809 // If the class isn't dynamic, it won't have a primary base.
810 if (!RD->isDynamicClass())
811 return;
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000812
Anders Carlsson81430692009-09-22 03:02:06 +0000813 // Compute all the primary virtual bases for all of our direct and
Mike Stump590a7c72009-08-13 23:26:06 +0000814 // indirect bases, and record all their primary virtual base classes.
Anders Carlsson5adde292010-11-24 22:55:48 +0000815 RD->getIndirectPrimaryBases(IndirectPrimaryBases);
Mike Stump590a7c72009-08-13 23:26:06 +0000816
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000817 // If the record has a dynamic base class, attempt to choose a primary base
818 // class. It is the first (in direct base class order) non-virtual dynamic
Anders Carlsson81430692009-09-22 03:02:06 +0000819 // base class, if one exists.
Aaron Ballman574705e2014-03-13 15:41:46 +0000820 for (const auto &I : RD->bases()) {
Anders Carlsson03ff3792009-11-27 22:05:05 +0000821 // Ignore virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000822 if (I.isVirtual())
Anders Carlsson03ff3792009-11-27 22:05:05 +0000823 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000824
Anders Carlsson03ff3792009-11-27 22:05:05 +0000825 const CXXRecordDecl *Base =
Aaron Ballman574705e2014-03-13 15:41:46 +0000826 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlsson03ff3792009-11-27 22:05:05 +0000827
Warren Hunt55d8e822013-10-23 23:53:07 +0000828 if (Base->isDynamicClass()) {
Anders Carlsson03ff3792009-11-27 22:05:05 +0000829 // We found it.
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000830 PrimaryBase = Base;
831 PrimaryBaseIsVirtual = false;
Anders Carlsson03ff3792009-11-27 22:05:05 +0000832 return;
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000833 }
834 }
835
Eli Friedman5e9534b2011-10-18 00:55:28 +0000836 // Under the Itanium ABI, if there is no non-virtual primary base class,
837 // try to compute the primary virtual base. The primary virtual base is
838 // the first nearly empty virtual base that is not an indirect primary
839 // virtual base class, if one exists.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000840 if (RD->getNumVBases() != 0) {
841 SelectPrimaryVBase(RD);
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000842 if (PrimaryBase)
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000843 return;
844 }
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000845
Eli Friedman5e9534b2011-10-18 00:55:28 +0000846 // Otherwise, it is the first indirect primary base class, if one exists.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000847 if (FirstNearlyEmptyVBase) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000848 PrimaryBase = FirstNearlyEmptyVBase;
849 PrimaryBaseIsVirtual = true;
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000850 return;
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000851 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000852
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000853 assert(!PrimaryBase && "Should not get here with a primary base!");
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000854}
855
Anders Carlssone3c24c72010-05-29 17:35:14 +0000856BaseSubobjectInfo *
857RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
858 bool IsVirtual,
859 BaseSubobjectInfo *Derived) {
860 BaseSubobjectInfo *Info;
861
862 if (IsVirtual) {
863 // Check if we already have info about this virtual base.
864 BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD];
865 if (InfoSlot) {
866 assert(InfoSlot->Class == RD && "Wrong class for virtual base info!");
867 return InfoSlot;
868 }
869
870 // We don't, create it.
871 InfoSlot = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
872 Info = InfoSlot;
873 } else {
874 Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
875 }
876
877 Info->Class = RD;
878 Info->IsVirtual = IsVirtual;
879 Info->Derived = 0;
880 Info->PrimaryVirtualBaseInfo = 0;
881
882 const CXXRecordDecl *PrimaryVirtualBase = 0;
883 BaseSubobjectInfo *PrimaryVirtualBaseInfo = 0;
884
885 // Check if this base has a primary virtual base.
886 if (RD->getNumVBases()) {
887 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlsson7f95cd12010-11-24 23:12:57 +0000888 if (Layout.isPrimaryBaseVirtual()) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000889 // This base does have a primary virtual base.
890 PrimaryVirtualBase = Layout.getPrimaryBase();
891 assert(PrimaryVirtualBase && "Didn't have a primary virtual base!");
892
893 // Now check if we have base subobject info about this primary base.
894 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
895
896 if (PrimaryVirtualBaseInfo) {
897 if (PrimaryVirtualBaseInfo->Derived) {
898 // We did have info about this primary base, and it turns out that it
899 // has already been claimed as a primary virtual base for another
900 // base.
901 PrimaryVirtualBase = 0;
902 } else {
903 // We can claim this base as our primary base.
904 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
905 PrimaryVirtualBaseInfo->Derived = Info;
906 }
907 }
908 }
909 }
910
911 // Now go through all direct bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000912 for (const auto &I : RD->bases()) {
913 bool IsVirtual = I.isVirtual();
Anders Carlssone3c24c72010-05-29 17:35:14 +0000914
915 const CXXRecordDecl *BaseDecl =
Aaron Ballman574705e2014-03-13 15:41:46 +0000916 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlssone3c24c72010-05-29 17:35:14 +0000917
918 Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info));
919 }
920
921 if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) {
922 // Traversing the bases must have created the base info for our primary
923 // virtual base.
924 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
925 assert(PrimaryVirtualBaseInfo &&
926 "Did not create a primary virtual base!");
927
928 // Claim the primary virtual base as our primary virtual base.
929 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
930 PrimaryVirtualBaseInfo->Derived = Info;
931 }
932
933 return Info;
934}
935
936void RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000937 for (const auto &I : RD->bases()) {
938 bool IsVirtual = I.isVirtual();
Anders Carlssone3c24c72010-05-29 17:35:14 +0000939
940 const CXXRecordDecl *BaseDecl =
Aaron Ballman574705e2014-03-13 15:41:46 +0000941 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlssone3c24c72010-05-29 17:35:14 +0000942
943 // Compute the base subobject info for this base.
944 BaseSubobjectInfo *Info = ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, 0);
945
946 if (IsVirtual) {
947 // ComputeBaseInfo has already added this base for us.
948 assert(VirtualBaseInfo.count(BaseDecl) &&
949 "Did not add virtual base!");
950 } else {
951 // Add the base info to the map of non-virtual bases.
952 assert(!NonVirtualBaseInfo.count(BaseDecl) &&
953 "Non-virtual base already exists!");
954 NonVirtualBaseInfo.insert(std::make_pair(BaseDecl, Info));
955 }
956 }
957}
958
Anders Carlsson09ffa322010-03-10 22:21:28 +0000959void
Eli Friedman43114f92011-10-21 22:49:56 +0000960RecordLayoutBuilder::EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign) {
Eli Friedman5e9534b2011-10-18 00:55:28 +0000961 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
962
963 // The maximum field alignment overrides base align.
964 if (!MaxFieldAlignment.isZero()) {
965 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
966 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
967 }
968
969 // Round up the current record size to pointer alignment.
Eli Friedman43114f92011-10-21 22:49:56 +0000970 setSize(getSize().RoundUpToAlignment(BaseAlign));
971 setDataSize(getSize());
Eli Friedman5e9534b2011-10-18 00:55:28 +0000972
973 // Update the alignment.
974 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
975}
976
977void
Anders Carlssonc2226202010-05-26 05:58:59 +0000978RecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl *RD) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000979 // Then, determine the primary base class.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000980 DeterminePrimaryBase(RD);
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000981
Anders Carlssone3c24c72010-05-29 17:35:14 +0000982 // Compute base subobject info.
983 ComputeBaseSubobjectInfo(RD);
984
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000985 // If we have a primary base class, lay it out.
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000986 if (PrimaryBase) {
987 if (PrimaryBaseIsVirtual) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000988 // If the primary virtual base was a primary virtual base of some other
989 // base class we'll have to steal it.
990 BaseSubobjectInfo *PrimaryBaseInfo = VirtualBaseInfo.lookup(PrimaryBase);
991 PrimaryBaseInfo->Derived = 0;
992
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000993 // We have a virtual primary base, insert it as an indirect primary base.
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000994 IndirectPrimaryBases.insert(PrimaryBase);
Anders Carlssonfe900962010-03-11 05:42:17 +0000995
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000996 assert(!VisitedVirtualBases.count(PrimaryBase) &&
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000997 "vbase already visited!");
998 VisitedVirtualBases.insert(PrimaryBase);
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000999
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001000 LayoutVirtualBase(PrimaryBaseInfo);
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001001 } else {
1002 BaseSubobjectInfo *PrimaryBaseInfo =
1003 NonVirtualBaseInfo.lookup(PrimaryBase);
1004 assert(PrimaryBaseInfo &&
1005 "Did not find base info for non-virtual primary base!");
1006
1007 LayoutNonVirtualBase(PrimaryBaseInfo);
1008 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001009
John McCall0153cd32011-11-08 04:01:03 +00001010 // If this class needs a vtable/vf-table and didn't get one from a
1011 // primary base, add it in now.
Warren Hunt55d8e822013-10-23 23:53:07 +00001012 } else if (RD->isDynamicClass()) {
Eli Friedman5e9534b2011-10-18 00:55:28 +00001013 assert(DataSize == 0 && "Vtable pointer must be at offset zero!");
Eli Friedman5e9534b2011-10-18 00:55:28 +00001014 CharUnits PtrWidth =
1015 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Eli Friedman43114f92011-10-21 22:49:56 +00001016 CharUnits PtrAlign =
1017 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
1018 EnsureVTablePointerAlignment(PtrAlign);
John McCalle42a3362012-05-01 08:55:32 +00001019 HasOwnVFPtr = true;
Eli Friedman5e9534b2011-10-18 00:55:28 +00001020 setSize(getSize() + PtrWidth);
1021 setDataSize(getSize());
1022 }
1023
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001024 // Now lay out the non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001025 for (const auto &I : RD->bases()) {
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001026
Benjamin Kramer273670a2013-10-25 07:40:50 +00001027 // Ignore virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001028 if (I.isVirtual())
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001029 continue;
1030
Aaron Ballman574705e2014-03-13 15:41:46 +00001031 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001032
John McCall0153cd32011-11-08 04:01:03 +00001033 // Skip the primary base, because we've already laid it out. The
1034 // !PrimaryBaseIsVirtual check is required because we might have a
1035 // non-virtual base of the same type as a primary virtual base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001036 if (BaseDecl == PrimaryBase && !PrimaryBaseIsVirtual)
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001037 continue;
1038
1039 // Lay out the base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001040 BaseSubobjectInfo *BaseInfo = NonVirtualBaseInfo.lookup(BaseDecl);
1041 assert(BaseInfo && "Did not find base info for non-virtual base!");
1042
1043 LayoutNonVirtualBase(BaseInfo);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001044 }
1045}
1046
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001047void RecordLayoutBuilder::LayoutNonVirtualBase(const BaseSubobjectInfo *Base) {
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001048 // Layout the base.
Anders Carlssona2f8e412010-10-31 22:20:42 +00001049 CharUnits Offset = LayoutBase(Base);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001050
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001051 // Add its base class offset.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001052 assert(!Bases.count(Base->Class) && "base offset already exists!");
Anders Carlssona2f8e412010-10-31 22:20:42 +00001053 Bases.insert(std::make_pair(Base->Class, Offset));
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001054
1055 AddPrimaryVirtualBaseOffsets(Base, Offset);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001056}
Mike Stump2b84dd32009-11-05 04:02:15 +00001057
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001058void
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001059RecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
Anders Carlssona2f8e412010-10-31 22:20:42 +00001060 CharUnits Offset) {
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001061 // This base isn't interesting, it has no virtual bases.
1062 if (!Info->Class->getNumVBases())
1063 return;
1064
1065 // First, check if we have a virtual primary base to add offsets for.
1066 if (Info->PrimaryVirtualBaseInfo) {
1067 assert(Info->PrimaryVirtualBaseInfo->IsVirtual &&
1068 "Primary virtual base is not virtual!");
1069 if (Info->PrimaryVirtualBaseInfo->Derived == Info) {
1070 // Add the offset.
1071 assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) &&
1072 "primary vbase offset already exists!");
1073 VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class,
John McCalle42a3362012-05-01 08:55:32 +00001074 ASTRecordLayout::VBaseInfo(Offset, false)));
Anders Carlssonea7b1822010-04-15 16:12:58 +00001075
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001076 // Traverse the primary virtual base.
1077 AddPrimaryVirtualBaseOffsets(Info->PrimaryVirtualBaseInfo, Offset);
1078 }
Anders Carlssonea7b1822010-04-15 16:12:58 +00001079 }
1080
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001081 // Now go through all direct non-virtual bases.
1082 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
1083 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
1084 const BaseSubobjectInfo *Base = Info->Bases[I];
1085 if (Base->IsVirtual)
Anders Carlssonea7b1822010-04-15 16:12:58 +00001086 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001087
Anders Carlsson0a14ee92010-11-01 00:21:58 +00001088 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001089 AddPrimaryVirtualBaseOffsets(Base, BaseOffset);
Anders Carlssonea7b1822010-04-15 16:12:58 +00001090 }
1091}
1092
1093void
Anders Carlssonc2226202010-05-26 05:58:59 +00001094RecordLayoutBuilder::LayoutVirtualBases(const CXXRecordDecl *RD,
Anders Carlssonea7b1822010-04-15 16:12:58 +00001095 const CXXRecordDecl *MostDerivedClass) {
Anders Carlssonde710c92010-03-11 04:33:54 +00001096 const CXXRecordDecl *PrimaryBase;
Anders Carlsson291279e2010-04-10 18:42:27 +00001097 bool PrimaryBaseIsVirtual;
Anders Carlssonfe900962010-03-11 05:42:17 +00001098
Anders Carlsson291279e2010-04-10 18:42:27 +00001099 if (MostDerivedClass == RD) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +00001100 PrimaryBase = this->PrimaryBase;
1101 PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual;
Anders Carlsson291279e2010-04-10 18:42:27 +00001102 } else {
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001103 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlssonde710c92010-03-11 04:33:54 +00001104 PrimaryBase = Layout.getPrimaryBase();
Anders Carlsson7f95cd12010-11-24 23:12:57 +00001105 PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
Anders Carlsson291279e2010-04-10 18:42:27 +00001106 }
1107
Aaron Ballman574705e2014-03-13 15:41:46 +00001108 for (const auto &I : RD->bases()) {
1109 assert(!I.getType()->isDependentType() &&
Sebastian Redl1054fae2009-10-25 17:03:50 +00001110 "Cannot layout class with dependent bases.");
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001111
Aaron Ballman574705e2014-03-13 15:41:46 +00001112 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001113
Aaron Ballman574705e2014-03-13 15:41:46 +00001114 if (I.isVirtual()) {
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001115 if (PrimaryBase != BaseDecl || !PrimaryBaseIsVirtual) {
1116 bool IndirectPrimaryBase = IndirectPrimaryBases.count(BaseDecl);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001117
Anders Carlsson291279e2010-04-10 18:42:27 +00001118 // Only lay out the virtual base if it's not an indirect primary base.
1119 if (!IndirectPrimaryBase) {
1120 // Only visit virtual bases once.
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001121 if (!VisitedVirtualBases.insert(BaseDecl))
Anders Carlsson291279e2010-04-10 18:42:27 +00001122 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001123
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001124 const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1125 assert(BaseInfo && "Did not find virtual base info!");
1126 LayoutVirtualBase(BaseInfo);
Anders Carlsson6a848892010-03-11 04:10:39 +00001127 }
Mike Stump2b84dd32009-11-05 04:02:15 +00001128 }
Mike Stumpc2f591b2009-08-13 22:53:07 +00001129 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001130
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001131 if (!BaseDecl->getNumVBases()) {
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001132 // This base isn't interesting since it doesn't have any virtual bases.
1133 continue;
Mike Stump996576f32009-08-16 19:04:13 +00001134 }
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001135
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001136 LayoutVirtualBases(BaseDecl, MostDerivedClass);
Mike Stump6b2556f2009-08-06 13:41:24 +00001137 }
1138}
1139
Warren Hunt55d8e822013-10-23 23:53:07 +00001140void RecordLayoutBuilder::LayoutVirtualBase(const BaseSubobjectInfo *Base) {
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001141 assert(!Base->Derived && "Trying to lay out a primary virtual base!");
1142
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001143 // Layout the base.
Anders Carlssona2f8e412010-10-31 22:20:42 +00001144 CharUnits Offset = LayoutBase(Base);
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001145
1146 // Add its base class offset.
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001147 assert(!VBases.count(Base->Class) && "vbase offset already exists!");
John McCalle42a3362012-05-01 08:55:32 +00001148 VBases.insert(std::make_pair(Base->Class,
Warren Hunt55d8e822013-10-23 23:53:07 +00001149 ASTRecordLayout::VBaseInfo(Offset, false)));
John McCalle42a3362012-05-01 08:55:32 +00001150
Warren Hunt55d8e822013-10-23 23:53:07 +00001151 AddPrimaryVirtualBaseOffsets(Base, Offset);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001152}
1153
Anders Carlssona2f8e412010-10-31 22:20:42 +00001154CharUnits RecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) {
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001155 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001156
Douglas Gregore9fc3772012-01-26 07:55:45 +00001157
1158 CharUnits Offset;
1159
1160 // Query the external layout to see if it provides an offset.
1161 bool HasExternalLayout = false;
1162 if (ExternalLayout) {
1163 llvm::DenseMap<const CXXRecordDecl *, CharUnits>::iterator Known;
1164 if (Base->IsVirtual) {
1165 Known = ExternalVirtualBaseOffsets.find(Base->Class);
1166 if (Known != ExternalVirtualBaseOffsets.end()) {
1167 Offset = Known->second;
1168 HasExternalLayout = true;
1169 }
1170 } else {
1171 Known = ExternalBaseOffsets.find(Base->Class);
1172 if (Known != ExternalBaseOffsets.end()) {
1173 Offset = Known->second;
1174 HasExternalLayout = true;
1175 }
1176 }
1177 }
1178
Warren Huntd640d7d2014-01-09 00:30:56 +00001179 CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlignment();
Eli Friedman69d27d22013-07-16 00:21:28 +00001180 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
1181
Anders Carlsson09ffa322010-03-10 22:21:28 +00001182 // If we have an empty base class, try to place it at offset 0.
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001183 if (Base->Class->isEmpty() &&
Douglas Gregore9fc3772012-01-26 07:55:45 +00001184 (!HasExternalLayout || Offset == CharUnits::Zero()) &&
Anders Carlsson28466ab2010-10-31 22:13:23 +00001185 EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) {
Ken Dyck1b4420e2011-02-28 02:01:38 +00001186 setSize(std::max(getSize(), Layout.getSize()));
Eli Friedman69d27d22013-07-16 00:21:28 +00001187 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001188
Anders Carlssona2f8e412010-10-31 22:20:42 +00001189 return CharUnits::Zero();
Anders Carlsson09ffa322010-03-10 22:21:28 +00001190 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001191
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001192 // The maximum field alignment overrides base align.
Ken Dyck02ced6f2011-02-17 01:49:42 +00001193 if (!MaxFieldAlignment.isZero()) {
Ken Dyck85ef0432011-02-19 18:58:07 +00001194 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1195 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001196 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001197
Douglas Gregore9fc3772012-01-26 07:55:45 +00001198 if (!HasExternalLayout) {
1199 // Round up the current record size to the base's alignment boundary.
1200 Offset = getDataSize().RoundUpToAlignment(BaseAlign);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001201
Douglas Gregore9fc3772012-01-26 07:55:45 +00001202 // Try to place the base.
1203 while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset))
1204 Offset += BaseAlign;
1205 } else {
1206 bool Allowed = EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset);
1207 (void)Allowed;
1208 assert(Allowed && "Base subobject externally placed at overlapping offset");
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001209
1210 if (InferAlignment && Offset < getDataSize().RoundUpToAlignment(BaseAlign)){
1211 // The externally-supplied base offset is before the base offset we
1212 // computed. Assume that the structure is packed.
1213 Alignment = CharUnits::One();
1214 InferAlignment = false;
1215 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001216 }
1217
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001218 if (!Base->Class->isEmpty()) {
Anders Carlsson09ffa322010-03-10 22:21:28 +00001219 // Update the data size.
Ken Dyck1b4420e2011-02-28 02:01:38 +00001220 setDataSize(Offset + Layout.getNonVirtualSize());
Anders Carlsson09ffa322010-03-10 22:21:28 +00001221
Ken Dyck1b4420e2011-02-28 02:01:38 +00001222 setSize(std::max(getSize(), getDataSize()));
Anders Carlsson09ffa322010-03-10 22:21:28 +00001223 } else
Ken Dyck1b4420e2011-02-28 02:01:38 +00001224 setSize(std::max(getSize(), Offset + Layout.getSize()));
Anders Carlsson09ffa322010-03-10 22:21:28 +00001225
1226 // Remember max struct/class alignment.
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001227 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001228
Ken Dyck1b4420e2011-02-28 02:01:38 +00001229 return Offset;
Anders Carlsson09ffa322010-03-10 22:21:28 +00001230}
1231
Daniel Dunbar6da10982010-05-27 05:45:51 +00001232void RecordLayoutBuilder::InitializeLayout(const Decl *D) {
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001233 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Daniel Dunbar6da10982010-05-27 05:45:51 +00001234 IsUnion = RD->isUnion();
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001235 IsMsStruct = RD->isMsStruct(Context);
1236 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001237
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001238 Packed = D->hasAttr<PackedAttr>();
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001239
Daniel Dunbar096ed292011-10-05 21:04:55 +00001240 // Honor the default struct packing maximum alignment flag.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001241 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) {
Daniel Dunbar096ed292011-10-05 21:04:55 +00001242 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
1243 }
1244
Daniel Dunbar6da10982010-05-27 05:45:51 +00001245 // mac68k alignment supersedes maximum field alignment and attribute aligned,
1246 // and forces all structures to have 2-byte alignment. The IBM docs on it
1247 // allude to additional (more complicated) semantics, especially with regard
1248 // to bit-fields, but gcc appears not to follow that.
1249 if (D->hasAttr<AlignMac68kAttr>()) {
1250 IsMac68kAlign = true;
Ken Dyck02ced6f2011-02-17 01:49:42 +00001251 MaxFieldAlignment = CharUnits::fromQuantity(2);
Ken Dyck4731d5b2011-02-16 02:05:21 +00001252 Alignment = CharUnits::fromQuantity(2);
Daniel Dunbar6da10982010-05-27 05:45:51 +00001253 } else {
1254 if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>())
Ken Dyck02ced6f2011-02-17 01:49:42 +00001255 MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001256
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001257 if (unsigned MaxAlign = D->getMaxAlignment())
Ken Dyck85ef0432011-02-19 18:58:07 +00001258 UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign));
Daniel Dunbar6da10982010-05-27 05:45:51 +00001259 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001260
1261 // If there is an external AST source, ask it for the various offsets.
1262 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
1263 if (ExternalASTSource *External = Context.getExternalSource()) {
1264 ExternalLayout = External->layoutRecordType(RD,
1265 ExternalSize,
1266 ExternalAlign,
1267 ExternalFieldOffsets,
1268 ExternalBaseOffsets,
1269 ExternalVirtualBaseOffsets);
1270
1271 // Update based on external alignment.
1272 if (ExternalLayout) {
Douglas Gregor44ba7892012-01-28 00:53:29 +00001273 if (ExternalAlign > 0) {
1274 Alignment = Context.toCharUnitsFromBits(ExternalAlign);
Douglas Gregor44ba7892012-01-28 00:53:29 +00001275 } else {
1276 // The external source didn't have alignment information; infer it.
1277 InferAlignment = true;
1278 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001279 }
1280 }
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001281}
Anders Carlsson6d9f6f32009-07-19 00:18:47 +00001282
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001283void RecordLayoutBuilder::Layout(const RecordDecl *D) {
1284 InitializeLayout(D);
Anders Carlsson118ce162009-07-18 21:48:39 +00001285 LayoutFields(D);
Mike Stump11289f42009-09-09 15:08:12 +00001286
Anders Carlsson79474332009-07-18 20:20:21 +00001287 // Finally, round the size of the total struct up to the alignment of the
1288 // struct itself.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001289 FinishLayout(D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001290}
1291
1292void RecordLayoutBuilder::Layout(const CXXRecordDecl *RD) {
1293 InitializeLayout(RD);
1294
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001295 // Lay out the vtable and the non-virtual bases.
1296 LayoutNonVirtualBases(RD);
1297
1298 LayoutFields(RD);
1299
Ken Dycke7380752011-03-10 01:53:59 +00001300 NonVirtualSize = Context.toCharUnitsFromBits(
1301 llvm::RoundUpToAlignment(getSizeInBits(),
Douglas Gregore8bbc122011-09-02 00:18:52 +00001302 Context.getTargetInfo().getCharAlign()));
Ken Dyck4731d5b2011-02-16 02:05:21 +00001303 NonVirtualAlignment = Alignment;
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001304
Warren Hunt55d8e822013-10-23 23:53:07 +00001305 // Lay out the virtual bases and add the primary virtual base offsets.
1306 LayoutVirtualBases(RD, RD);
John McCall0153cd32011-11-08 04:01:03 +00001307
1308 // Finally, round the size of the total struct up to the alignment
Eli Friedman83a12582011-12-01 00:37:01 +00001309 // of the struct itself.
1310 FinishLayout(RD);
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001311
Anders Carlsson5b441d72010-04-10 21:24:48 +00001312#ifndef NDEBUG
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001313 // Check that we have base offsets for all bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001314 for (const auto &I : RD->bases()) {
1315 if (I.isVirtual())
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001316 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001317
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001318 const CXXRecordDecl *BaseDecl =
Aaron Ballman574705e2014-03-13 15:41:46 +00001319 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001320
1321 assert(Bases.count(BaseDecl) && "Did not find base offset!");
1322 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001323
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001324 // And all virtual bases.
Aaron Ballman445a9392014-03-13 16:15:17 +00001325 for (const auto &I : RD->vbases()) {
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001326 const CXXRecordDecl *BaseDecl =
Aaron Ballman445a9392014-03-13 16:15:17 +00001327 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001328
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001329 assert(VBases.count(BaseDecl) && "Did not find base offset!");
Anders Carlsson5b441d72010-04-10 21:24:48 +00001330 }
1331#endif
Anders Carlsson79474332009-07-18 20:20:21 +00001332}
1333
Anders Carlssonc2226202010-05-26 05:58:59 +00001334void RecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) {
Anders Carlsson4f516282009-07-18 20:50:59 +00001335 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001336 const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD);
Anders Carlsson4f516282009-07-18 20:50:59 +00001337
Ken Dyck85ef0432011-02-19 18:58:07 +00001338 UpdateAlignment(SL.getAlignment());
Mike Stump11289f42009-09-09 15:08:12 +00001339
Anders Carlsson4f516282009-07-18 20:50:59 +00001340 // We start laying out ivars not at the end of the superclass
1341 // structure, but at the next byte following the last field.
Ken Dyckecfc7552011-02-24 01:13:28 +00001342 setSize(SL.getDataSize());
Ken Dyck1b4420e2011-02-28 02:01:38 +00001343 setDataSize(getSize());
Anders Carlsson4f516282009-07-18 20:50:59 +00001344 }
Mike Stump11289f42009-09-09 15:08:12 +00001345
Daniel Dunbar6da10982010-05-27 05:45:51 +00001346 InitializeLayout(D);
Anders Carlsson4f516282009-07-18 20:50:59 +00001347 // Layout each ivar sequentially.
Jordy Rosea91768e2011-07-22 02:08:32 +00001348 for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD;
1349 IVD = IVD->getNextIvar())
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001350 LayoutField(IVD);
Mike Stump11289f42009-09-09 15:08:12 +00001351
Anders Carlsson4f516282009-07-18 20:50:59 +00001352 // Finally, round the size of the total struct up to the alignment of the
1353 // struct itself.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001354 FinishLayout(D);
Anders Carlsson4f516282009-07-18 20:50:59 +00001355}
1356
Anders Carlssonc2226202010-05-26 05:58:59 +00001357void RecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
Anders Carlsson118ce162009-07-18 21:48:39 +00001358 // Layout each field, for now, just sequentially, respecting alignment. In
1359 // the future, this will need to be tweakable by targets.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001360 for (const auto *Field : D->fields())
1361 LayoutField(Field);
Anders Carlsson118ce162009-07-18 21:48:39 +00001362}
1363
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001364void RecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize,
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001365 uint64_t TypeSize,
1366 bool FieldPacked,
1367 const FieldDecl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001368 assert(Context.getLangOpts().CPlusPlus &&
Anders Carlsson57235162010-04-16 15:57:11 +00001369 "Can only have wide bit-fields in C++!");
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001370
Anders Carlsson57235162010-04-16 15:57:11 +00001371 // Itanium C++ ABI 2.4:
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001372 // If sizeof(T)*8 < n, let T' be the largest integral POD type with
Anders Carlsson57235162010-04-16 15:57:11 +00001373 // sizeof(T')*8 <= n.
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001374
Anders Carlsson57235162010-04-16 15:57:11 +00001375 QualType IntegralPODTypes[] = {
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001376 Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy,
Anders Carlsson57235162010-04-16 15:57:11 +00001377 Context.UnsignedLongTy, Context.UnsignedLongLongTy
1378 };
1379
Anders Carlsson57235162010-04-16 15:57:11 +00001380 QualType Type;
1381 for (unsigned I = 0, E = llvm::array_lengthof(IntegralPODTypes);
1382 I != E; ++I) {
1383 uint64_t Size = Context.getTypeSize(IntegralPODTypes[I]);
Anders Carlsson57235162010-04-16 15:57:11 +00001384
1385 if (Size > FieldSize)
1386 break;
1387
1388 Type = IntegralPODTypes[I];
1389 }
1390 assert(!Type.isNull() && "Did not find a type!");
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001391
Ken Dyckdbe37f32011-03-01 01:36:00 +00001392 CharUnits TypeAlign = Context.getTypeAlignInChars(Type);
Anders Carlsson57235162010-04-16 15:57:11 +00001393
1394 // We're not going to use any of the unfilled bits in the last byte.
Eli Friedman2782dac2013-06-26 20:50:34 +00001395 UnfilledBitsInLastUnit = 0;
1396 LastBitfieldTypeSize = 0;
Anders Carlsson57235162010-04-16 15:57:11 +00001397
Anders Carlssonaad5fa82010-04-17 20:21:41 +00001398 uint64_t FieldOffset;
Eli Friedman2782dac2013-06-26 20:50:34 +00001399 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001400
Anders Carlsson57235162010-04-16 15:57:11 +00001401 if (IsUnion) {
Ken Dyckecfc7552011-02-24 01:13:28 +00001402 setDataSize(std::max(getDataSizeInBits(), FieldSize));
Anders Carlssonaad5fa82010-04-17 20:21:41 +00001403 FieldOffset = 0;
Anders Carlsson57235162010-04-16 15:57:11 +00001404 } else {
Chad Rosiere1a6a0e2011-08-05 22:38:04 +00001405 // The bitfield is allocated starting at the next offset aligned
1406 // appropriately for T', with length n bits.
Ken Dyckdbe37f32011-03-01 01:36:00 +00001407 FieldOffset = llvm::RoundUpToAlignment(getDataSizeInBits(),
1408 Context.toBits(TypeAlign));
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001409
Anders Carlsson57235162010-04-16 15:57:11 +00001410 uint64_t NewSizeInBits = FieldOffset + FieldSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001411
Ken Dycka1a2e8d2011-03-10 02:00:35 +00001412 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
Douglas Gregore8bbc122011-09-02 00:18:52 +00001413 Context.getTargetInfo().getCharAlign()));
Eli Friedman2782dac2013-06-26 20:50:34 +00001414 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
Anders Carlsson57235162010-04-16 15:57:11 +00001415 }
1416
1417 // Place this field at the current location.
1418 FieldOffsets.push_back(FieldOffset);
1419
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001420 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset,
Ken Dyckdbe37f32011-03-01 01:36:00 +00001421 Context.toBits(TypeAlign), FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001422
Anders Carlsson57235162010-04-16 15:57:11 +00001423 // Update the size.
Ken Dyckecfc7552011-02-24 01:13:28 +00001424 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001425
Anders Carlsson57235162010-04-16 15:57:11 +00001426 // Remember max struct/class alignment.
Ken Dyckdbe37f32011-03-01 01:36:00 +00001427 UpdateAlignment(TypeAlign);
Anders Carlsson57235162010-04-16 15:57:11 +00001428}
1429
Anders Carlssonc2226202010-05-26 05:58:59 +00001430void RecordLayoutBuilder::LayoutBitField(const FieldDecl *D) {
Anders Carlsson07209442009-11-22 17:37:31 +00001431 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
Richard Smithcaf33902011-10-10 18:28:20 +00001432 uint64_t FieldSize = D->getBitWidthValue(Context);
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001433 std::pair<uint64_t, unsigned> FieldInfo = Context.getTypeInfo(D->getType());
Anders Carlsson07209442009-11-22 17:37:31 +00001434 uint64_t TypeSize = FieldInfo.first;
1435 unsigned FieldAlign = FieldInfo.second;
Eli Friedman2782dac2013-06-26 20:50:34 +00001436
John McCall30268ca2014-01-29 07:53:44 +00001437 // UnfilledBitsInLastUnit is the difference between the end of the
1438 // last allocated bitfield (i.e. the first bit offset available for
1439 // bitfields) and the end of the current data size in bits (i.e. the
1440 // first bit offset available for non-bitfields). The current data
1441 // size in bits is always a multiple of the char size; additionally,
1442 // for ms_struct records it's also a multiple of the
1443 // LastBitfieldTypeSize (if set).
1444
John McCall76e1818a2014-02-13 00:50:08 +00001445 // The struct-layout algorithm is dictated by the platform ABI,
1446 // which in principle could use almost any rules it likes. In
1447 // practice, UNIXy targets tend to inherit the algorithm described
1448 // in the System V generic ABI. The basic bitfield layout rule in
1449 // System V is to place bitfields at the next available bit offset
1450 // where the entire bitfield would fit in an aligned storage unit of
1451 // the declared type; it's okay if an earlier or later non-bitfield
1452 // is allocated in the same storage unit. However, some targets
1453 // (those that !useBitFieldTypeAlignment(), e.g. ARM APCS) don't
1454 // require this storage unit to be aligned, and therefore always put
1455 // the bitfield at the next available bit offset.
John McCall30268ca2014-01-29 07:53:44 +00001456
John McCall76e1818a2014-02-13 00:50:08 +00001457 // ms_struct basically requests a complete replacement of the
1458 // platform ABI's struct-layout algorithm, with the high-level goal
1459 // of duplicating MSVC's layout. For non-bitfields, this follows
1460 // the the standard algorithm. The basic bitfield layout rule is to
1461 // allocate an entire unit of the bitfield's declared type
1462 // (e.g. 'unsigned long'), then parcel it up among successive
1463 // bitfields whose declared types have the same size, making a new
1464 // unit as soon as the last can no longer store the whole value.
1465 // Since it completely replaces the platform ABI's algorithm,
1466 // settings like !useBitFieldTypeAlignment() do not apply.
1467
1468 // A zero-width bitfield forces the use of a new storage unit for
1469 // later bitfields. In general, this occurs by rounding up the
1470 // current size of the struct as if the algorithm were about to
1471 // place a non-bitfield of the field's formal type. Usually this
1472 // does not change the alignment of the struct itself, but it does
1473 // on some targets (those that useZeroLengthBitfieldAlignment(),
1474 // e.g. ARM). In ms_struct layout, zero-width bitfields are
1475 // ignored unless they follow a non-zero-width bitfield.
1476
1477 // A field alignment restriction (e.g. from #pragma pack) or
1478 // specification (e.g. from __attribute__((aligned))) changes the
1479 // formal alignment of the field. For System V, this alters the
1480 // required alignment of the notional storage unit that must contain
1481 // the bitfield. For ms_struct, this only affects the placement of
1482 // new storage units. In both cases, the effect of #pragma pack is
1483 // ignored on zero-width bitfields.
1484
1485 // On System V, a packed field (e.g. from #pragma pack or
1486 // __attribute__((packed))) always uses the next available bit
1487 // offset.
1488
John McCall95833f32014-02-27 20:30:49 +00001489 // In an ms_struct struct, the alignment of a fundamental type is
1490 // always equal to its size. This is necessary in order to mimic
1491 // the i386 alignment rules on targets which might not fully align
1492 // all types (e.g. Darwin PPC32, where alignof(long long) == 4).
John McCall30268ca2014-01-29 07:53:44 +00001493
1494 // First, some simple bookkeeping to perform for ms_struct structs.
Eli Friedman2782dac2013-06-26 20:50:34 +00001495 if (IsMsStruct) {
John McCall30268ca2014-01-29 07:53:44 +00001496 // The field alignment for integer types is always the size.
Fariborz Jahanian7adbed62011-05-09 22:03:17 +00001497 FieldAlign = TypeSize;
John McCall30268ca2014-01-29 07:53:44 +00001498
1499 // If the previous field was not a bitfield, or was a bitfield
1500 // with a different storage unit size, we're done with that
1501 // storage unit.
Eli Friedman2782dac2013-06-26 20:50:34 +00001502 if (LastBitfieldTypeSize != TypeSize) {
John McCall30268ca2014-01-29 07:53:44 +00001503 // Also, ignore zero-length bitfields after non-bitfields.
1504 if (!LastBitfieldTypeSize && !FieldSize)
1505 FieldAlign = 1;
1506
Eli Friedman2782dac2013-06-26 20:50:34 +00001507 UnfilledBitsInLastUnit = 0;
1508 LastBitfieldTypeSize = 0;
1509 }
1510 }
1511
John McCall30268ca2014-01-29 07:53:44 +00001512 // If the field is wider than its declared type, it follows
1513 // different rules in all cases.
Anders Carlsson57235162010-04-16 15:57:11 +00001514 if (FieldSize > TypeSize) {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001515 LayoutWideBitField(FieldSize, TypeSize, FieldPacked, D);
Anders Carlsson57235162010-04-16 15:57:11 +00001516 return;
1517 }
1518
John McCall30268ca2014-01-29 07:53:44 +00001519 // Compute the next available bit offset.
1520 uint64_t FieldOffset =
1521 IsUnion ? 0 : (getDataSizeInBits() - UnfilledBitsInLastUnit);
1522
1523 // Handle targets that don't honor bitfield type alignment.
John McCall76e1818a2014-02-13 00:50:08 +00001524 if (!IsMsStruct && !Context.getTargetInfo().useBitFieldTypeAlignment()) {
John McCall30268ca2014-01-29 07:53:44 +00001525 // Some such targets do honor it on zero-width bitfields.
1526 if (FieldSize == 0 &&
1527 Context.getTargetInfo().useZeroLengthBitfieldAlignment()) {
1528 // The alignment to round up to is the max of the field's natural
1529 // alignment and a target-specific fixed value (sometimes zero).
1530 unsigned ZeroLengthBitfieldBoundary =
1531 Context.getTargetInfo().getZeroLengthBitfieldBoundary();
1532 FieldAlign = std::max(FieldAlign, ZeroLengthBitfieldBoundary);
1533
1534 // If that doesn't apply, just ignore the field alignment.
1535 } else {
1536 FieldAlign = 1;
1537 }
1538 }
1539
1540 // Remember the alignment we would have used if the field were not packed.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001541 unsigned UnpackedFieldAlign = FieldAlign;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001542
Yunzhong Gao5fd0c9d2014-02-13 02:45:10 +00001543 // Ignore the field alignment if the field is packed unless it has zero-size.
1544 if (!IsMsStruct && FieldPacked && FieldSize != 0)
Anders Carlsson07209442009-11-22 17:37:31 +00001545 FieldAlign = 1;
Anders Carlsson07209442009-11-22 17:37:31 +00001546
John McCall30268ca2014-01-29 07:53:44 +00001547 // But, if there's an 'aligned' attribute on the field, honor that.
1548 if (unsigned ExplicitFieldAlign = D->getMaxAlignment()) {
1549 FieldAlign = std::max(FieldAlign, ExplicitFieldAlign);
1550 UnpackedFieldAlign = std::max(UnpackedFieldAlign, ExplicitFieldAlign);
1551 }
1552
1553 // But, if there's a #pragma pack in play, that takes precedent over
1554 // even the 'aligned' attribute, for non-zero-width bitfields.
1555 if (!MaxFieldAlignment.isZero() && FieldSize) {
Ken Dyck02ced6f2011-02-17 01:49:42 +00001556 unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment);
1557 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1558 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001559 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001560
John McCall30268ca2014-01-29 07:53:44 +00001561 // For purposes of diagnostics, we're going to simultaneously
1562 // compute the field offsets that we would have used if we weren't
1563 // adding any alignment padding or if the field weren't packed.
1564 uint64_t UnpaddedFieldOffset = FieldOffset;
1565 uint64_t UnpackedFieldOffset = FieldOffset;
1566
1567 // Check if we need to add padding to fit the bitfield within an
1568 // allocation unit with the right size and alignment. The rules are
1569 // somewhat different here for ms_struct structs.
1570 if (IsMsStruct) {
1571 // If it's not a zero-width bitfield, and we can fit the bitfield
1572 // into the active storage unit (and we haven't already decided to
1573 // start a new storage unit), just do so, regardless of any other
1574 // other consideration. Otherwise, round up to the right alignment.
1575 if (FieldSize == 0 || FieldSize > UnfilledBitsInLastUnit) {
1576 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
1577 UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1578 UnpackedFieldAlign);
1579 UnfilledBitsInLastUnit = 0;
1580 }
1581
1582 } else {
1583 // #pragma pack, with any value, suppresses the insertion of padding.
1584 bool AllowPadding = MaxFieldAlignment.isZero();
1585
1586 // Compute the real offset.
1587 if (FieldSize == 0 ||
1588 (AllowPadding &&
1589 (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)) {
1590 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
1591 }
1592
1593 // Repeat the computation for diagnostic purposes.
1594 if (FieldSize == 0 ||
1595 (AllowPadding &&
1596 (UnpackedFieldOffset & (UnpackedFieldAlign-1)) + FieldSize > TypeSize))
1597 UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1598 UnpackedFieldAlign);
Eli Friedman2782dac2013-06-26 20:50:34 +00001599 }
1600
John McCall30268ca2014-01-29 07:53:44 +00001601 // If we're using external layout, give the external layout a chance
1602 // to override this information.
Douglas Gregor44ba7892012-01-28 00:53:29 +00001603 if (ExternalLayout)
1604 FieldOffset = updateExternalFieldOffset(D, FieldOffset);
1605
John McCall30268ca2014-01-29 07:53:44 +00001606 // Okay, place the bitfield at the calculated offset.
Anders Carlsson07209442009-11-22 17:37:31 +00001607 FieldOffsets.push_back(FieldOffset);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001608
John McCall30268ca2014-01-29 07:53:44 +00001609 // Bookkeeping:
1610
1611 // Anonymous members don't affect the overall record alignment,
1612 // except on targets where they do.
1613 if (!IsMsStruct &&
1614 !Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
1615 !D->getIdentifier())
1616 FieldAlign = UnpackedFieldAlign = 1;
1617
1618 // Diagnose differences in layout due to padding or packing.
Douglas Gregore9fc3772012-01-26 07:55:45 +00001619 if (!ExternalLayout)
1620 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset,
1621 UnpackedFieldAlign, FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001622
Anders Carlssonba958402009-11-22 19:13:51 +00001623 // Update DataSize to include the last byte containing (part of) the bitfield.
John McCall30268ca2014-01-29 07:53:44 +00001624
1625 // For unions, this is just a max operation, as usual.
Anders Carlssonba958402009-11-22 19:13:51 +00001626 if (IsUnion) {
1627 // FIXME: I think FieldSize should be TypeSize here.
Ken Dyckecfc7552011-02-24 01:13:28 +00001628 setDataSize(std::max(getDataSizeInBits(), FieldSize));
John McCall30268ca2014-01-29 07:53:44 +00001629
1630 // For non-zero-width bitfields in ms_struct structs, allocate a new
1631 // storage unit if necessary.
1632 } else if (IsMsStruct && FieldSize) {
1633 // We should have cleared UnfilledBitsInLastUnit in every case
1634 // where we changed storage units.
1635 if (!UnfilledBitsInLastUnit) {
1636 setDataSize(FieldOffset + TypeSize);
1637 UnfilledBitsInLastUnit = TypeSize;
Eli Friedman2782dac2013-06-26 20:50:34 +00001638 }
John McCall30268ca2014-01-29 07:53:44 +00001639 UnfilledBitsInLastUnit -= FieldSize;
1640 LastBitfieldTypeSize = TypeSize;
1641
1642 // Otherwise, bump the data size up to include the bitfield,
1643 // including padding up to char alignment, and then remember how
1644 // bits we didn't use.
1645 } else {
1646 uint64_t NewSizeInBits = FieldOffset + FieldSize;
1647 uint64_t CharAlignment = Context.getTargetInfo().getCharAlign();
1648 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits, CharAlignment));
1649 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
1650
1651 // The only time we can get here for an ms_struct is if this is a
1652 // zero-width bitfield, which doesn't count as anything for the
1653 // purposes of unfilled bits.
1654 LastBitfieldTypeSize = 0;
Anders Carlssonba958402009-11-22 19:13:51 +00001655 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001656
Anders Carlssonba958402009-11-22 19:13:51 +00001657 // Update the size.
Ken Dyckecfc7552011-02-24 01:13:28 +00001658 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001659
Anders Carlsson07209442009-11-22 17:37:31 +00001660 // Remember max struct/class alignment.
Ken Dyck85ef0432011-02-19 18:58:07 +00001661 UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign),
1662 Context.toCharUnitsFromBits(UnpackedFieldAlign));
Anders Carlsson07209442009-11-22 17:37:31 +00001663}
1664
Douglas Gregore9fc3772012-01-26 07:55:45 +00001665void RecordLayoutBuilder::LayoutField(const FieldDecl *D) {
Anders Carlsson07209442009-11-22 17:37:31 +00001666 if (D->isBitField()) {
1667 LayoutBitField(D);
1668 return;
1669 }
1670
Eli Friedman2782dac2013-06-26 20:50:34 +00001671 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001672
Anders Carlssonba958402009-11-22 19:13:51 +00001673 // Reset the unfilled bits.
Eli Friedman2782dac2013-06-26 20:50:34 +00001674 UnfilledBitsInLastUnit = 0;
1675 LastBitfieldTypeSize = 0;
Anders Carlssonba958402009-11-22 19:13:51 +00001676
Anders Carlsson07209442009-11-22 17:37:31 +00001677 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
Ken Dyck6d90e892011-02-20 02:06:09 +00001678 CharUnits FieldOffset =
Ken Dyckecfc7552011-02-24 01:13:28 +00001679 IsUnion ? CharUnits::Zero() : getDataSize();
Ken Dyck6d90e892011-02-20 02:06:09 +00001680 CharUnits FieldSize;
1681 CharUnits FieldAlign;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001682
Anders Carlsson07209442009-11-22 17:37:31 +00001683 if (D->getType()->isIncompleteArrayType()) {
1684 // This is a flexible array member; we can't directly
1685 // query getTypeInfo about these, so we figure it out here.
1686 // Flexible array members don't have any size, but they
1687 // have to be aligned appropriately for their element type.
Ken Dyck6d90e892011-02-20 02:06:09 +00001688 FieldSize = CharUnits::Zero();
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001689 const ArrayType* ATy = Context.getAsArrayType(D->getType());
Ken Dyck6d90e892011-02-20 02:06:09 +00001690 FieldAlign = Context.getTypeAlignInChars(ATy->getElementType());
Anders Carlsson07209442009-11-22 17:37:31 +00001691 } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) {
1692 unsigned AS = RT->getPointeeType().getAddressSpace();
Ken Dyck6d90e892011-02-20 02:06:09 +00001693 FieldSize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001694 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(AS));
Ken Dyck6d90e892011-02-20 02:06:09 +00001695 FieldAlign =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001696 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(AS));
Anders Carlsson79474332009-07-18 20:20:21 +00001697 } else {
Ken Dyck6d90e892011-02-20 02:06:09 +00001698 std::pair<CharUnits, CharUnits> FieldInfo =
1699 Context.getTypeInfoInChars(D->getType());
Anders Carlsson07209442009-11-22 17:37:31 +00001700 FieldSize = FieldInfo.first;
1701 FieldAlign = FieldInfo.second;
Chad Rosier18903ee2011-08-04 01:21:14 +00001702
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001703 if (IsMsStruct) {
Douglas Gregordbe39272011-02-01 15:15:22 +00001704 // If MS bitfield layout is required, figure out what type is being
1705 // laid out and align the field to the width of that type.
1706
1707 // Resolve all typedefs down to their base type and round up the field
1708 // alignment if necessary.
1709 QualType T = Context.getBaseElementType(D->getType());
1710 if (const BuiltinType *BTy = T->getAs<BuiltinType>()) {
Ken Dyck6d90e892011-02-20 02:06:09 +00001711 CharUnits TypeSize = Context.getTypeSizeInChars(BTy);
Douglas Gregordbe39272011-02-01 15:15:22 +00001712 if (TypeSize > FieldAlign)
1713 FieldAlign = TypeSize;
1714 }
1715 }
Anders Carlsson79474332009-07-18 20:20:21 +00001716 }
Mike Stump11289f42009-09-09 15:08:12 +00001717
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001718 // The align if the field is not packed. This is to check if the attribute
1719 // was unnecessary (-Wpacked).
Ken Dyck6d90e892011-02-20 02:06:09 +00001720 CharUnits UnpackedFieldAlign = FieldAlign;
1721 CharUnits UnpackedFieldOffset = FieldOffset;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001722
Anders Carlsson07209442009-11-22 17:37:31 +00001723 if (FieldPacked)
Ken Dyck6d90e892011-02-20 02:06:09 +00001724 FieldAlign = CharUnits::One();
1725 CharUnits MaxAlignmentInChars =
1726 Context.toCharUnitsFromBits(D->getMaxAlignment());
1727 FieldAlign = std::max(FieldAlign, MaxAlignmentInChars);
1728 UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars);
Anders Carlsson07209442009-11-22 17:37:31 +00001729
1730 // The maximum field alignment overrides the aligned attribute.
Ken Dyck02ced6f2011-02-17 01:49:42 +00001731 if (!MaxFieldAlignment.isZero()) {
Ken Dyck6d90e892011-02-20 02:06:09 +00001732 FieldAlign = std::min(FieldAlign, MaxFieldAlignment);
1733 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001734 }
Anders Carlsson07209442009-11-22 17:37:31 +00001735
Douglas Gregor44ba7892012-01-28 00:53:29 +00001736 // Round up the current record size to the field's alignment boundary.
1737 FieldOffset = FieldOffset.RoundUpToAlignment(FieldAlign);
1738 UnpackedFieldOffset =
1739 UnpackedFieldOffset.RoundUpToAlignment(UnpackedFieldAlign);
1740
1741 if (ExternalLayout) {
1742 FieldOffset = Context.toCharUnitsFromBits(
1743 updateExternalFieldOffset(D, Context.toBits(FieldOffset)));
1744
1745 if (!IsUnion && EmptySubobjects) {
1746 // Record the fact that we're placing a field at this offset.
1747 bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset);
1748 (void)Allowed;
1749 assert(Allowed && "Externally-placed field cannot be placed here");
1750 }
1751 } else {
Douglas Gregore9fc3772012-01-26 07:55:45 +00001752 if (!IsUnion && EmptySubobjects) {
1753 // Check if we can place the field at this offset.
1754 while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) {
1755 // We couldn't place the field at the offset. Try again at a new offset.
1756 FieldOffset += FieldAlign;
1757 }
Anders Carlsson07209442009-11-22 17:37:31 +00001758 }
Anders Carlsson07209442009-11-22 17:37:31 +00001759 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001760
Anders Carlsson79474332009-07-18 20:20:21 +00001761 // Place this field at the current location.
Ken Dyck6d90e892011-02-20 02:06:09 +00001762 FieldOffsets.push_back(Context.toBits(FieldOffset));
Mike Stump11289f42009-09-09 15:08:12 +00001763
Douglas Gregore9fc3772012-01-26 07:55:45 +00001764 if (!ExternalLayout)
1765 CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset,
1766 Context.toBits(UnpackedFieldOffset),
1767 Context.toBits(UnpackedFieldAlign), FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001768
Anders Carlsson79474332009-07-18 20:20:21 +00001769 // Reserve space for this field.
Eli Friedman43f18342012-01-12 23:27:03 +00001770 uint64_t FieldSizeInBits = Context.toBits(FieldSize);
Anders Carlsson79474332009-07-18 20:20:21 +00001771 if (IsUnion)
Eli Friedman2e108372012-01-12 23:48:56 +00001772 setDataSize(std::max(getDataSizeInBits(), FieldSizeInBits));
Anders Carlsson79474332009-07-18 20:20:21 +00001773 else
Eli Friedman2e108372012-01-12 23:48:56 +00001774 setDataSize(FieldOffset + FieldSize);
Mike Stump11289f42009-09-09 15:08:12 +00001775
Eli Friedman2e108372012-01-12 23:48:56 +00001776 // Update the size.
1777 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Mike Stump11289f42009-09-09 15:08:12 +00001778
Anders Carlsson79474332009-07-18 20:20:21 +00001779 // Remember max struct/class alignment.
Ken Dyck6d90e892011-02-20 02:06:09 +00001780 UpdateAlignment(FieldAlign, UnpackedFieldAlign);
Anders Carlsson79474332009-07-18 20:20:21 +00001781}
1782
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001783void RecordLayoutBuilder::FinishLayout(const NamedDecl *D) {
Anders Carlsson79474332009-07-18 20:20:21 +00001784 // In C++, records cannot be of size 0.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001785 if (Context.getLangOpts().CPlusPlus && getSizeInBits() == 0) {
Fariborz Jahanian09b23312011-02-02 19:36:18 +00001786 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
1787 // Compatibility with gcc requires a class (pod or non-pod)
1788 // which is not empty but of size 0; such as having fields of
1789 // array of zero-length, remains of Size 0
1790 if (RD->isEmpty())
Ken Dyck1b4420e2011-02-28 02:01:38 +00001791 setSize(CharUnits::One());
Fariborz Jahanian09b23312011-02-02 19:36:18 +00001792 }
1793 else
Ken Dyck1b4420e2011-02-28 02:01:38 +00001794 setSize(CharUnits::One());
Fariborz Jahanian09b23312011-02-02 19:36:18 +00001795 }
Eli Friedman83a12582011-12-01 00:37:01 +00001796
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001797 // Finally, round the size of the record up to the alignment of the
1798 // record itself.
Eli Friedman2782dac2013-06-26 20:50:34 +00001799 uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastUnit;
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001800 uint64_t UnpackedSizeInBits =
1801 llvm::RoundUpToAlignment(getSizeInBits(),
1802 Context.toBits(UnpackedAlignment));
1803 CharUnits UnpackedSize = Context.toCharUnitsFromBits(UnpackedSizeInBits);
1804 uint64_t RoundedSize
1805 = llvm::RoundUpToAlignment(getSizeInBits(), Context.toBits(Alignment));
1806
1807 if (ExternalLayout) {
1808 // If we're inferring alignment, and the external size is smaller than
1809 // our size after we've rounded up to alignment, conservatively set the
1810 // alignment to 1.
1811 if (InferAlignment && ExternalSize < RoundedSize) {
1812 Alignment = CharUnits::One();
1813 InferAlignment = false;
1814 }
1815 setSize(ExternalSize);
1816 return;
1817 }
1818
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001819 // Set the size to the final size.
1820 setSize(RoundedSize);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001821
Douglas Gregore8bbc122011-09-02 00:18:52 +00001822 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001823 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1824 // Warn if padding was introduced to the struct/class/union.
Ken Dyckecfc7552011-02-24 01:13:28 +00001825 if (getSizeInBits() > UnpaddedSize) {
1826 unsigned PadSize = getSizeInBits() - UnpaddedSize;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001827 bool InBits = true;
1828 if (PadSize % CharBitNum == 0) {
1829 PadSize = PadSize / CharBitNum;
1830 InBits = false;
1831 }
1832 Diag(RD->getLocation(), diag::warn_padded_struct_size)
1833 << Context.getTypeDeclType(RD)
1834 << PadSize
1835 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
1836 }
1837
1838 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
1839 // bother since there won't be alignment issues.
Ken Dyckecfc7552011-02-24 01:13:28 +00001840 if (Packed && UnpackedAlignment > CharUnits::One() &&
Ken Dyck1b4420e2011-02-28 02:01:38 +00001841 getSize() == UnpackedSize)
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001842 Diag(D->getLocation(), diag::warn_unnecessary_packed)
1843 << Context.getTypeDeclType(RD);
1844 }
Anders Carlsson79474332009-07-18 20:20:21 +00001845}
1846
Ken Dyck85ef0432011-02-19 18:58:07 +00001847void RecordLayoutBuilder::UpdateAlignment(CharUnits NewAlignment,
1848 CharUnits UnpackedNewAlignment) {
Douglas Gregore9fc3772012-01-26 07:55:45 +00001849 // The alignment is not modified when using 'mac68k' alignment or when
Douglas Gregor44ba7892012-01-28 00:53:29 +00001850 // we have an externally-supplied layout that also provides overall alignment.
1851 if (IsMac68kAlign || (ExternalLayout && !InferAlignment))
Daniel Dunbar6da10982010-05-27 05:45:51 +00001852 return;
1853
Ken Dyck85ef0432011-02-19 18:58:07 +00001854 if (NewAlignment > Alignment) {
1855 assert(llvm::isPowerOf2_32(NewAlignment.getQuantity() &&
1856 "Alignment not a power of 2"));
1857 Alignment = NewAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001858 }
1859
Ken Dyck85ef0432011-02-19 18:58:07 +00001860 if (UnpackedNewAlignment > UnpackedAlignment) {
1861 assert(llvm::isPowerOf2_32(UnpackedNewAlignment.getQuantity() &&
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001862 "Alignment not a power of 2"));
Ken Dyck85ef0432011-02-19 18:58:07 +00001863 UnpackedAlignment = UnpackedNewAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001864 }
1865}
1866
Douglas Gregor44ba7892012-01-28 00:53:29 +00001867uint64_t
1868RecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field,
1869 uint64_t ComputedOffset) {
1870 assert(ExternalFieldOffsets.find(Field) != ExternalFieldOffsets.end() &&
1871 "Field does not have an external offset");
1872
1873 uint64_t ExternalFieldOffset = ExternalFieldOffsets[Field];
1874
1875 if (InferAlignment && ExternalFieldOffset < ComputedOffset) {
1876 // The externally-supplied field offset is before the field offset we
1877 // computed. Assume that the structure is packed.
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001878 Alignment = CharUnits::One();
Douglas Gregor44ba7892012-01-28 00:53:29 +00001879 InferAlignment = false;
1880 }
1881
1882 // Use the externally-supplied field offset.
Benjamin Kramer648e68b2012-08-31 22:14:25 +00001883 return ExternalFieldOffset;
1884}
1885
1886/// \brief Get diagnostic %select index for tag kind for
1887/// field padding diagnostic message.
1888/// WARNING: Indexes apply to particular diagnostics only!
1889///
1890/// \returns diagnostic %select index.
1891static unsigned getPaddingDiagFromTagKind(TagTypeKind Tag) {
1892 switch (Tag) {
1893 case TTK_Struct: return 0;
1894 case TTK_Interface: return 1;
1895 case TTK_Class: return 2;
1896 default: llvm_unreachable("Invalid tag kind for field padding diagnostic!");
1897 }
1898}
1899
1900void RecordLayoutBuilder::CheckFieldPadding(uint64_t Offset,
1901 uint64_t UnpaddedOffset,
1902 uint64_t UnpackedOffset,
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001903 unsigned UnpackedAlign,
1904 bool isPacked,
1905 const FieldDecl *D) {
1906 // We let objc ivars without warning, objc interfaces generally are not used
1907 // for padding tricks.
1908 if (isa<ObjCIvarDecl>(D))
Anders Carlsson79474332009-07-18 20:20:21 +00001909 return;
Mike Stump11289f42009-09-09 15:08:12 +00001910
Ted Kremenekfed48af2011-09-06 19:40:45 +00001911 // Don't warn about structs created without a SourceLocation. This can
1912 // be done by clients of the AST, such as codegen.
1913 if (D->getLocation().isInvalid())
1914 return;
1915
Douglas Gregore8bbc122011-09-02 00:18:52 +00001916 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
Mike Stump11289f42009-09-09 15:08:12 +00001917
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001918 // Warn if padding was introduced to the struct/class.
1919 if (!IsUnion && Offset > UnpaddedOffset) {
1920 unsigned PadSize = Offset - UnpaddedOffset;
1921 bool InBits = true;
1922 if (PadSize % CharBitNum == 0) {
1923 PadSize = PadSize / CharBitNum;
1924 InBits = false;
Benjamin Kramer648e68b2012-08-31 22:14:25 +00001925 }
1926 if (D->getIdentifier())
1927 Diag(D->getLocation(), diag::warn_padded_struct_field)
1928 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
1929 << Context.getTypeDeclType(D->getParent())
1930 << PadSize
1931 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1) // plural or not
1932 << D->getIdentifier();
1933 else
1934 Diag(D->getLocation(), diag::warn_padded_struct_anon_field)
1935 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
1936 << Context.getTypeDeclType(D->getParent())
1937 << PadSize
1938 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001939 }
1940
1941 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
1942 // bother since there won't be alignment issues.
1943 if (isPacked && UnpackedAlign > CharBitNum && Offset == UnpackedOffset)
1944 Diag(D->getLocation(), diag::warn_unnecessary_packed)
1945 << D->getIdentifier();
Anders Carlsson79474332009-07-18 20:20:21 +00001946}
Mike Stump11289f42009-09-09 15:08:12 +00001947
John McCall6bd2a892013-01-25 22:31:03 +00001948static const CXXMethodDecl *computeKeyFunction(ASTContext &Context,
1949 const CXXRecordDecl *RD) {
Daniel Dunbarccabe482010-04-19 20:44:53 +00001950 // If a class isn't polymorphic it doesn't have a key function.
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00001951 if (!RD->isPolymorphic())
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001952 return 0;
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001953
Eli Friedman300f55d2011-06-10 21:53:06 +00001954 // A class that is not externally visible doesn't have a key function. (Or
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001955 // at least, there's no point to assigning a key function to such a class;
1956 // this doesn't affect the ABI.)
Rafael Espindola3ae00052013-05-13 00:12:11 +00001957 if (!RD->isExternallyVisible())
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001958 return 0;
1959
Argyrios Kyrtzidis8c64bbe2010-10-13 02:39:41 +00001960 // Template instantiations don't have key functions,see Itanium C++ ABI 5.2.6.
1961 // Same behavior as GCC.
1962 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
1963 if (TSK == TSK_ImplicitInstantiation ||
1964 TSK == TSK_ExplicitInstantiationDefinition)
1965 return 0;
1966
John McCall6bd2a892013-01-25 22:31:03 +00001967 bool allowInlineFunctions =
1968 Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline();
1969
Aaron Ballman2b124d12014-03-13 16:36:16 +00001970 for (const auto *MD : RD->methods()) {
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001971 if (!MD->isVirtual())
1972 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001973
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001974 if (MD->isPure())
1975 continue;
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001976
Anders Carlssonf98849e2009-12-02 17:15:43 +00001977 // Ignore implicit member functions, they are always marked as inline, but
1978 // they don't have a body until they're defined.
1979 if (MD->isImplicit())
1980 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001981
Douglas Gregora318efd2010-01-05 19:06:31 +00001982 if (MD->isInlineSpecified())
1983 continue;
Eli Friedman71a26d82009-12-06 20:50:05 +00001984
1985 if (MD->hasInlineBody())
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001986 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001987
Benjamin Kramer4a902082012-08-03 15:43:22 +00001988 // Ignore inline deleted or defaulted functions.
Benjamin Kramer73d1be72012-08-03 08:39:58 +00001989 if (!MD->isUserProvided())
1990 continue;
1991
John McCall6bd2a892013-01-25 22:31:03 +00001992 // In certain ABIs, ignore functions with out-of-line inline definitions.
1993 if (!allowInlineFunctions) {
1994 const FunctionDecl *Def;
1995 if (MD->hasBody(Def) && Def->isInlineSpecified())
1996 continue;
1997 }
1998
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001999 // We found it.
2000 return MD;
2001 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002002
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002003 return 0;
2004}
2005
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002006DiagnosticBuilder
2007RecordLayoutBuilder::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +00002008 return Context.getDiagnostics().Report(Loc, DiagID);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002009}
2010
John McCall5c1f1d02013-01-29 01:14:22 +00002011/// Does the target C++ ABI require us to skip over the tail-padding
2012/// of the given class (considering it as a base class) when allocating
2013/// objects?
2014static bool mustSkipTailPadding(TargetCXXABI ABI, const CXXRecordDecl *RD) {
2015 switch (ABI.getTailPaddingUseRules()) {
2016 case TargetCXXABI::AlwaysUseTailPadding:
2017 return false;
2018
2019 case TargetCXXABI::UseTailPaddingUnlessPOD03:
2020 // FIXME: To the extent that this is meant to cover the Itanium ABI
2021 // rules, we should implement the restrictions about over-sized
2022 // bitfields:
2023 //
2024 // http://mentorembedded.github.com/cxx-abi/abi.html#POD :
2025 // In general, a type is considered a POD for the purposes of
2026 // layout if it is a POD type (in the sense of ISO C++
2027 // [basic.types]). However, a POD-struct or POD-union (in the
2028 // sense of ISO C++ [class]) with a bitfield member whose
2029 // declared width is wider than the declared type of the
2030 // bitfield is not a POD for the purpose of layout. Similarly,
2031 // an array type is not a POD for the purpose of layout if the
2032 // element type of the array is not a POD for the purpose of
2033 // layout.
2034 //
2035 // Where references to the ISO C++ are made in this paragraph,
2036 // the Technical Corrigendum 1 version of the standard is
2037 // intended.
2038 return RD->isPOD();
2039
2040 case TargetCXXABI::UseTailPaddingUnlessPOD11:
2041 // This is equivalent to RD->getTypeForDecl().isCXX11PODType(),
2042 // but with a lot of abstraction penalty stripped off. This does
2043 // assume that these properties are set correctly even in C++98
2044 // mode; fortunately, that is true because we want to assign
2045 // consistently semantics to the type-traits intrinsics (or at
2046 // least as many of them as possible).
2047 return RD->isTrivial() && RD->isStandardLayout();
2048 }
2049
2050 llvm_unreachable("bad tail-padding use kind");
2051}
2052
Warren Hunt8f8bad72013-10-11 20:19:00 +00002053static bool isMsLayout(const RecordDecl* D) {
Warren Hunt55d8e822013-10-23 23:53:07 +00002054 return D->getASTContext().getTargetInfo().getCXXABI().isMicrosoft();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002055}
2056
2057// This section contains an implementation of struct layout that is, up to the
2058// included tests, compatible with cl.exe (2012). The layout produced is
2059// significantly different than those produced by the Itanium ABI. Here we note
2060// the most important differences.
2061//
2062// * The alignment of bitfields in unions is ignored when computing the
2063// alignment of the union.
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002064// * The existence of zero-width bitfield that occurs after anything other than
Warren Hunt8f8bad72013-10-11 20:19:00 +00002065// a non-zero length bitfield is ignored.
2066// * The Itanium equivalent vtable pointers are split into a vfptr (virtual
2067// function pointer) and a vbptr (virtual base pointer). They can each be
Warren Hunt55d8e822013-10-23 23:53:07 +00002068// shared with a, non-virtual bases. These bases need not be the same. vfptrs
2069// always occur at offset 0. vbptrs can occur at an
Warren Hunt8f8bad72013-10-11 20:19:00 +00002070// arbitrary offset and are placed after non-virtual bases but before fields.
2071// * Virtual bases sometimes require a 'vtordisp' field that is laid out before
2072// the virtual base and is used in conjunction with virtual overrides during
2073// construction and destruction.
2074// * vfptrs are allocated in a block of memory equal to the alignment of the
Warren Hunt55d8e822013-10-23 23:53:07 +00002075// fields and non-virtual bases at offset 0 in 32 bit mode and in a pointer
2076// sized block of memory in 64 bit mode.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002077// * vbptrs are allocated in a block of memory equal to the alignment of the
Warren Hunt55d8e822013-10-23 23:53:07 +00002078// fields and non-virtual bases. This block is at a potentially unaligned
2079// offset. If the allocation slot is unaligned and the alignment is less than
2080// or equal to the pointer size, additional space is allocated so that the
2081// pointer can be aligned properly. This causes very strange effects on the
2082// placement of objects after the allocated block. (see the code).
Warren Hunt8f8bad72013-10-11 20:19:00 +00002083// * vtordisps are allocated in a block of memory with size and alignment equal
2084// to the alignment of the completed structure (before applying __declspec(
Warren Hunt55d8e822013-10-23 23:53:07 +00002085// align())). The vtordisp always occur at the end of the allocation block,
2086// immediately prior to the virtual base.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002087// * The last zero sized non-virtual base is allocated after the placement of
2088// vbptr if one exists and can be placed at the end of the struct, potentially
2089// aliasing either the first member or another struct allocated after this
2090// one.
2091// * The last zero size virtual base may be placed at the end of the struct.
2092// and can potentially alias a zero sized type in the next struct.
Warren Hunt71140d62013-12-06 20:16:49 +00002093// * If the last field is a non-zero length bitfield, all virtual bases will
2094// have extra padding added before them for no obvious reason. The padding
2095// has the same number of bits as the type of the bitfield.
Warren Huntc0df47d2013-11-19 22:11:09 +00002096// * When laying out empty non-virtual bases, an extra byte of padding is added
2097// if the non-virtual base before the empty non-virtual base has a vbptr.
Warren Hunt049f6732013-12-06 19:54:25 +00002098// * The ABI attempts to avoid aliasing of zero sized bases by adding padding
2099// between bases or vbases with specific properties. The criteria for
2100// additional padding between two bases is that the first base is zero sized
2101// or has a zero sized subobject and the second base is zero sized or leads
2102// with a zero sized base (sharing of vfptrs can reorder the layout of the
2103// so the leading base is not always the first one declared). The padding
2104// added for bases is 1 byte. The padding added for vbases depends on the
2105// alignment of the object but is at least 4 bytes (in both 32 and 64 bit
2106// modes).
Warren Huntd640d7d2014-01-09 00:30:56 +00002107// * There is no concept of non-virtual alignment or any distinction between
2108// data size and non-virtual size.
Warren Huntf4518def2014-01-10 01:28:05 +00002109// * __declspec(align) on bitfields has the effect of changing the bitfield's
2110// alignment instead of its required alignment. This has implications on how
2111// it interacts with pragam pack.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002112
2113namespace {
2114struct MicrosoftRecordLayoutBuilder {
Warren Huntd640d7d2014-01-09 00:30:56 +00002115 struct ElementInfo {
2116 CharUnits Size;
2117 CharUnits Alignment;
2118 };
Warren Hunt8f8bad72013-10-11 20:19:00 +00002119 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
2120 MicrosoftRecordLayoutBuilder(const ASTContext &Context) : Context(Context) {}
2121private:
2122 MicrosoftRecordLayoutBuilder(const MicrosoftRecordLayoutBuilder &)
2123 LLVM_DELETED_FUNCTION;
2124 void operator=(const MicrosoftRecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
2125public:
Warren Hunt8f8bad72013-10-11 20:19:00 +00002126 void layout(const RecordDecl *RD);
2127 void cxxLayout(const CXXRecordDecl *RD);
2128 /// \brief Initializes size and alignment and honors some flags.
2129 void initializeLayout(const RecordDecl *RD);
2130 /// \brief Initialized C++ layout, compute alignment and virtual alignment and
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002131 /// existence of vfptrs and vbptrs. Alignment is needed before the vfptr is
Warren Hunt8f8bad72013-10-11 20:19:00 +00002132 /// laid out.
2133 void initializeCXXLayout(const CXXRecordDecl *RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002134 void layoutNonVirtualBases(const CXXRecordDecl *RD);
Warren Huntd640d7d2014-01-09 00:30:56 +00002135 void layoutNonVirtualBase(const CXXRecordDecl *BaseDecl,
2136 const ASTRecordLayout &BaseLayout,
2137 const ASTRecordLayout *&PreviousBaseLayout);
2138 void injectVFPtr(const CXXRecordDecl *RD);
2139 void injectVBPtr(const CXXRecordDecl *RD);
2140 void injectVPtrs(const CXXRecordDecl *RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002141 /// \brief Lays out the fields of the record. Also rounds size up to
2142 /// alignment.
2143 void layoutFields(const RecordDecl *RD);
2144 void layoutField(const FieldDecl *FD);
2145 void layoutBitField(const FieldDecl *FD);
2146 /// \brief Lays out a single zero-width bit-field in the record and handles
2147 /// special cases associated with zero-width bit-fields.
2148 void layoutZeroWidthBitField(const FieldDecl *FD);
2149 void layoutVirtualBases(const CXXRecordDecl *RD);
Warren Hunt1603e522013-12-10 01:44:39 +00002150 void finalizeLayout(const RecordDecl *RD);
Warren Huntd640d7d2014-01-09 00:30:56 +00002151 /// \brief Gets the size and alignment of a base taking pragma pack and
2152 /// __declspec(align) into account.
Warren Huntf6ec7482014-02-21 01:40:35 +00002153 ElementInfo getAdjustedElementInfo(const ASTRecordLayout &Layout,
2154 bool AsBase = true);
Warren Huntd640d7d2014-01-09 00:30:56 +00002155 /// \brief Gets the size and alignment of a field taking pragma pack and
2156 /// __declspec(align) into account. It also updates RequiredAlignment as a
2157 /// side effect because it is most convenient to do so here.
2158 ElementInfo getAdjustedElementInfo(const FieldDecl *FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002159 /// \brief Places a field at an offset in CharUnits.
2160 void placeFieldAtOffset(CharUnits FieldOffset) {
2161 FieldOffsets.push_back(Context.toBits(FieldOffset));
2162 }
2163 /// \brief Places a bitfield at a bit offset.
2164 void placeFieldAtBitOffset(uint64_t FieldOffset) {
2165 FieldOffsets.push_back(FieldOffset);
2166 }
2167 /// \brief Compute the set of virtual bases for which vtordisps are required.
2168 llvm::SmallPtrSet<const CXXRecordDecl *, 2>
2169 computeVtorDispSet(const CXXRecordDecl *RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002170 const ASTContext &Context;
2171 /// \brief The size of the record being laid out.
2172 CharUnits Size;
Warren Huntf6ec7482014-02-21 01:40:35 +00002173 /// \brief The non-virtual size of the record layout.
2174 CharUnits NonVirtualSize;
2175 /// \brief The data size of the record layout.
Warren Huntd640d7d2014-01-09 00:30:56 +00002176 CharUnits DataSize;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002177 /// \brief The current alignment of the record layout.
2178 CharUnits Alignment;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002179 /// \brief The maximum allowed field alignment. This is set by #pragma pack.
2180 CharUnits MaxFieldAlignment;
Warren Hunt7b252d22013-12-06 00:01:17 +00002181 /// \brief The alignment that this record must obey. This is imposed by
2182 /// __declspec(align()) on the record itself or one of its fields or bases.
2183 CharUnits RequiredAlignment;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002184 /// \brief The size of the allocation of the currently active bitfield.
2185 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield
2186 /// is true.
2187 CharUnits CurrentBitfieldSize;
Warren Huntd640d7d2014-01-09 00:30:56 +00002188 /// \brief Offset to the virtual base table pointer (if one exists).
2189 CharUnits VBPtrOffset;
2190 /// \brief The size and alignment info of a pointer.
2191 ElementInfo PointerInfo;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002192 /// \brief The primary base class (if one exists).
2193 const CXXRecordDecl *PrimaryBase;
2194 /// \brief The class we share our vb-pointer with.
2195 const CXXRecordDecl *SharedVBPtrBase;
Warren Huntd640d7d2014-01-09 00:30:56 +00002196 /// \brief The collection of field offsets.
2197 SmallVector<uint64_t, 16> FieldOffsets;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002198 /// \brief Base classes and their offsets in the record.
2199 BaseOffsetsMapTy Bases;
2200 /// \brief virtual base classes and their offsets in the record.
2201 ASTRecordLayout::VBaseOffsetsMapTy VBases;
Warren Huntd640d7d2014-01-09 00:30:56 +00002202 /// \brief The number of remaining bits in our last bitfield allocation.
2203 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield is
2204 /// true.
2205 unsigned RemainingBitsInField;
2206 bool IsUnion : 1;
2207 /// \brief True if the last field laid out was a bitfield and was not 0
2208 /// width.
2209 bool LastFieldIsNonZeroWidthBitfield : 1;
2210 /// \brief True if the class has its own vftable pointer.
2211 bool HasOwnVFPtr : 1;
2212 /// \brief True if the class has a vbtable pointer.
2213 bool HasVBPtr : 1;
Warren Hunt55d8e822013-10-23 23:53:07 +00002214 /// \brief Lets us know if we're in 64-bit mode
Warren Hunt049f6732013-12-06 19:54:25 +00002215 bool Is64BitMode : 1;
2216 /// \brief True if this class contains a zero sized member or base or a base
2217 /// with a zero sized member or base. Only used for MS-ABI.
2218 bool HasZeroSizedSubObject : 1;
2219 /// \brief True if this class is zero sized or first base is zero sized or
2220 /// has this property. Only used for MS-ABI.
2221 bool LeadsWithZeroSizedBase : 1;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002222};
2223} // namespace
2224
Warren Huntd640d7d2014-01-09 00:30:56 +00002225MicrosoftRecordLayoutBuilder::ElementInfo
2226MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
Warren Huntf6ec7482014-02-21 01:40:35 +00002227 const ASTRecordLayout &Layout, bool AsBase) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002228 ElementInfo Info;
2229 Info.Alignment = Layout.getAlignment();
2230 // Respect pragma pack.
Warren Hunt7b252d22013-12-06 00:01:17 +00002231 if (!MaxFieldAlignment.isZero())
Warren Huntd640d7d2014-01-09 00:30:56 +00002232 Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
2233 // Track zero-sized subobjects here where it's already available.
2234 if (Layout.hasZeroSizedSubObject())
2235 HasZeroSizedSubObject = true;
2236 // Respect required alignment, this is necessary because we may have adjusted
Warren Hunt94258912014-01-11 01:16:40 +00002237 // the alignment in the case of pragam pack. Note that the required alignment
2238 // doesn't actually apply to the struct alignment at this point.
2239 Alignment = std::max(Alignment, Info.Alignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002240 Info.Alignment = std::max(Info.Alignment, Layout.getRequiredAlignment());
Warren Huntf6ec7482014-02-21 01:40:35 +00002241 Info.Size = AsBase ? Layout.getNonVirtualSize() : Layout.getSize();
Warren Huntd640d7d2014-01-09 00:30:56 +00002242 return Info;
Warren Hunt7b252d22013-12-06 00:01:17 +00002243}
2244
Warren Huntd640d7d2014-01-09 00:30:56 +00002245MicrosoftRecordLayoutBuilder::ElementInfo
2246MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
2247 const FieldDecl *FD) {
2248 ElementInfo Info;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002249 std::tie(Info.Size, Info.Alignment) =
Reid Klecknerdb673ca2014-02-25 18:08:48 +00002250 Context.getTypeInfoInChars(FD->getType());
Warren Huntf4518def2014-01-10 01:28:05 +00002251 // Respect align attributes.
2252 CharUnits FieldRequiredAlignment =
2253 Context.toCharUnitsFromBits(FD->getMaxAlignment());
Warren Hunt049f6732013-12-06 19:54:25 +00002254 // Respect attributes applied to subobjects of the field.
Warren Hunt7b252d22013-12-06 00:01:17 +00002255 if (const RecordType *RT =
2256 FD->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
2257 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RT->getDecl());
Warren Huntd640d7d2014-01-09 00:30:56 +00002258 // Get the element info for a layout, respecting pack.
Reid Klecknerdb673ca2014-02-25 18:08:48 +00002259 Info.Alignment = getAdjustedElementInfo(Layout, false).Alignment;
Warren Huntd640d7d2014-01-09 00:30:56 +00002260 // Capture required alignment as a side-effect.
Warren Hunt7b252d22013-12-06 00:01:17 +00002261 RequiredAlignment = std::max(RequiredAlignment,
2262 Layout.getRequiredAlignment());
Reid Klecknerdb673ca2014-02-25 18:08:48 +00002263 } else {
Warren Huntf4518def2014-01-10 01:28:05 +00002264 if (FD->isBitField() && FD->getMaxAlignment() != 0)
2265 Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
Warren Hunt26b94422014-01-14 00:54:36 +00002266 // Respect pragma pack.
2267 if (!MaxFieldAlignment.isZero())
2268 Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002269 }
2270 // Respect packed field attribute.
2271 if (FD->hasAttr<PackedAttr>())
2272 Info.Alignment = CharUnits::One();
Warren Huntf4518def2014-01-10 01:28:05 +00002273 // Take required alignment into account. __declspec(align) on bitfields
2274 // impacts the alignment rather than the required alignment.
2275 if (!FD->isBitField()) {
2276 Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
2277 // Capture required alignment as a side-effect.
2278 RequiredAlignment = std::max(RequiredAlignment, FieldRequiredAlignment);
2279 }
Warren Hunt94258912014-01-11 01:16:40 +00002280 // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
Warren Hunt26b94422014-01-14 00:54:36 +00002281 if (!(FD->isBitField() && IsUnion)) {
Warren Hunt94258912014-01-11 01:16:40 +00002282 Alignment = std::max(Alignment, Info.Alignment);
Warren Hunt26b94422014-01-14 00:54:36 +00002283 if (!MaxFieldAlignment.isZero())
2284 Alignment = std::min(Alignment, MaxFieldAlignment);
2285 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002286 return Info;
2287}
2288
2289void MicrosoftRecordLayoutBuilder::layout(const RecordDecl *RD) {
2290 initializeLayout(RD);
2291 layoutFields(RD);
2292 DataSize = Size = Size.RoundUpToAlignment(Alignment);
David Majnemer79a1c892014-02-12 00:43:02 +00002293 RequiredAlignment = std::max(
2294 RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
Warren Huntd640d7d2014-01-09 00:30:56 +00002295 finalizeLayout(RD);
2296}
2297
2298void MicrosoftRecordLayoutBuilder::cxxLayout(const CXXRecordDecl *RD) {
2299 initializeLayout(RD);
2300 initializeCXXLayout(RD);
2301 layoutNonVirtualBases(RD);
2302 layoutFields(RD);
2303 injectVPtrs(RD);
Warren Huntf6ec7482014-02-21 01:40:35 +00002304 NonVirtualSize = Size = Size.RoundUpToAlignment(Alignment);
David Majnemer79a1c892014-02-12 00:43:02 +00002305 RequiredAlignment = std::max(
2306 RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
Warren Huntd640d7d2014-01-09 00:30:56 +00002307 layoutVirtualBases(RD);
2308 finalizeLayout(RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002309}
2310
2311void MicrosoftRecordLayoutBuilder::initializeLayout(const RecordDecl *RD) {
2312 IsUnion = RD->isUnion();
Warren Hunt5ae586a2013-11-01 23:59:41 +00002313 Is64BitMode = Context.getTargetInfo().getPointerWidth(0) == 64;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002314 Size = CharUnits::Zero();
2315 Alignment = CharUnits::One();
Warren Hunt7b252d22013-12-06 00:01:17 +00002316 // In 64-bit mode we always perform an alignment step after laying out vbases.
2317 // In 32-bit mode we do not. The check to see if we need to perform alignment
2318 // checks the RequiredAlignment field and performs alignment if it isn't 0.
2319 RequiredAlignment = Is64BitMode ? CharUnits::One() : CharUnits::Zero();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002320 // Compute the maximum field alignment.
2321 MaxFieldAlignment = CharUnits::Zero();
2322 // Honor the default struct packing maximum alignment flag.
2323 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct)
Warren Huntf4518def2014-01-10 01:28:05 +00002324 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
2325 // Honor the packing attribute. The MS-ABI ignores pragma pack if its larger
2326 // than the pointer size.
2327 if (const MaxFieldAlignmentAttr *MFAA = RD->getAttr<MaxFieldAlignmentAttr>()){
2328 unsigned PackedAlignment = MFAA->getAlignment();
2329 if (PackedAlignment <= Context.getTargetInfo().getPointerWidth(0))
2330 MaxFieldAlignment = Context.toCharUnitsFromBits(PackedAlignment);
2331 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002332 // Packed attribute forces max field alignment to be 1.
2333 if (RD->hasAttr<PackedAttr>())
2334 MaxFieldAlignment = CharUnits::One();
2335}
2336
Warren Hunt8f8bad72013-10-11 20:19:00 +00002337void
2338MicrosoftRecordLayoutBuilder::initializeCXXLayout(const CXXRecordDecl *RD) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002339 HasZeroSizedSubObject = false;
Warren Hunt049f6732013-12-06 19:54:25 +00002340 LeadsWithZeroSizedBase = false;
Warren Huntd640d7d2014-01-09 00:30:56 +00002341 HasOwnVFPtr = false;
2342 HasVBPtr = false;
2343 PrimaryBase = 0;
2344 SharedVBPtrBase = 0;
2345 // Calculate pointer size and alignment. These are used for vfptr and vbprt
2346 // injection.
2347 PointerInfo.Size =
2348 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
2349 PointerInfo.Alignment = PointerInfo.Size;
2350 // Respect pragma pack.
2351 if (!MaxFieldAlignment.isZero())
2352 PointerInfo.Alignment = std::min(PointerInfo.Alignment, MaxFieldAlignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002353}
2354
2355void
2356MicrosoftRecordLayoutBuilder::layoutNonVirtualBases(const CXXRecordDecl *RD) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002357 // The MS-ABI lays out all bases that contain leading vfptrs before it lays
2358 // out any bases that do not contain vfptrs. We implement this as two passes
2359 // over the bases. This approach guarantees that the primary base is laid out
2360 // first. We use these passes to calculate some additional aggregated
2361 // information about the bases, such as reqruied alignment and the presence of
2362 // zero sized members.
2363 const ASTRecordLayout* PreviousBaseLayout = 0;
2364 // Iterate through the bases and lay out the non-virtual ones.
Aaron Ballman574705e2014-03-13 15:41:46 +00002365 for (const auto &I : RD->bases()) {
2366 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002367 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
Warren Huntd640d7d2014-01-09 00:30:56 +00002368 // Mark and skip virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00002369 if (I.isVirtual()) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002370 HasVBPtr = true;
2371 continue;
2372 }
David Majnemer79a1c892014-02-12 00:43:02 +00002373 // Track RequiredAlignment for all bases in this pass.
2374 RequiredAlignment = std::max(RequiredAlignment,
2375 BaseLayout.getRequiredAlignment());
Warren Huntd640d7d2014-01-09 00:30:56 +00002376 // Check fo a base to share a VBPtr with.
2377 if (!SharedVBPtrBase && BaseLayout.hasVBPtr()) {
2378 SharedVBPtrBase = BaseDecl;
2379 HasVBPtr = true;
2380 }
2381 // Only lay out bases with extendable VFPtrs on the first pass.
2382 if (!BaseLayout.hasExtendableVFPtr())
2383 continue;
2384 // If we don't have a primary base, this one qualifies.
Warren Huntbadf9e02014-01-13 19:55:52 +00002385 if (!PrimaryBase) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002386 PrimaryBase = BaseDecl;
Warren Huntbadf9e02014-01-13 19:55:52 +00002387 LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
2388 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002389 // Lay out the base.
2390 layoutNonVirtualBase(BaseDecl, BaseLayout, PreviousBaseLayout);
2391 }
2392 // Figure out if we need a fresh VFPtr for this class.
2393 if (!PrimaryBase && RD->isDynamicClass())
2394 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2395 e = RD->method_end();
2396 !HasOwnVFPtr && i != e; ++i)
2397 HasOwnVFPtr = i->isVirtual() && i->size_overridden_methods() == 0;
2398 // If we don't have a primary base then we have a leading object that could
2399 // itself lead with a zero-sized object, something we track.
2400 bool CheckLeadingLayout = !PrimaryBase;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002401 // Iterate through the bases and lay out the non-virtual ones.
Aaron Ballman574705e2014-03-13 15:41:46 +00002402 for (const auto &I : RD->bases()) {
2403 if (I.isVirtual())
Warren Hunt8f8bad72013-10-11 20:19:00 +00002404 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00002405 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002406 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2407 // Only lay out bases without extendable VFPtrs on the second pass.
2408 if (BaseLayout.hasExtendableVFPtr())
Warren Hunt4431fe62013-12-12 22:33:37 +00002409 continue;
Warren Huntd640d7d2014-01-09 00:30:56 +00002410 // If this is the first layout, check to see if it leads with a zero sized
2411 // object. If it does, so do we.
2412 if (CheckLeadingLayout) {
2413 CheckLeadingLayout = false;
2414 LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
Warren Hunt049f6732013-12-06 19:54:25 +00002415 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002416 // Lay out the base.
2417 layoutNonVirtualBase(BaseDecl, BaseLayout, PreviousBaseLayout);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002418 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002419 // Set our VBPtroffset if we know it at this point.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002420 if (!HasVBPtr)
2421 VBPtrOffset = CharUnits::fromQuantity(-1);
Warren Hunt6eba9072014-01-14 00:31:30 +00002422 else if (SharedVBPtrBase) {
2423 const ASTRecordLayout &Layout = Context.getASTRecordLayout(SharedVBPtrBase);
2424 VBPtrOffset = Bases[SharedVBPtrBase] + Layout.getVBPtrOffset();
2425 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002426}
2427
2428void MicrosoftRecordLayoutBuilder::layoutNonVirtualBase(
2429 const CXXRecordDecl *BaseDecl,
2430 const ASTRecordLayout &BaseLayout,
2431 const ASTRecordLayout *&PreviousBaseLayout) {
Warren Huntf4518def2014-01-10 01:28:05 +00002432 // Insert padding between two bases if the left first one is zero sized or
2433 // contains a zero sized subobject and the right is zero sized or one leads
2434 // with a zero sized base.
2435 if (PreviousBaseLayout && PreviousBaseLayout->hasZeroSizedSubObject() &&
2436 BaseLayout.leadsWithZeroSizedBase())
2437 Size++;
2438 ElementInfo Info = getAdjustedElementInfo(BaseLayout);
2439 CharUnits BaseOffset = Size.RoundUpToAlignment(Info.Alignment);
2440 Bases.insert(std::make_pair(BaseDecl, BaseOffset));
Warren Huntf6ec7482014-02-21 01:40:35 +00002441 Size = BaseOffset + BaseLayout.getNonVirtualSize();
Warren Huntf4518def2014-01-10 01:28:05 +00002442 PreviousBaseLayout = &BaseLayout;
Warren Huntd640d7d2014-01-09 00:30:56 +00002443 VBPtrOffset = Size;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002444}
2445
2446void MicrosoftRecordLayoutBuilder::layoutFields(const RecordDecl *RD) {
2447 LastFieldIsNonZeroWidthBitfield = false;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002448 for (const auto *Field : RD->fields())
2449 layoutField(Field);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002450}
2451
2452void MicrosoftRecordLayoutBuilder::layoutField(const FieldDecl *FD) {
2453 if (FD->isBitField()) {
2454 layoutBitField(FD);
2455 return;
2456 }
2457 LastFieldIsNonZeroWidthBitfield = false;
Warren Huntd640d7d2014-01-09 00:30:56 +00002458 ElementInfo Info = getAdjustedElementInfo(FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002459 if (IsUnion) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002460 placeFieldAtOffset(CharUnits::Zero());
2461 Size = std::max(Size, Info.Size);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002462 } else {
Warren Huntd640d7d2014-01-09 00:30:56 +00002463 CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002464 placeFieldAtOffset(FieldOffset);
Warren Huntd640d7d2014-01-09 00:30:56 +00002465 Size = FieldOffset + Info.Size;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002466 }
2467}
2468
2469void MicrosoftRecordLayoutBuilder::layoutBitField(const FieldDecl *FD) {
2470 unsigned Width = FD->getBitWidthValue(Context);
2471 if (Width == 0) {
2472 layoutZeroWidthBitField(FD);
2473 return;
2474 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002475 ElementInfo Info = getAdjustedElementInfo(FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002476 // Clamp the bitfield to a containable size for the sake of being able
2477 // to lay them out. Sema will throw an error.
Warren Huntd640d7d2014-01-09 00:30:56 +00002478 if (Width > Context.toBits(Info.Size))
2479 Width = Context.toBits(Info.Size);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002480 // Check to see if this bitfield fits into an existing allocation. Note:
2481 // MSVC refuses to pack bitfields of formal types with different sizes
2482 // into the same allocation.
2483 if (!IsUnion && LastFieldIsNonZeroWidthBitfield &&
Warren Huntd640d7d2014-01-09 00:30:56 +00002484 CurrentBitfieldSize == Info.Size && Width <= RemainingBitsInField) {
Warren Hunt8f8bad72013-10-11 20:19:00 +00002485 placeFieldAtBitOffset(Context.toBits(Size) - RemainingBitsInField);
2486 RemainingBitsInField -= Width;
2487 return;
2488 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002489 LastFieldIsNonZeroWidthBitfield = true;
Warren Huntd640d7d2014-01-09 00:30:56 +00002490 CurrentBitfieldSize = Info.Size;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002491 if (IsUnion) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002492 placeFieldAtOffset(CharUnits::Zero());
2493 Size = std::max(Size, Info.Size);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002494 } else {
2495 // Allocate a new block of memory and place the bitfield in it.
Warren Huntd640d7d2014-01-09 00:30:56 +00002496 CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002497 placeFieldAtOffset(FieldOffset);
Warren Huntd640d7d2014-01-09 00:30:56 +00002498 Size = FieldOffset + Info.Size;
Warren Huntd640d7d2014-01-09 00:30:56 +00002499 RemainingBitsInField = Context.toBits(Info.Size) - Width;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002500 }
2501}
2502
2503void
2504MicrosoftRecordLayoutBuilder::layoutZeroWidthBitField(const FieldDecl *FD) {
2505 // Zero-width bitfields are ignored unless they follow a non-zero-width
2506 // bitfield.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002507 if (!LastFieldIsNonZeroWidthBitfield) {
2508 placeFieldAtOffset(IsUnion ? CharUnits::Zero() : Size);
2509 // TODO: Add a Sema warning that MS ignores alignment for zero
Alp Tokerd4733632013-12-05 04:47:09 +00002510 // sized bitfields that occur after zero-size bitfields or non-bitfields.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002511 return;
2512 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002513 LastFieldIsNonZeroWidthBitfield = false;
Warren Huntd640d7d2014-01-09 00:30:56 +00002514 ElementInfo Info = getAdjustedElementInfo(FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002515 if (IsUnion) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002516 placeFieldAtOffset(CharUnits::Zero());
2517 Size = std::max(Size, Info.Size);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002518 } else {
2519 // Round up the current record size to the field's alignment boundary.
Warren Huntd640d7d2014-01-09 00:30:56 +00002520 CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002521 placeFieldAtOffset(FieldOffset);
2522 Size = FieldOffset;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002523 }
2524}
2525
Warren Huntd640d7d2014-01-09 00:30:56 +00002526void MicrosoftRecordLayoutBuilder::injectVBPtr(const CXXRecordDecl *RD) {
Warren Hunt6eba9072014-01-14 00:31:30 +00002527 if (!HasVBPtr || SharedVBPtrBase)
Warren Huntd640d7d2014-01-09 00:30:56 +00002528 return;
Warren Huntd640d7d2014-01-09 00:30:56 +00002529 // Inject the VBPointer at the injection site.
2530 CharUnits InjectionSite = VBPtrOffset;
2531 // But before we do, make sure it's properly aligned.
2532 VBPtrOffset = VBPtrOffset.RoundUpToAlignment(PointerInfo.Alignment);
2533 // Determine where the first field should be laid out after the vbptr.
2534 CharUnits FieldStart = VBPtrOffset + PointerInfo.Size;
2535 // Make sure that the amount we push the fields back by is a multiple of the
2536 // alignment.
David Majnemer79a1c892014-02-12 00:43:02 +00002537 CharUnits Offset = (FieldStart - InjectionSite).RoundUpToAlignment(
2538 std::max(RequiredAlignment, Alignment));
Warren Huntd640d7d2014-01-09 00:30:56 +00002539 // Increase the size of the object and push back all fields by the offset
2540 // amount.
2541 Size += Offset;
2542 for (SmallVector<uint64_t, 16>::iterator i = FieldOffsets.begin(),
2543 e = FieldOffsets.end();
2544 i != e; ++i)
2545 *i += Context.toBits(Offset);
2546 for (BaseOffsetsMapTy::iterator i = Bases.begin(), e = Bases.end();
2547 i != e; ++i)
2548 if (i->second >= InjectionSite)
2549 i->second += Offset;
Warren Huntd640d7d2014-01-09 00:30:56 +00002550}
2551
2552void MicrosoftRecordLayoutBuilder::injectVFPtr(const CXXRecordDecl *RD) {
2553 if (!HasOwnVFPtr)
2554 return;
2555 // Make sure that the amount we push the struct back by is a multiple of the
2556 // alignment.
David Majnemer79a1c892014-02-12 00:43:02 +00002557 CharUnits Offset = PointerInfo.Size.RoundUpToAlignment(
2558 std::max(RequiredAlignment, Alignment));
Warren Huntd640d7d2014-01-09 00:30:56 +00002559 // Increase the size of the object and push back all fields, the vbptr and all
2560 // bases by the offset amount.
2561 Size += Offset;
David Majnemer79a1c892014-02-12 00:43:02 +00002562 for (SmallVectorImpl<uint64_t>::iterator i = FieldOffsets.begin(),
Warren Huntd640d7d2014-01-09 00:30:56 +00002563 e = FieldOffsets.end();
2564 i != e; ++i)
2565 *i += Context.toBits(Offset);
2566 if (HasVBPtr)
2567 VBPtrOffset += Offset;
2568 for (BaseOffsetsMapTy::iterator i = Bases.begin(), e = Bases.end();
2569 i != e; ++i)
2570 i->second += Offset;
Warren Huntd640d7d2014-01-09 00:30:56 +00002571}
2572
2573void MicrosoftRecordLayoutBuilder::injectVPtrs(const CXXRecordDecl *RD) {
David Blaikie461f1ea2014-01-09 02:34:06 +00002574 if (!(HasOwnVFPtr || (HasVBPtr && !SharedVBPtrBase)))
Warren Huntd640d7d2014-01-09 00:30:56 +00002575 return;
2576 if (!Is64BitMode || RequiredAlignment <= CharUnits::fromQuantity(8)) {
2577 // Note that the VBPtr is injected first. It depends on the alignment of
2578 // the object *before* the alignment is updated by inserting a pointer into
2579 // the record.
2580 injectVBPtr(RD);
2581 injectVFPtr(RD);
Warren Hunt94258912014-01-11 01:16:40 +00002582 Alignment = std::max(Alignment, PointerInfo.Alignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002583 return;
2584 }
2585 // In 64-bit mode, structs with RequiredAlignment greater than 8 get special
2586 // layout rules. Likely this is to avoid excessive padding intruced around
2587 // the vfptrs and vbptrs. The special rules involve re-laying out the struct
2588 // and inserting the vfptr and vbptr as if they were fields/bases.
2589 FieldOffsets.clear();
2590 Bases.clear();
2591 Size = CharUnits::Zero();
Warren Hunt94258912014-01-11 01:16:40 +00002592 Alignment = std::max(Alignment, PointerInfo.Alignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002593 if (HasOwnVFPtr)
2594 Size = PointerInfo.Size;
2595 layoutNonVirtualBases(RD);
2596 if (HasVBPtr && !SharedVBPtrBase) {
2597 const CXXRecordDecl *PenultBaseDecl = 0;
2598 const CXXRecordDecl *LastBaseDecl = 0;
2599 // Iterate through the bases and find the last two non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00002600 for (const auto &I : RD->bases()) {
2601 if (I.isVirtual())
Warren Huntd640d7d2014-01-09 00:30:56 +00002602 continue;
Aaron Ballman574705e2014-03-13 15:41:46 +00002603 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002604 if (!LastBaseDecl || Bases[BaseDecl] > Bases[LastBaseDecl]) {
2605 PenultBaseDecl = LastBaseDecl;
2606 LastBaseDecl = BaseDecl;
2607 }
2608 }
2609 const ASTRecordLayout *PenultBaseLayout = PenultBaseDecl ?
2610 &Context.getASTRecordLayout(PenultBaseDecl) : 0;
2611 const ASTRecordLayout *LastBaseLayout = LastBaseDecl ?
2612 &Context.getASTRecordLayout(LastBaseDecl) : 0;
2613 // Calculate the vbptr offset. The rule is different than in the general
2614 // case layout. Particularly, if the last two non-virtual bases are both
2615 // zero sized, the site of the vbptr is *before* the padding that occurs
2616 // between the two zero sized bases and the vbptr potentially aliases with
2617 // the first of these two bases. We have no understanding of why this is
2618 // different from the general case layout but it may have to do with lazy
2619 // placement of zero sized bases.
2620 VBPtrOffset = Size;
Warren Huntf6ec7482014-02-21 01:40:35 +00002621 if (LastBaseLayout && LastBaseLayout->getNonVirtualSize().isZero()) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002622 VBPtrOffset = Bases[LastBaseDecl];
Warren Huntf6ec7482014-02-21 01:40:35 +00002623 if (PenultBaseLayout && PenultBaseLayout->getNonVirtualSize().isZero())
Warren Huntd640d7d2014-01-09 00:30:56 +00002624 VBPtrOffset = Bases[PenultBaseDecl];
2625 }
2626 // Once we've located a spot for the vbptr, place it.
2627 VBPtrOffset = VBPtrOffset.RoundUpToAlignment(PointerInfo.Alignment);
2628 Size = VBPtrOffset + PointerInfo.Size;
Warren Huntf6ec7482014-02-21 01:40:35 +00002629 if (LastBaseLayout && LastBaseLayout->getNonVirtualSize().isZero()) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002630 // Add the padding between zero sized bases after the vbptr.
Warren Huntf6ec7482014-02-21 01:40:35 +00002631 if (PenultBaseLayout && PenultBaseLayout->getNonVirtualSize().isZero())
Warren Huntd640d7d2014-01-09 00:30:56 +00002632 Size += CharUnits::One();
2633 Size = Size.RoundUpToAlignment(LastBaseLayout->getRequiredAlignment());
2634 Bases[LastBaseDecl] = Size;
2635 }
2636 }
2637 layoutFields(RD);
Warren Hunt87c2b042014-01-10 23:32:32 +00002638 // The presence of a vbptr suppresses zero sized objects that are not in
2639 // virtual bases.
2640 HasZeroSizedSubObject = false;
Warren Hunt1603e522013-12-10 01:44:39 +00002641}
2642
Warren Hunt8f8bad72013-10-11 20:19:00 +00002643void MicrosoftRecordLayoutBuilder::layoutVirtualBases(const CXXRecordDecl *RD) {
2644 if (!HasVBPtr)
2645 return;
Warren Huntd640d7d2014-01-09 00:30:56 +00002646 // Vtordisps are always 4 bytes (even in 64-bit mode)
2647 CharUnits VtorDispSize = CharUnits::fromQuantity(4);
2648 CharUnits VtorDispAlignment = VtorDispSize;
2649 // vtordisps respect pragma pack.
2650 if (!MaxFieldAlignment.isZero())
2651 VtorDispAlignment = std::min(VtorDispAlignment, MaxFieldAlignment);
2652 // The alignment of the vtordisp is at least the required alignment of the
2653 // entire record. This requirement may be present to support vtordisp
2654 // injection.
Aaron Ballman445a9392014-03-13 16:15:17 +00002655 for (const auto &I : RD->vbases()) {
2656 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
David Majnemer79a1c892014-02-12 00:43:02 +00002657 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2658 RequiredAlignment =
2659 std::max(RequiredAlignment, BaseLayout.getRequiredAlignment());
2660 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002661 VtorDispAlignment = std::max(VtorDispAlignment, RequiredAlignment);
2662 // Compute the vtordisp set.
2663 llvm::SmallPtrSet<const CXXRecordDecl *, 2> HasVtordispSet =
Warren Hunt8f8bad72013-10-11 20:19:00 +00002664 computeVtorDispSet(RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002665 // Iterate through the virtual bases and lay them out.
Warren Huntd640d7d2014-01-09 00:30:56 +00002666 const ASTRecordLayout* PreviousBaseLayout = 0;
Aaron Ballman445a9392014-03-13 16:15:17 +00002667 for (const auto &I : RD->vbases()) {
2668 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002669 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2670 bool HasVtordisp = HasVtordispSet.count(BaseDecl);
Warren Hunt71140d62013-12-06 20:16:49 +00002671 // If the last field we laid out was a non-zero length bitfield then add
2672 // some extra padding for no obvious reason.
2673 if (LastFieldIsNonZeroWidthBitfield)
2674 Size += CurrentBitfieldSize;
Warren Huntd640d7d2014-01-09 00:30:56 +00002675 // Insert padding between two bases if the left first one is zero sized or
2676 // contains a zero sized subobject and the right is zero sized or one leads
2677 // with a zero sized base. The padding between virtual bases is 4
2678 // bytes (in both 32 and 64 bits modes) and always involves rounding up to
2679 // the required alignment, we don't know why.
2680 if (PreviousBaseLayout && PreviousBaseLayout->hasZeroSizedSubObject() &&
2681 BaseLayout.leadsWithZeroSizedBase())
2682 Size = Size.RoundUpToAlignment(VtorDispAlignment) + VtorDispSize;
2683 // Insert the vtordisp.
2684 if (HasVtordisp)
2685 Size = Size.RoundUpToAlignment(VtorDispAlignment) + VtorDispSize;
2686 // Insert the virtual base.
Warren Huntf6ec7482014-02-21 01:40:35 +00002687 HasZeroSizedSubObject = false;
Warren Huntd640d7d2014-01-09 00:30:56 +00002688 ElementInfo Info = getAdjustedElementInfo(BaseLayout);
Warren Huntf4518def2014-01-10 01:28:05 +00002689 CharUnits BaseOffset = Size.RoundUpToAlignment(Info.Alignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002690 VBases.insert(std::make_pair(BaseDecl,
2691 ASTRecordLayout::VBaseInfo(BaseOffset, HasVtordisp)));
Warren Huntf6ec7482014-02-21 01:40:35 +00002692 Size = BaseOffset + BaseLayout.getNonVirtualSize();
Warren Huntd640d7d2014-01-09 00:30:56 +00002693 PreviousBaseLayout = &BaseLayout;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002694 }
2695}
2696
Warren Huntc3384312013-12-11 22:28:32 +00002697void MicrosoftRecordLayoutBuilder::finalizeLayout(const RecordDecl *RD) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002698 // Respect required alignment. Note that in 32-bit mode Required alignment
2699 // may be 0 nad cause size not to be updated.
Warren Huntf6ec7482014-02-21 01:40:35 +00002700 DataSize = Size;
Warren Huntd640d7d2014-01-09 00:30:56 +00002701 if (!RequiredAlignment.isZero()) {
2702 Alignment = std::max(Alignment, RequiredAlignment);
2703 Size = Size.RoundUpToAlignment(Alignment);
2704 }
2705 // Zero-sized structures have size equal to their alignment.
Warren Hunt049f6732013-12-06 19:54:25 +00002706 if (Size.isZero()) {
2707 HasZeroSizedSubObject = true;
2708 LeadsWithZeroSizedBase = true;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002709 Size = Alignment;
Warren Hunt049f6732013-12-06 19:54:25 +00002710 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002711}
2712
2713static bool
2714RequiresVtordisp(const llvm::SmallPtrSet<const CXXRecordDecl *, 2> &HasVtordisp,
2715 const CXXRecordDecl *RD) {
2716 if (HasVtordisp.count(RD))
2717 return true;
2718 // If any of a virtual bases non-virtual bases (recursively) requires a
2719 // vtordisp than so does this virtual base.
Aaron Ballman574705e2014-03-13 15:41:46 +00002720 for (const auto &I : RD->bases())
2721 if (!I.isVirtual() &&
Warren Hunt8f8bad72013-10-11 20:19:00 +00002722 RequiresVtordisp(
2723 HasVtordisp,
Aaron Ballman574705e2014-03-13 15:41:46 +00002724 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl())))
Warren Hunt8f8bad72013-10-11 20:19:00 +00002725 return true;
2726 return false;
2727}
2728
2729llvm::SmallPtrSet<const CXXRecordDecl *, 2>
2730MicrosoftRecordLayoutBuilder::computeVtorDispSet(const CXXRecordDecl *RD) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002731 llvm::SmallPtrSet<const CXXRecordDecl *, 2> HasVtordispSet;
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00002732
2733 // /vd0 or #pragma vtordisp(0): Never use vtordisps when used as a vbase.
2734 if (RD->getMSVtorDispMode() == MSVtorDispAttr::Never)
2735 return HasVtordispSet;
2736
2737 // /vd2 or #pragma vtordisp(2): Always use vtordisps for virtual bases with
2738 // vftables.
2739 if (RD->getMSVtorDispMode() == MSVtorDispAttr::ForVFTable) {
Aaron Ballman445a9392014-03-13 16:15:17 +00002740 for (const auto &I : RD->vbases()) {
2741 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00002742 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
2743 if (Layout.hasExtendableVFPtr())
2744 HasVtordispSet.insert(BaseDecl);
2745 }
2746 return HasVtordispSet;
2747 }
2748
2749 // /vd1 or #pragma vtordisp(1): Try to guess based on whether we think it's
2750 // possible for a partially constructed object with virtual base overrides to
2751 // escape a non-trivial constructor.
2752 assert(RD->getMSVtorDispMode() == MSVtorDispAttr::ForVBaseOverride);
2753
Warren Hunt8f8bad72013-10-11 20:19:00 +00002754 // If any of our bases need a vtordisp for this type, so do we. Check our
2755 // direct bases for vtordisp requirements.
Aaron Ballman574705e2014-03-13 15:41:46 +00002756 for (const auto &I : RD->bases()) {
Warren Hunt8f8bad72013-10-11 20:19:00 +00002757 const CXXRecordDecl *BaseDecl =
Aaron Ballman574705e2014-03-13 15:41:46 +00002758 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Warren Hunt8f8bad72013-10-11 20:19:00 +00002759 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
2760 for (ASTRecordLayout::VBaseOffsetsMapTy::const_iterator
2761 bi = Layout.getVBaseOffsetsMap().begin(),
2762 be = Layout.getVBaseOffsetsMap().end();
2763 bi != be; ++bi)
2764 if (bi->second.hasVtorDisp())
Warren Huntd640d7d2014-01-09 00:30:56 +00002765 HasVtordispSet.insert(bi->first);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002766 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002767 // If we define a constructor or destructor and override a function that is
2768 // defined in a virtual base's vtable, that virtual bases need a vtordisp.
2769 // Here we collect a list of classes with vtables for which our virtual bases
2770 // actually live. The virtual bases with this property will require
2771 // vtordisps. In addition, virtual bases that contain non-virtual bases that
2772 // define functions we override also require vtordisps, this case is checked
2773 // explicitly below.
2774 if (RD->hasUserDeclaredConstructor() || RD->hasUserDeclaredDestructor()) {
2775 llvm::SmallPtrSet<const CXXMethodDecl *, 8> Work;
2776 // Seed the working set with our non-destructor virtual methods.
Aaron Ballman2b124d12014-03-13 16:36:16 +00002777 for (const auto *I : RD->methods())
2778 if (I->isVirtual() && !isa<CXXDestructorDecl>(I))
2779 Work.insert(I);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002780 while (!Work.empty()) {
2781 const CXXMethodDecl *MD = *Work.begin();
2782 CXXMethodDecl::method_iterator i = MD->begin_overridden_methods(),
2783 e = MD->end_overridden_methods();
2784 if (i == e)
2785 // If a virtual method has no-overrides it lives in its parent's vtable.
Warren Huntd640d7d2014-01-09 00:30:56 +00002786 HasVtordispSet.insert(MD->getParent());
Warren Hunt8f8bad72013-10-11 20:19:00 +00002787 else
2788 Work.insert(i, e);
2789 // We've finished processing this element, remove it from the working set.
2790 Work.erase(MD);
2791 }
2792 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002793 // Re-check all of our vbases for vtordisp requirements (in case their
2794 // non-virtual bases have vtordisp requirements).
Aaron Ballman445a9392014-03-13 16:15:17 +00002795 for (const auto &I : RD->vbases()) {
2796 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002797 if (!HasVtordispSet.count(BaseDecl) &&
2798 RequiresVtordisp(HasVtordispSet, BaseDecl))
2799 HasVtordispSet.insert(BaseDecl);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002800 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002801 return HasVtordispSet;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002802}
2803
2804/// \brief Get or compute information about the layout of the specified record
2805/// (struct/union/class), which indicates its size and field position
2806/// information.
2807const ASTRecordLayout *
2808ASTContext::BuildMicrosoftASTRecordLayout(const RecordDecl *D) const {
2809 MicrosoftRecordLayoutBuilder Builder(*this);
2810 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2811 Builder.cxxLayout(RD);
2812 return new (*this) ASTRecordLayout(
Warren Hunt7b252d22013-12-06 00:01:17 +00002813 *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment,
Warren Huntd640d7d2014-01-09 00:30:56 +00002814 Builder.HasOwnVFPtr,
2815 Builder.HasOwnVFPtr || Builder.PrimaryBase,
Warren Huntf6ec7482014-02-21 01:40:35 +00002816 Builder.VBPtrOffset, Builder.NonVirtualSize, Builder.FieldOffsets.data(),
2817 Builder.FieldOffsets.size(), Builder.NonVirtualSize,
Warren Huntd640d7d2014-01-09 00:30:56 +00002818 Builder.Alignment, CharUnits::Zero(), Builder.PrimaryBase,
Warren Hunt049f6732013-12-06 19:54:25 +00002819 false, Builder.SharedVBPtrBase,
2820 Builder.HasZeroSizedSubObject, Builder.LeadsWithZeroSizedBase,
2821 Builder.Bases, Builder.VBases);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002822 } else {
2823 Builder.layout(D);
2824 return new (*this) ASTRecordLayout(
Warren Hunt7b252d22013-12-06 00:01:17 +00002825 *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment,
2826 Builder.Size, Builder.FieldOffsets.data(), Builder.FieldOffsets.size());
Warren Hunt8f8bad72013-10-11 20:19:00 +00002827 }
2828}
2829
Anders Carlssondf291d82010-05-26 04:56:53 +00002830/// getASTRecordLayout - Get or compute information about the layout of the
2831/// specified record (struct/union/class), which indicates its size and field
2832/// position information.
Jay Foad39c79802011-01-12 09:06:06 +00002833const ASTRecordLayout &
2834ASTContext::getASTRecordLayout(const RecordDecl *D) const {
John McCall0710e552011-10-07 02:39:22 +00002835 // These asserts test different things. A record has a definition
2836 // as soon as we begin to parse the definition. That definition is
2837 // not a complete definition (which is what isDefinition() tests)
2838 // until we *finish* parsing the definition.
Sean Callanan56c19892012-02-08 00:04:52 +00002839
2840 if (D->hasExternalLexicalStorage() && !D->getDefinition())
2841 getExternalSource()->CompleteType(const_cast<RecordDecl*>(D));
2842
Anders Carlssondf291d82010-05-26 04:56:53 +00002843 D = D->getDefinition();
2844 assert(D && "Cannot get layout of forward declarations!");
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00002845 assert(!D->isInvalidDecl() && "Cannot get layout of invalid decl!");
John McCallf937c022011-10-07 06:10:15 +00002846 assert(D->isCompleteDefinition() && "Cannot layout type before complete!");
Anders Carlssondf291d82010-05-26 04:56:53 +00002847
2848 // Look up this layout, if already laid out, return what we have.
2849 // Note that we can't save a reference to the entry because this function
2850 // is recursive.
2851 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
2852 if (Entry) return *Entry;
2853
Warren Hunt8f8bad72013-10-11 20:19:00 +00002854 const ASTRecordLayout *NewEntry = 0;
Anders Carlssond2954862010-05-26 05:10:47 +00002855
Reid Kleckneraf1465c2014-02-20 23:07:29 +00002856 if (isMsLayout(D) && !D->getASTContext().getExternalSource()) {
Warren Hunt8f8bad72013-10-11 20:19:00 +00002857 NewEntry = BuildMicrosoftASTRecordLayout(D);
2858 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
Anders Carlssonc121b4e2010-05-27 00:07:01 +00002859 EmptySubobjectMap EmptySubobjects(*this, RD);
John McCall0153cd32011-11-08 04:01:03 +00002860 RecordLayoutBuilder Builder(*this, &EmptySubobjects);
2861 Builder.Layout(RD);
Anders Carlsson439edd12010-05-27 05:41:06 +00002862
John McCall5c1f1d02013-01-29 01:14:22 +00002863 // In certain situations, we are allowed to lay out objects in the
2864 // tail-padding of base classes. This is ABI-dependent.
2865 // FIXME: this should be stored in the record layout.
2866 bool skipTailPadding =
2867 mustSkipTailPadding(getTargetInfo().getCXXABI(), cast<CXXRecordDecl>(D));
Anders Carlssond2954862010-05-26 05:10:47 +00002868
2869 // FIXME: This should be done in FinalizeLayout.
Ken Dyck1b4420e2011-02-28 02:01:38 +00002870 CharUnits DataSize =
John McCall5c1f1d02013-01-29 01:14:22 +00002871 skipTailPadding ? Builder.getSize() : Builder.getDataSize();
Ken Dyck1b4420e2011-02-28 02:01:38 +00002872 CharUnits NonVirtualSize =
John McCall5c1f1d02013-01-29 01:14:22 +00002873 skipTailPadding ? DataSize : Builder.NonVirtualSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002874 NewEntry =
John McCall0153cd32011-11-08 04:01:03 +00002875 new (*this) ASTRecordLayout(*this, Builder.getSize(),
2876 Builder.Alignment,
Warren Hunt7b252d22013-12-06 00:01:17 +00002877 /*RequiredAlignment : used by MS-ABI)*/
2878 Builder.Alignment,
John McCalle42a3362012-05-01 08:55:32 +00002879 Builder.HasOwnVFPtr,
Warren Hunt8f8bad72013-10-11 20:19:00 +00002880 RD->isDynamicClass(),
Warren Hunt55d8e822013-10-23 23:53:07 +00002881 CharUnits::fromQuantity(-1),
Ken Dyck1b4420e2011-02-28 02:01:38 +00002882 DataSize,
John McCall0153cd32011-11-08 04:01:03 +00002883 Builder.FieldOffsets.data(),
2884 Builder.FieldOffsets.size(),
Ken Dyckaf1c83f2011-02-16 01:52:01 +00002885 NonVirtualSize,
John McCall0153cd32011-11-08 04:01:03 +00002886 Builder.NonVirtualAlignment,
Anders Carlssonc121b4e2010-05-27 00:07:01 +00002887 EmptySubobjects.SizeOfLargestEmptySubobject,
John McCall0153cd32011-11-08 04:01:03 +00002888 Builder.PrimaryBase,
2889 Builder.PrimaryBaseIsVirtual,
Warren Hunt049f6732013-12-06 19:54:25 +00002890 0, false, false,
John McCall0153cd32011-11-08 04:01:03 +00002891 Builder.Bases, Builder.VBases);
Anders Carlssond2954862010-05-26 05:10:47 +00002892 } else {
John McCall0153cd32011-11-08 04:01:03 +00002893 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
Anders Carlssond2954862010-05-26 05:10:47 +00002894 Builder.Layout(D);
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002895
Anders Carlssond2954862010-05-26 05:10:47 +00002896 NewEntry =
Ken Dyck1b4420e2011-02-28 02:01:38 +00002897 new (*this) ASTRecordLayout(*this, Builder.getSize(),
Ken Dyck4731d5b2011-02-16 02:05:21 +00002898 Builder.Alignment,
Warren Hunt7b252d22013-12-06 00:01:17 +00002899 /*RequiredAlignment : used by MS-ABI)*/
2900 Builder.Alignment,
Ken Dyck1b4420e2011-02-28 02:01:38 +00002901 Builder.getSize(),
Anders Carlssond2954862010-05-26 05:10:47 +00002902 Builder.FieldOffsets.data(),
2903 Builder.FieldOffsets.size());
2904 }
2905
Anders Carlssondf291d82010-05-26 04:56:53 +00002906 ASTRecordLayouts[D] = NewEntry;
2907
David Blaikiebbafb8a2012-03-11 07:00:24 +00002908 if (getLangOpts().DumpRecordLayouts) {
Argyrios Kyrtzidis8ade08e2013-07-12 22:30:03 +00002909 llvm::outs() << "\n*** Dumping AST Record Layout\n";
2910 DumpRecordLayout(D, llvm::outs(), getLangOpts().DumpRecordLayoutsSimple);
Anders Carlssondf291d82010-05-26 04:56:53 +00002911 }
2912
2913 return *NewEntry;
2914}
2915
John McCall6bd2a892013-01-25 22:31:03 +00002916const CXXMethodDecl *ASTContext::getCurrentKeyFunction(const CXXRecordDecl *RD) {
Reid Kleckner5d7f2982013-05-29 16:18:30 +00002917 if (!getTargetInfo().getCXXABI().hasKeyFunctions())
2918 return 0;
2919
John McCall6bd2a892013-01-25 22:31:03 +00002920 assert(RD->getDefinition() && "Cannot get key function for forward decl!");
Anders Carlssondf291d82010-05-26 04:56:53 +00002921 RD = cast<CXXRecordDecl>(RD->getDefinition());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002922
Richard Smith676c4042013-08-29 23:59:27 +00002923 LazyDeclPtr &Entry = KeyFunctions[RD];
2924 if (!Entry)
2925 Entry = const_cast<CXXMethodDecl*>(computeKeyFunction(*this, RD));
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002926
Richard Smith676c4042013-08-29 23:59:27 +00002927 return cast_or_null<CXXMethodDecl>(Entry.get(getExternalSource()));
John McCall6bd2a892013-01-25 22:31:03 +00002928}
2929
Richard Smith676c4042013-08-29 23:59:27 +00002930void ASTContext::setNonKeyFunction(const CXXMethodDecl *Method) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002931 assert(Method == Method->getFirstDecl() &&
John McCall6bd2a892013-01-25 22:31:03 +00002932 "not working with method declaration from class definition");
2933
2934 // Look up the cache entry. Since we're working with the first
2935 // declaration, its parent must be the class definition, which is
2936 // the correct key for the KeyFunctions hash.
Richard Smith676c4042013-08-29 23:59:27 +00002937 llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr>::iterator
2938 I = KeyFunctions.find(Method->getParent());
John McCall6bd2a892013-01-25 22:31:03 +00002939
2940 // If it's not cached, there's nothing to do.
Richard Smith676c4042013-08-29 23:59:27 +00002941 if (I == KeyFunctions.end()) return;
John McCall6bd2a892013-01-25 22:31:03 +00002942
2943 // If it is cached, check whether it's the target method, and if so,
2944 // remove it from the cache.
Richard Smith676c4042013-08-29 23:59:27 +00002945 if (I->second.get(getExternalSource()) == Method) {
John McCall6bd2a892013-01-25 22:31:03 +00002946 // FIXME: remember that we did this for module / chained PCH state?
Richard Smith676c4042013-08-29 23:59:27 +00002947 KeyFunctions.erase(I);
John McCall6bd2a892013-01-25 22:31:03 +00002948 }
Anders Carlssondf291d82010-05-26 04:56:53 +00002949}
2950
Richard Smithdafff942012-01-14 04:30:29 +00002951static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) {
2952 const ASTRecordLayout &Layout = C.getASTRecordLayout(FD->getParent());
2953 return Layout.getFieldOffset(FD->getFieldIndex());
2954}
2955
2956uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const {
2957 uint64_t OffsetInBits;
2958 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
2959 OffsetInBits = ::getFieldOffset(*this, FD);
2960 } else {
2961 const IndirectFieldDecl *IFD = cast<IndirectFieldDecl>(VD);
2962
2963 OffsetInBits = 0;
Aaron Ballman29c94602014-03-07 18:36:15 +00002964 for (const auto *CI : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002965 OffsetInBits += ::getFieldOffset(*this, cast<FieldDecl>(CI));
Richard Smithdafff942012-01-14 04:30:29 +00002966 }
2967
2968 return OffsetInBits;
2969}
2970
Eric Christopher8a39a012011-10-05 06:00:51 +00002971/// getObjCLayout - Get or compute information about the layout of the
2972/// given interface.
Anders Carlssondf291d82010-05-26 04:56:53 +00002973///
2974/// \param Impl - If given, also include the layout of the interface's
2975/// implementation. This may differ by including synthesized ivars.
2976const ASTRecordLayout &
2977ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
Jay Foad39c79802011-01-12 09:06:06 +00002978 const ObjCImplementationDecl *Impl) const {
Douglas Gregor64d92572011-12-20 15:50:13 +00002979 // Retrieve the definition
Sean Callanand9a909c2012-03-15 16:33:08 +00002980 if (D->hasExternalLexicalStorage() && !D->getDefinition())
2981 getExternalSource()->CompleteType(const_cast<ObjCInterfaceDecl*>(D));
Douglas Gregor64d92572011-12-20 15:50:13 +00002982 D = D->getDefinition();
2983 assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!");
Anders Carlssondf291d82010-05-26 04:56:53 +00002984
2985 // Look up this layout, if already laid out, return what we have.
Roman Divackye6377112012-09-06 15:59:27 +00002986 const ObjCContainerDecl *Key =
2987 Impl ? (const ObjCContainerDecl*) Impl : (const ObjCContainerDecl*) D;
Anders Carlssondf291d82010-05-26 04:56:53 +00002988 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
2989 return *Entry;
2990
2991 // Add in synthesized ivar count if laying out an implementation.
2992 if (Impl) {
2993 unsigned SynthCount = CountNonClassIvars(D);
2994 // If there aren't any sythesized ivars then reuse the interface
2995 // entry. Note we can't cache this because we simply free all
2996 // entries later; however we shouldn't look up implementations
2997 // frequently.
2998 if (SynthCount == 0)
2999 return getObjCLayout(D, 0);
3000 }
3001
John McCall0153cd32011-11-08 04:01:03 +00003002 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
Anders Carlsson6ed3a9a2010-05-26 05:04:25 +00003003 Builder.Layout(D);
3004
Anders Carlssondf291d82010-05-26 04:56:53 +00003005 const ASTRecordLayout *NewEntry =
Ken Dyck1b4420e2011-02-28 02:01:38 +00003006 new (*this) ASTRecordLayout(*this, Builder.getSize(),
Ken Dyck4731d5b2011-02-16 02:05:21 +00003007 Builder.Alignment,
Warren Hunt7b252d22013-12-06 00:01:17 +00003008 /*RequiredAlignment : used by MS-ABI)*/
3009 Builder.Alignment,
Ken Dyck1b4420e2011-02-28 02:01:38 +00003010 Builder.getDataSize(),
Anders Carlsson6ed3a9a2010-05-26 05:04:25 +00003011 Builder.FieldOffsets.data(),
3012 Builder.FieldOffsets.size());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00003013
Anders Carlssondf291d82010-05-26 04:56:53 +00003014 ObjCLayouts[Key] = NewEntry;
3015
3016 return *NewEntry;
3017}
3018
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003019static void PrintOffset(raw_ostream &OS,
Anders Carlsson3f018712010-10-31 23:45:59 +00003020 CharUnits Offset, unsigned IndentLevel) {
Benjamin Kramer96ad7172011-11-05 09:02:52 +00003021 OS << llvm::format("%4" PRId64 " | ", (int64_t)Offset.getQuantity());
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003022 OS.indent(IndentLevel * 2);
3023}
3024
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00003025static void PrintIndentNoOffset(raw_ostream &OS, unsigned IndentLevel) {
3026 OS << " | ";
3027 OS.indent(IndentLevel * 2);
3028}
3029
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003030static void DumpCXXRecordLayout(raw_ostream &OS,
Jay Foad39c79802011-01-12 09:06:06 +00003031 const CXXRecordDecl *RD, const ASTContext &C,
Anders Carlsson3f018712010-10-31 23:45:59 +00003032 CharUnits Offset,
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003033 unsigned IndentLevel,
3034 const char* Description,
3035 bool IncludeVirtualBases) {
Anders Carlsson3f018712010-10-31 23:45:59 +00003036 const ASTRecordLayout &Layout = C.getASTRecordLayout(RD);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003037
3038 PrintOffset(OS, Offset, IndentLevel);
Dan Gohman145f3f12010-04-19 16:39:44 +00003039 OS << C.getTypeDeclType(const_cast<CXXRecordDecl *>(RD)).getAsString();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003040 if (Description)
3041 OS << ' ' << Description;
3042 if (RD->isEmpty())
3043 OS << " (empty)";
3044 OS << '\n';
3045
3046 IndentLevel++;
3047
Anders Carlsson3f018712010-10-31 23:45:59 +00003048 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
Warren Hunt8f8bad72013-10-11 20:19:00 +00003049 bool HasOwnVFPtr = Layout.hasOwnVFPtr();
3050 bool HasOwnVBPtr = Layout.hasOwnVBPtr();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003051
3052 // Vtable pointer.
Warren Hunt8f8bad72013-10-11 20:19:00 +00003053 if (RD->isDynamicClass() && !PrimaryBase && !isMsLayout(RD)) {
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003054 PrintOffset(OS, Offset, IndentLevel);
Benjamin Kramerb89514a2011-10-14 18:45:37 +00003055 OS << '(' << *RD << " vtable pointer)\n";
Warren Hunt8f8bad72013-10-11 20:19:00 +00003056 } else if (HasOwnVFPtr) {
3057 PrintOffset(OS, Offset, IndentLevel);
3058 // vfptr (for Microsoft C++ ABI)
3059 OS << '(' << *RD << " vftable pointer)\n";
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003060 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00003061
Reid Klecknerad59deb2014-02-28 01:03:09 +00003062 // Collect nvbases.
3063 SmallVector<const CXXRecordDecl *, 4> Bases;
Aaron Ballman574705e2014-03-13 15:41:46 +00003064 for (const auto &I : RD->bases()) {
3065 assert(!I.getType()->isDependentType() &&
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003066 "Cannot layout class with dependent bases.");
Aaron Ballman574705e2014-03-13 15:41:46 +00003067 if (!I.isVirtual())
3068 Bases.push_back(I.getType()->getAsCXXRecordDecl());
Reid Klecknerad59deb2014-02-28 01:03:09 +00003069 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003070
Reid Klecknerad59deb2014-02-28 01:03:09 +00003071 // Sort nvbases by offset.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00003072 std::stable_sort(Bases.begin(), Bases.end(),
3073 [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
3074 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
3075 });
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003076
Reid Klecknerad59deb2014-02-28 01:03:09 +00003077 // Dump (non-virtual) bases
3078 for (SmallVectorImpl<const CXXRecordDecl *>::iterator I = Bases.begin(),
3079 E = Bases.end();
3080 I != E; ++I) {
3081 const CXXRecordDecl *Base = *I;
Anders Carlsson3f018712010-10-31 23:45:59 +00003082 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003083 DumpCXXRecordLayout(OS, Base, C, BaseOffset, IndentLevel,
3084 Base == PrimaryBase ? "(primary base)" : "(base)",
3085 /*IncludeVirtualBases=*/false);
3086 }
Eli Friedman43114f92011-10-21 22:49:56 +00003087
Warren Hunt8f8bad72013-10-11 20:19:00 +00003088 // vbptr (for Microsoft C++ ABI)
3089 if (HasOwnVBPtr) {
Eli Friedman84d2d3a2011-09-27 19:12:27 +00003090 PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel);
Benjamin Kramerb89514a2011-10-14 18:45:37 +00003091 OS << '(' << *RD << " vbtable pointer)\n";
Eli Friedman84d2d3a2011-09-27 19:12:27 +00003092 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003093
3094 // Dump fields.
3095 uint64_t FieldNo = 0;
3096 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
3097 E = RD->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +00003098 const FieldDecl &Field = **I;
Anders Carlsson3f018712010-10-31 23:45:59 +00003099 CharUnits FieldOffset = Offset +
Ken Dyck86a7fcc2011-01-18 01:56:16 +00003100 C.toCharUnitsFromBits(Layout.getFieldOffset(FieldNo));
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003101
David Blaikie2d7c57e2012-04-30 02:36:29 +00003102 if (const RecordType *RT = Field.getType()->getAs<RecordType>()) {
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003103 if (const CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
3104 DumpCXXRecordLayout(OS, D, C, FieldOffset, IndentLevel,
David Blaikie2d7c57e2012-04-30 02:36:29 +00003105 Field.getName().data(),
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003106 /*IncludeVirtualBases=*/true);
3107 continue;
3108 }
3109 }
3110
3111 PrintOffset(OS, FieldOffset, IndentLevel);
David Blaikie2d7c57e2012-04-30 02:36:29 +00003112 OS << Field.getType().getAsString() << ' ' << Field << '\n';
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003113 }
3114
3115 if (!IncludeVirtualBases)
3116 return;
3117
3118 // Dump virtual bases.
John McCalle42a3362012-05-01 08:55:32 +00003119 const ASTRecordLayout::VBaseOffsetsMapTy &vtordisps =
3120 Layout.getVBaseOffsetsMap();
Aaron Ballman445a9392014-03-13 16:15:17 +00003121 for (const auto &I : RD->vbases()) {
3122 assert(I.isVirtual() && "Found non-virtual class!");
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003123 const CXXRecordDecl *VBase =
Aaron Ballman445a9392014-03-13 16:15:17 +00003124 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003125
Anders Carlsson3f018712010-10-31 23:45:59 +00003126 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
John McCalle42a3362012-05-01 08:55:32 +00003127
3128 if (vtordisps.find(VBase)->second.hasVtorDisp()) {
3129 PrintOffset(OS, VBaseOffset - CharUnits::fromQuantity(4), IndentLevel);
3130 OS << "(vtordisp for vbase " << *VBase << ")\n";
3131 }
3132
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003133 DumpCXXRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel,
3134 VBase == PrimaryBase ?
3135 "(primary virtual base)" : "(virtual base)",
3136 /*IncludeVirtualBases=*/false);
3137 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003138
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00003139 PrintIndentNoOffset(OS, IndentLevel - 1);
3140 OS << "[sizeof=" << Layout.getSize().getQuantity();
Warren Hunt8f8bad72013-10-11 20:19:00 +00003141 if (!isMsLayout(RD))
3142 OS << ", dsize=" << Layout.getDataSize().getQuantity();
Ken Dyck7ad11e72011-02-15 02:32:40 +00003143 OS << ", align=" << Layout.getAlignment().getQuantity() << '\n';
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00003144
3145 PrintIndentNoOffset(OS, IndentLevel - 1);
3146 OS << " nvsize=" << Layout.getNonVirtualSize().getQuantity();
Warren Huntd640d7d2014-01-09 00:30:56 +00003147 OS << ", nvalign=" << Layout.getNonVirtualAlignment().getQuantity() << "]\n";
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003148 OS << '\n';
3149}
Daniel Dunbarccabe482010-04-19 20:44:53 +00003150
3151void ASTContext::DumpRecordLayout(const RecordDecl *RD,
Douglas Gregore9fc3772012-01-26 07:55:45 +00003152 raw_ostream &OS,
3153 bool Simple) const {
Daniel Dunbarccabe482010-04-19 20:44:53 +00003154 const ASTRecordLayout &Info = getASTRecordLayout(RD);
3155
3156 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Douglas Gregore9fc3772012-01-26 07:55:45 +00003157 if (!Simple)
3158 return DumpCXXRecordLayout(OS, CXXRD, *this, CharUnits(), 0, 0,
3159 /*IncludeVirtualBases=*/true);
Daniel Dunbarccabe482010-04-19 20:44:53 +00003160
3161 OS << "Type: " << getTypeDeclType(RD).getAsString() << "\n";
Douglas Gregore9fc3772012-01-26 07:55:45 +00003162 if (!Simple) {
3163 OS << "Record: ";
3164 RD->dump();
3165 }
Daniel Dunbarccabe482010-04-19 20:44:53 +00003166 OS << "\nLayout: ";
3167 OS << "<ASTRecordLayout\n";
Ken Dyckb0fcc592011-02-11 01:54:29 +00003168 OS << " Size:" << toBits(Info.getSize()) << "\n";
Warren Hunt8f8bad72013-10-11 20:19:00 +00003169 if (!isMsLayout(RD))
3170 OS << " DataSize:" << toBits(Info.getDataSize()) << "\n";
Ken Dyck7ad11e72011-02-15 02:32:40 +00003171 OS << " Alignment:" << toBits(Info.getAlignment()) << "\n";
Daniel Dunbarccabe482010-04-19 20:44:53 +00003172 OS << " FieldOffsets: [";
3173 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) {
3174 if (i) OS << ", ";
3175 OS << Info.getFieldOffset(i);
3176 }
3177 OS << "]>\n";
3178}