blob: d5df63f7d151380fceb5b23259fdba30dfc598f1 [file] [log] [blame]
Anders Carlsson9392fa62010-05-26 05:41:04 +00001//=== RecordLayoutBuilder.cpp - Helper class for building record layouts ---==//
Anders Carlssonbda4c102009-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
Benjamin Kramerd4f51982012-07-04 18:45:14 +000010#include "clang/AST/ASTContext.h"
Anders Carlssonbda4c102009-07-18 20:20:21 +000011#include "clang/AST/Attr.h"
Anders Carlsson245656e2010-11-24 22:55:48 +000012#include "clang/AST/CXXInheritance.h"
Anders Carlssonbda4c102009-07-18 20:20:21 +000013#include "clang/AST/Decl.h"
Anders Carlsson74cbe222009-07-19 00:18:47 +000014#include "clang/AST/DeclCXX.h"
Anders Carlsson93fab9d2009-07-18 20:50:59 +000015#include "clang/AST/DeclObjC.h"
Anders Carlssonbda4c102009-07-18 20:20:21 +000016#include "clang/AST/Expr.h"
Anders Carlsson9392fa62010-05-26 05:41:04 +000017#include "clang/AST/RecordLayout.h"
Anders Carlssonbda4c102009-07-18 20:20:21 +000018#include "clang/Basic/TargetInfo.h"
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +000019#include "clang/Sema/SemaDiagnostic.h"
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +000020#include "llvm/Support/Format.h"
21#include "llvm/ADT/SmallSet.h"
22#include "llvm/Support/MathExtras.h"
Ted Kremenek4d96d9f2011-03-19 01:00:36 +000023#include "llvm/Support/CrashRecoveryContext.h"
Anders Carlssonbda4c102009-07-18 20:20:21 +000024
25using namespace clang;
26
Benjamin Kramer7e220282010-05-26 09:58:31 +000027namespace {
Anders Carlsson6a91c032010-05-26 15:32:58 +000028
Anders Carlssonea2f41c2010-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 Carlsson4a257992010-05-28 21:13:31 +000042 const CXXRecordDecl *Class;
Anders Carlssonea2f41c2010-05-28 21:24:37 +000043
44 /// IsVirtual - Whether the BaseInfo represents a virtual base or not.
Anders Carlsson4a257992010-05-28 21:13:31 +000045 bool IsVirtual;
46
Anders Carlssonea2f41c2010-05-28 21:24:37 +000047 /// Bases - Information about the base subobjects.
Chris Lattner5f9e2722011-07-23 10:55:15 +000048 SmallVector<BaseSubobjectInfo*, 4> Bases;
Anders Carlssonea2f41c2010-05-28 21:24:37 +000049
Anders Carlsson6e264542010-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 Carlssonea2f41c2010-05-28 21:24:37 +000053
54 // FIXME: Document.
55 const BaseSubobjectInfo *Derived;
Anders Carlsson4a257992010-05-28 21:13:31 +000056};
57
Anders Carlsson6a91c032010-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 Foad4ba2a172011-01-12 09:06:06 +000061 const ASTContext &Context;
Anders Carlsson8c6acc62010-10-31 21:54:55 +000062 uint64_t CharWidth;
63
Anders Carlsson6a91c032010-05-26 15:32:58 +000064 /// Class - The class whose empty entries we're keeping track of.
65 const CXXRecordDecl *Class;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +000066
Anders Carlsson58b16b62010-05-27 05:41:06 +000067 /// EmptyClassOffsets - A map from offsets to empty record decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +000068 typedef SmallVector<const CXXRecordDecl *, 1> ClassVectorTy;
Anders Carlssond8da7632010-10-31 21:22:43 +000069 typedef llvm::DenseMap<CharUnits, ClassVectorTy> EmptyClassOffsetsMapTy;
Anders Carlsson58b16b62010-05-27 05:41:06 +000070 EmptyClassOffsetsMapTy EmptyClassOffsets;
71
Anders Carlssonc8cb4622010-06-08 15:56:03 +000072 /// MaxEmptyClassOffset - The highest offset known to contain an empty
73 /// base subobject.
Anders Carlssonfe5ef732010-10-31 21:39:24 +000074 CharUnits MaxEmptyClassOffset;
Anders Carlssonc8cb4622010-06-08 15:56:03 +000075
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +000076 /// ComputeEmptySubobjectSizes - Compute the size of the largest base or
Anders Carlsson0c54fc92010-05-26 15:54:25 +000077 /// member subobject that is empty.
78 void ComputeEmptySubobjectSizes();
Anders Carlsson58b16b62010-05-27 05:41:06 +000079
Anders Carlssonfe5ef732010-10-31 21:39:24 +000080 void AddSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset);
Anders Carlsson812a3452010-05-27 18:20:57 +000081
Anders Carlssonea2f41c2010-05-28 21:24:37 +000082 void UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
Anders Carlssona3d43802010-10-31 22:13:23 +000083 CharUnits Offset, bool PlacingEmptyBase);
Anders Carlsson58b16b62010-05-27 05:41:06 +000084
Anders Carlsson812a3452010-05-27 18:20:57 +000085 void UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
86 const CXXRecordDecl *Class,
Anders Carlssona3d43802010-10-31 22:13:23 +000087 CharUnits Offset);
88 void UpdateEmptyFieldSubobjects(const FieldDecl *FD, CharUnits Offset);
Anders Carlsson812a3452010-05-27 18:20:57 +000089
Anders Carlssonc8cb4622010-06-08 15:56:03 +000090 /// AnyEmptySubobjectsBeyondOffset - Returns whether there are any empty
91 /// subobjects beyond the given offset.
Anders Carlssonfe5ef732010-10-31 21:39:24 +000092 bool AnyEmptySubobjectsBeyondOffset(CharUnits Offset) const {
Anders Carlssonc8cb4622010-06-08 15:56:03 +000093 return Offset <= MaxEmptyClassOffset;
94 }
95
Anders Carlsson8c6acc62010-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 Dyckff3a5172011-01-24 01:28:50 +0000102 return Context.toCharUnitsFromBits(FieldOffset);
Anders Carlssond8da7632010-10-31 21:22:43 +0000103 }
Anders Carlssond8da7632010-10-31 21:22:43 +0000104
Charles Davisc9f8aec2010-08-19 00:55:19 +0000105protected:
Anders Carlssonfe5ef732010-10-31 21:39:24 +0000106 bool CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
107 CharUnits Offset) const;
Charles Davisc9f8aec2010-08-19 00:55:19 +0000108
109 bool CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
Anders Carlssona3d43802010-10-31 22:13:23 +0000110 CharUnits Offset);
Charles Davisc9f8aec2010-08-19 00:55:19 +0000111
112 bool CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
113 const CXXRecordDecl *Class,
Anders Carlssona3d43802010-10-31 22:13:23 +0000114 CharUnits Offset) const;
Charles Davisc9f8aec2010-08-19 00:55:19 +0000115 bool CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
Anders Carlsson8c6acc62010-10-31 21:54:55 +0000116 CharUnits Offset) const;
Charles Davisc9f8aec2010-08-19 00:55:19 +0000117
Anders Carlsson6a91c032010-05-26 15:32:58 +0000118public:
Anders Carlsson0c54fc92010-05-26 15:54:25 +0000119 /// This holds the size of the largest empty subobject (either a base
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000120 /// or a member). Will be zero if the record being built doesn't contain
Anders Carlsson0c54fc92010-05-26 15:54:25 +0000121 /// any empty classes.
Anders Carlssona3d43802010-10-31 22:13:23 +0000122 CharUnits SizeOfLargestEmptySubobject;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000123
Jay Foad4ba2a172011-01-12 09:06:06 +0000124 EmptySubobjectMap(const ASTContext &Context, const CXXRecordDecl *Class)
Anders Carlssona3d43802010-10-31 22:13:23 +0000125 : Context(Context), CharWidth(Context.getCharWidth()), Class(Class) {
Anders Carlsson261febd2010-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 Dunbar0aa7edb2010-05-27 02:25:46 +0000131 /// Returns false if placing the record will result in two components
Anders Carlsson261febd2010-05-27 00:07:01 +0000132 /// (direct or indirect) of the same type having the same offset.
Anders Carlssonc8cb4622010-06-08 15:56:03 +0000133 bool CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
Anders Carlssona3d43802010-10-31 22:13:23 +0000134 CharUnits Offset);
Anders Carlsson812a3452010-05-27 18:20:57 +0000135
136 /// CanPlaceFieldAtOffset - Return whether a field can be placed at the given
137 /// offset.
Anders Carlssona3d43802010-10-31 22:13:23 +0000138 bool CanPlaceFieldAtOffset(const FieldDecl *FD, CharUnits Offset);
Anders Carlsson6a91c032010-05-26 15:32:58 +0000139};
Anders Carlsson0c54fc92010-05-26 15:54:25 +0000140
141void EmptySubobjectMap::ComputeEmptySubobjectSizes() {
142 // Check the bases.
143 for (CXXRecordDecl::base_class_const_iterator I = Class->bases_begin(),
144 E = Class->bases_end(); I != E; ++I) {
145 const CXXRecordDecl *BaseDecl =
146 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
147
Anders Carlssona3d43802010-10-31 22:13:23 +0000148 CharUnits EmptySize;
Anders Carlsson0c54fc92010-05-26 15:54:25 +0000149 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
150 if (BaseDecl->isEmpty()) {
151 // If the class decl is empty, get its size.
Ken Dyck5f022d82011-02-09 01:59:34 +0000152 EmptySize = Layout.getSize();
Anders Carlsson0c54fc92010-05-26 15:54:25 +0000153 } else {
154 // Otherwise, we get the largest empty subobject for the decl.
155 EmptySize = Layout.getSizeOfLargestEmptySubobject();
156 }
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000157
Anders Carlssona3d43802010-10-31 22:13:23 +0000158 if (EmptySize > SizeOfLargestEmptySubobject)
159 SizeOfLargestEmptySubobject = EmptySize;
Anders Carlsson0c54fc92010-05-26 15:54:25 +0000160 }
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000161
Anders Carlsson0c54fc92010-05-26 15:54:25 +0000162 // Check the fields.
163 for (CXXRecordDecl::field_iterator I = Class->field_begin(),
164 E = Class->field_end(); I != E; ++I) {
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000165
166 const RecordType *RT =
David Blaikie581deb32012-06-06 20:45:41 +0000167 Context.getBaseElementType(I->getType())->getAs<RecordType>();
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000168
Anders Carlsson0c54fc92010-05-26 15:54:25 +0000169 // We only care about record types.
170 if (!RT)
171 continue;
172
Anders Carlssona3d43802010-10-31 22:13:23 +0000173 CharUnits EmptySize;
Anders Carlsson0c54fc92010-05-26 15:54:25 +0000174 const CXXRecordDecl *MemberDecl = cast<CXXRecordDecl>(RT->getDecl());
175 const ASTRecordLayout &Layout = Context.getASTRecordLayout(MemberDecl);
176 if (MemberDecl->isEmpty()) {
177 // If the class decl is empty, get its size.
Ken Dyck5f022d82011-02-09 01:59:34 +0000178 EmptySize = Layout.getSize();
Anders Carlsson0c54fc92010-05-26 15:54:25 +0000179 } else {
180 // Otherwise, we get the largest empty subobject for the decl.
181 EmptySize = Layout.getSizeOfLargestEmptySubobject();
182 }
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000183
Anders Carlssona3d43802010-10-31 22:13:23 +0000184 if (EmptySize > SizeOfLargestEmptySubobject)
185 SizeOfLargestEmptySubobject = EmptySize;
Anders Carlsson0c54fc92010-05-26 15:54:25 +0000186 }
187}
188
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000189bool
Anders Carlsson812a3452010-05-27 18:20:57 +0000190EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
Anders Carlssonfe5ef732010-10-31 21:39:24 +0000191 CharUnits Offset) const {
Anders Carlsson812a3452010-05-27 18:20:57 +0000192 // We only need to check empty bases.
193 if (!RD->isEmpty())
194 return true;
195
Anders Carlssonfe5ef732010-10-31 21:39:24 +0000196 EmptyClassOffsetsMapTy::const_iterator I = EmptyClassOffsets.find(Offset);
Anders Carlsson812a3452010-05-27 18:20:57 +0000197 if (I == EmptyClassOffsets.end())
198 return true;
199
200 const ClassVectorTy& Classes = I->second;
201 if (std::find(Classes.begin(), Classes.end(), RD) == Classes.end())
202 return true;
203
204 // There is already an empty class of the same type at this offset.
205 return false;
206}
207
208void EmptySubobjectMap::AddSubobjectAtOffset(const CXXRecordDecl *RD,
Anders Carlssonfe5ef732010-10-31 21:39:24 +0000209 CharUnits Offset) {
Anders Carlsson812a3452010-05-27 18:20:57 +0000210 // We only care about empty bases.
211 if (!RD->isEmpty())
212 return;
213
Rafael Espindola272324b2010-12-29 23:02:58 +0000214 // If we have empty structures inside an union, we can assign both
215 // the same offset. Just avoid pushing them twice in the list.
Anders Carlssonfe5ef732010-10-31 21:39:24 +0000216 ClassVectorTy& Classes = EmptyClassOffsets[Offset];
Rafael Espindola272324b2010-12-29 23:02:58 +0000217 if (std::find(Classes.begin(), Classes.end(), RD) != Classes.end())
218 return;
219
Anders Carlsson812a3452010-05-27 18:20:57 +0000220 Classes.push_back(RD);
Anders Carlssonc8cb4622010-06-08 15:56:03 +0000221
222 // Update the empty class offset.
Anders Carlssonfe5ef732010-10-31 21:39:24 +0000223 if (Offset > MaxEmptyClassOffset)
224 MaxEmptyClassOffset = Offset;
Anders Carlsson812a3452010-05-27 18:20:57 +0000225}
226
227bool
Anders Carlssona3d43802010-10-31 22:13:23 +0000228EmptySubobjectMap::CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
229 CharUnits Offset) {
Anders Carlsson2177ab72010-06-08 16:20:35 +0000230 // We don't have to keep looking past the maximum offset that's known to
231 // contain an empty class.
Anders Carlssona3d43802010-10-31 22:13:23 +0000232 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson2177ab72010-06-08 16:20:35 +0000233 return true;
234
Anders Carlssona3d43802010-10-31 22:13:23 +0000235 if (!CanPlaceSubobjectAtOffset(Info->Class, Offset))
Anders Carlsson812a3452010-05-27 18:20:57 +0000236 return false;
237
Anders Carlsson58b16b62010-05-27 05:41:06 +0000238 // Traverse all non-virtual bases.
Anders Carlsson4137d512010-05-29 21:10:24 +0000239 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
Anders Carlsson58b16b62010-05-27 05:41:06 +0000240 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
Anders Carlssonea2f41c2010-05-28 21:24:37 +0000241 BaseSubobjectInfo* Base = Info->Bases[I];
Anders Carlsson58b16b62010-05-27 05:41:06 +0000242 if (Base->IsVirtual)
243 continue;
244
Anders Carlsson6a356742010-11-01 00:21:58 +0000245 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlsson58b16b62010-05-27 05:41:06 +0000246
247 if (!CanPlaceBaseSubobjectAtOffset(Base, BaseOffset))
248 return false;
249 }
250
Anders Carlsson6e264542010-05-29 17:35:14 +0000251 if (Info->PrimaryVirtualBaseInfo) {
252 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
Anders Carlsson58b16b62010-05-27 05:41:06 +0000253
254 if (Info == PrimaryVirtualBaseInfo->Derived) {
255 if (!CanPlaceBaseSubobjectAtOffset(PrimaryVirtualBaseInfo, Offset))
256 return false;
257 }
258 }
259
Anders Carlsson812a3452010-05-27 18:20:57 +0000260 // Traverse all member variables.
261 unsigned FieldNo = 0;
262 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
263 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie581deb32012-06-06 20:45:41 +0000264 if (I->isBitField())
Anders Carlsson8c6acc62010-10-31 21:54:55 +0000265 continue;
266
Anders Carlssona3d43802010-10-31 22:13:23 +0000267 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
David Blaikie581deb32012-06-06 20:45:41 +0000268 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
Anders Carlsson812a3452010-05-27 18:20:57 +0000269 return false;
270 }
271
Anders Carlsson58b16b62010-05-27 05:41:06 +0000272 return true;
273}
274
Anders Carlssonea2f41c2010-05-28 21:24:37 +0000275void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
Anders Carlssona3d43802010-10-31 22:13:23 +0000276 CharUnits Offset,
Anders Carlssone3362bc2010-06-13 18:00:18 +0000277 bool PlacingEmptyBase) {
278 if (!PlacingEmptyBase && Offset >= SizeOfLargestEmptySubobject) {
279 // We know that the only empty subobjects that can conflict with empty
280 // subobject of non-empty bases, are empty bases that can be placed at
281 // offset zero. Because of this, we only need to keep track of empty base
282 // subobjects with offsets less than the size of the largest empty
283 // subobject for our class.
284 return;
285 }
286
Anders Carlssona3d43802010-10-31 22:13:23 +0000287 AddSubobjectAtOffset(Info->Class, Offset);
Anders Carlsson4137d512010-05-29 21:10:24 +0000288
Anders Carlsson58b16b62010-05-27 05:41:06 +0000289 // Traverse all non-virtual bases.
Anders Carlsson4137d512010-05-29 21:10:24 +0000290 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
Anders Carlsson58b16b62010-05-27 05:41:06 +0000291 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
Anders Carlssonea2f41c2010-05-28 21:24:37 +0000292 BaseSubobjectInfo* Base = Info->Bases[I];
Anders Carlsson58b16b62010-05-27 05:41:06 +0000293 if (Base->IsVirtual)
294 continue;
Anders Carlsson4137d512010-05-29 21:10:24 +0000295
Anders Carlsson6a356742010-11-01 00:21:58 +0000296 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlssone3362bc2010-06-13 18:00:18 +0000297 UpdateEmptyBaseSubobjects(Base, BaseOffset, PlacingEmptyBase);
Anders Carlsson58b16b62010-05-27 05:41:06 +0000298 }
299
Anders Carlsson6e264542010-05-29 17:35:14 +0000300 if (Info->PrimaryVirtualBaseInfo) {
301 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
Anders Carlsson58b16b62010-05-27 05:41:06 +0000302
303 if (Info == PrimaryVirtualBaseInfo->Derived)
Anders Carlssone3362bc2010-06-13 18:00:18 +0000304 UpdateEmptyBaseSubobjects(PrimaryVirtualBaseInfo, Offset,
305 PlacingEmptyBase);
Anders Carlsson58b16b62010-05-27 05:41:06 +0000306 }
Anders Carlsson812a3452010-05-27 18:20:57 +0000307
Anders Carlsson812a3452010-05-27 18:20:57 +0000308 // Traverse all member variables.
309 unsigned FieldNo = 0;
310 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
311 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie581deb32012-06-06 20:45:41 +0000312 if (I->isBitField())
Anders Carlsson8c6acc62010-10-31 21:54:55 +0000313 continue;
Anders Carlsson4137d512010-05-29 21:10:24 +0000314
Anders Carlssona3d43802010-10-31 22:13:23 +0000315 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
David Blaikie581deb32012-06-06 20:45:41 +0000316 UpdateEmptyFieldSubobjects(*I, FieldOffset);
Anders Carlsson812a3452010-05-27 18:20:57 +0000317 }
Anders Carlsson58b16b62010-05-27 05:41:06 +0000318}
319
Anders Carlsson5b1319c2010-05-29 20:49:49 +0000320bool EmptySubobjectMap::CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
Anders Carlssona3d43802010-10-31 22:13:23 +0000321 CharUnits Offset) {
Anders Carlsson261febd2010-05-27 00:07:01 +0000322 // If we know this class doesn't have any empty subobjects we don't need to
323 // bother checking.
Anders Carlssona3d43802010-10-31 22:13:23 +0000324 if (SizeOfLargestEmptySubobject.isZero())
Anders Carlsson261febd2010-05-27 00:07:01 +0000325 return true;
326
Anders Carlsson58b16b62010-05-27 05:41:06 +0000327 if (!CanPlaceBaseSubobjectAtOffset(Info, Offset))
328 return false;
Anders Carlsson812a3452010-05-27 18:20:57 +0000329
330 // We are able to place the base at this offset. Make sure to update the
331 // empty base subobject map.
Anders Carlssone3362bc2010-06-13 18:00:18 +0000332 UpdateEmptyBaseSubobjects(Info, Offset, Info->Class->isEmpty());
Anders Carlsson261febd2010-05-27 00:07:01 +0000333 return true;
334}
335
Anders Carlsson812a3452010-05-27 18:20:57 +0000336bool
337EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
338 const CXXRecordDecl *Class,
Anders Carlssona3d43802010-10-31 22:13:23 +0000339 CharUnits Offset) const {
Anders Carlsson2177ab72010-06-08 16:20:35 +0000340 // We don't have to keep looking past the maximum offset that's known to
341 // contain an empty class.
Anders Carlssona3d43802010-10-31 22:13:23 +0000342 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson2177ab72010-06-08 16:20:35 +0000343 return true;
344
Anders Carlssona3d43802010-10-31 22:13:23 +0000345 if (!CanPlaceSubobjectAtOffset(RD, Offset))
Anders Carlsson812a3452010-05-27 18:20:57 +0000346 return false;
347
348 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
349
350 // Traverse all non-virtual bases.
351 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
352 E = RD->bases_end(); I != E; ++I) {
353 if (I->isVirtual())
354 continue;
355
356 const CXXRecordDecl *BaseDecl =
357 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
358
Anders Carlsson6a356742010-11-01 00:21:58 +0000359 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson812a3452010-05-27 18:20:57 +0000360 if (!CanPlaceFieldSubobjectAtOffset(BaseDecl, Class, BaseOffset))
361 return false;
362 }
363
Anders Carlsson45f5b542010-06-08 19:09:24 +0000364 if (RD == Class) {
365 // This is the most derived class, traverse virtual bases as well.
366 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
367 E = RD->vbases_end(); I != E; ++I) {
368 const CXXRecordDecl *VBaseDecl =
369 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
370
Anders Carlsson3069a0d2010-10-31 23:45:59 +0000371 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
Anders Carlsson45f5b542010-06-08 19:09:24 +0000372 if (!CanPlaceFieldSubobjectAtOffset(VBaseDecl, Class, VBaseOffset))
373 return false;
374 }
375 }
376
Anders Carlsson812a3452010-05-27 18:20:57 +0000377 // Traverse all member variables.
378 unsigned FieldNo = 0;
379 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
380 I != E; ++I, ++FieldNo) {
David Blaikie581deb32012-06-06 20:45:41 +0000381 if (I->isBitField())
Anders Carlsson8c6acc62010-10-31 21:54:55 +0000382 continue;
383
Anders Carlssona3d43802010-10-31 22:13:23 +0000384 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
Anders Carlsson812a3452010-05-27 18:20:57 +0000385
David Blaikie581deb32012-06-06 20:45:41 +0000386 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
Anders Carlsson812a3452010-05-27 18:20:57 +0000387 return false;
388 }
389
390 return true;
391}
392
Anders Carlsson8c6acc62010-10-31 21:54:55 +0000393bool
394EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
395 CharUnits Offset) const {
Anders Carlsson2177ab72010-06-08 16:20:35 +0000396 // We don't have to keep looking past the maximum offset that's known to
397 // contain an empty class.
Anders Carlsson8c6acc62010-10-31 21:54:55 +0000398 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson2177ab72010-06-08 16:20:35 +0000399 return true;
400
Anders Carlsson812a3452010-05-27 18:20:57 +0000401 QualType T = FD->getType();
402 if (const RecordType *RT = T->getAs<RecordType>()) {
403 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
Anders Carlssona3d43802010-10-31 22:13:23 +0000404 return CanPlaceFieldSubobjectAtOffset(RD, RD, Offset);
Anders Carlsson812a3452010-05-27 18:20:57 +0000405 }
406
407 // If we have an array type we need to look at every element.
408 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
409 QualType ElemTy = Context.getBaseElementType(AT);
410 const RecordType *RT = ElemTy->getAs<RecordType>();
411 if (!RT)
412 return true;
413
414 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
415 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
416
417 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
Anders Carlsson8c6acc62010-10-31 21:54:55 +0000418 CharUnits ElementOffset = Offset;
Anders Carlsson812a3452010-05-27 18:20:57 +0000419 for (uint64_t I = 0; I != NumElements; ++I) {
Anders Carlsson2177ab72010-06-08 16:20:35 +0000420 // We don't have to keep looking past the maximum offset that's known to
421 // contain an empty class.
Anders Carlsson8c6acc62010-10-31 21:54:55 +0000422 if (!AnyEmptySubobjectsBeyondOffset(ElementOffset))
Anders Carlsson2177ab72010-06-08 16:20:35 +0000423 return true;
424
Anders Carlssona3d43802010-10-31 22:13:23 +0000425 if (!CanPlaceFieldSubobjectAtOffset(RD, RD, ElementOffset))
Anders Carlsson812a3452010-05-27 18:20:57 +0000426 return false;
427
Ken Dyck5f022d82011-02-09 01:59:34 +0000428 ElementOffset += Layout.getSize();
Anders Carlsson812a3452010-05-27 18:20:57 +0000429 }
430 }
431
432 return true;
433}
434
435bool
Anders Carlssona3d43802010-10-31 22:13:23 +0000436EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl *FD,
437 CharUnits Offset) {
438 if (!CanPlaceFieldSubobjectAtOffset(FD, Offset))
Anders Carlsson812a3452010-05-27 18:20:57 +0000439 return false;
440
441 // We are able to place the member variable at this offset.
442 // Make sure to update the empty base subobject map.
443 UpdateEmptyFieldSubobjects(FD, Offset);
444 return true;
445}
446
447void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
448 const CXXRecordDecl *Class,
Anders Carlssona3d43802010-10-31 22:13:23 +0000449 CharUnits Offset) {
Anders Carlsson5ccfdd82010-06-13 17:49:16 +0000450 // We know that the only empty subobjects that can conflict with empty
Anders Carlssone3362bc2010-06-13 18:00:18 +0000451 // field subobjects are subobjects of empty bases that can be placed at offset
Anders Carlsson5ccfdd82010-06-13 17:49:16 +0000452 // zero. Because of this, we only need to keep track of empty field
453 // subobjects with offsets less than the size of the largest empty
454 // subobject for our class.
455 if (Offset >= SizeOfLargestEmptySubobject)
456 return;
457
Anders Carlssona3d43802010-10-31 22:13:23 +0000458 AddSubobjectAtOffset(RD, Offset);
Anders Carlsson812a3452010-05-27 18:20:57 +0000459
460 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
461
462 // Traverse all non-virtual bases.
463 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
464 E = RD->bases_end(); I != E; ++I) {
465 if (I->isVirtual())
466 continue;
467
468 const CXXRecordDecl *BaseDecl =
469 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
470
Anders Carlsson6a356742010-11-01 00:21:58 +0000471 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
Anders Carlsson812a3452010-05-27 18:20:57 +0000472 UpdateEmptyFieldSubobjects(BaseDecl, Class, BaseOffset);
473 }
474
Anders Carlsson45f5b542010-06-08 19:09:24 +0000475 if (RD == Class) {
476 // This is the most derived class, traverse virtual bases as well.
477 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
478 E = RD->vbases_end(); I != E; ++I) {
479 const CXXRecordDecl *VBaseDecl =
480 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
481
Anders Carlsson3069a0d2010-10-31 23:45:59 +0000482 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
Anders Carlsson45f5b542010-06-08 19:09:24 +0000483 UpdateEmptyFieldSubobjects(VBaseDecl, Class, VBaseOffset);
484 }
485 }
486
Anders Carlsson812a3452010-05-27 18:20:57 +0000487 // Traverse all member variables.
488 unsigned FieldNo = 0;
489 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
490 I != E; ++I, ++FieldNo) {
David Blaikie581deb32012-06-06 20:45:41 +0000491 if (I->isBitField())
Anders Carlssonfa84fba2010-11-01 15:14:51 +0000492 continue;
493
Anders Carlssona3d43802010-10-31 22:13:23 +0000494 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
Anders Carlsson812a3452010-05-27 18:20:57 +0000495
David Blaikie581deb32012-06-06 20:45:41 +0000496 UpdateEmptyFieldSubobjects(*I, FieldOffset);
Anders Carlsson812a3452010-05-27 18:20:57 +0000497 }
498}
499
500void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const FieldDecl *FD,
Anders Carlssona3d43802010-10-31 22:13:23 +0000501 CharUnits Offset) {
Anders Carlsson812a3452010-05-27 18:20:57 +0000502 QualType T = FD->getType();
503 if (const RecordType *RT = T->getAs<RecordType>()) {
504 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
505 UpdateEmptyFieldSubobjects(RD, RD, Offset);
506 return;
507 }
508
509 // If we have an array type we need to update every element.
510 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
511 QualType ElemTy = Context.getBaseElementType(AT);
512 const RecordType *RT = ElemTy->getAs<RecordType>();
513 if (!RT)
514 return;
515
516 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
517 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
518
519 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
Anders Carlssona3d43802010-10-31 22:13:23 +0000520 CharUnits ElementOffset = Offset;
Anders Carlsson812a3452010-05-27 18:20:57 +0000521
522 for (uint64_t I = 0; I != NumElements; ++I) {
Anders Carlsson5ccfdd82010-06-13 17:49:16 +0000523 // We know that the only empty subobjects that can conflict with empty
Anders Carlssone3362bc2010-06-13 18:00:18 +0000524 // field subobjects are subobjects of empty bases that can be placed at
Anders Carlsson5ccfdd82010-06-13 17:49:16 +0000525 // offset zero. Because of this, we only need to keep track of empty field
526 // subobjects with offsets less than the size of the largest empty
527 // subobject for our class.
528 if (ElementOffset >= SizeOfLargestEmptySubobject)
529 return;
530
Anders Carlsson812a3452010-05-27 18:20:57 +0000531 UpdateEmptyFieldSubobjects(RD, RD, ElementOffset);
Ken Dyck5f022d82011-02-09 01:59:34 +0000532 ElementOffset += Layout.getSize();
Anders Carlsson812a3452010-05-27 18:20:57 +0000533 }
534 }
535}
536
John McCall441c6232012-05-01 08:55:32 +0000537typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> ClassSetTy;
538
Anders Carlsson7d0918a2010-05-26 05:58:59 +0000539class RecordLayoutBuilder {
Charles Davisc9f8aec2010-08-19 00:55:19 +0000540protected:
Anders Carlsson9392fa62010-05-26 05:41:04 +0000541 // FIXME: Remove this and make the appropriate fields public.
542 friend class clang::ASTContext;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000543
Jay Foad4ba2a172011-01-12 09:06:06 +0000544 const ASTContext &Context;
Anders Carlsson9392fa62010-05-26 05:41:04 +0000545
Anders Carlsson6a91c032010-05-26 15:32:58 +0000546 EmptySubobjectMap *EmptySubobjects;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000547
Anders Carlsson9392fa62010-05-26 05:41:04 +0000548 /// Size - The current size of the record layout.
549 uint64_t Size;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000550
Anders Carlsson9392fa62010-05-26 05:41:04 +0000551 /// Alignment - The current alignment of the record layout.
Ken Dyckea7f6c22011-02-16 02:05:21 +0000552 CharUnits Alignment;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000553
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000554 /// \brief The alignment if attribute packed is not used.
Ken Dyck6feb4bb2011-02-16 02:11:31 +0000555 CharUnits UnpackedAlignment;
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000556
Chris Lattner5f9e2722011-07-23 10:55:15 +0000557 SmallVector<uint64_t, 16> FieldOffsets;
Anders Carlsson9392fa62010-05-26 05:41:04 +0000558
Douglas Gregor453dbcb2012-01-26 07:55:45 +0000559 /// \brief Whether the external AST source has provided a layout for this
560 /// record.
561 unsigned ExternalLayout : 1;
Douglas Gregor394f7b62012-01-28 00:53:29 +0000562
563 /// \brief Whether we need to infer alignment, even when we have an
564 /// externally-provided layout.
565 unsigned InferAlignment : 1;
Douglas Gregor453dbcb2012-01-26 07:55:45 +0000566
Anders Carlsson9392fa62010-05-26 05:41:04 +0000567 /// Packed - Whether the record is packed or not.
Daniel Dunbarc6082fe2010-05-27 05:45:51 +0000568 unsigned Packed : 1;
569
570 unsigned IsUnion : 1;
571
572 unsigned IsMac68kAlign : 1;
Fariborz Jahanian62055b02011-04-26 23:52:16 +0000573
574 unsigned IsMsStruct : 1;
Anders Carlsson9392fa62010-05-26 05:41:04 +0000575
576 /// UnfilledBitsInLastByte - If the last field laid out was a bitfield,
577 /// this contains the number of bits in the last byte that can be used for
578 /// an adjacent bitfield if necessary.
579 unsigned char UnfilledBitsInLastByte;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000580
Anders Carlsson9392fa62010-05-26 05:41:04 +0000581 /// MaxFieldAlignment - The maximum allowed field alignment. This is set by
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000582 /// #pragma pack.
Ken Dyck834945c2011-02-17 01:49:42 +0000583 CharUnits MaxFieldAlignment;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000584
Anders Carlsson9392fa62010-05-26 05:41:04 +0000585 /// DataSize - The data size of the record being laid out.
586 uint64_t DataSize;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000587
Ken Dycka1fdb0b2011-02-16 01:52:01 +0000588 CharUnits NonVirtualSize;
Ken Dyckdf205382011-02-16 01:43:15 +0000589 CharUnits NonVirtualAlignment;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000590
Fariborz Jahanian855a8e72011-05-03 20:21:04 +0000591 FieldDecl *ZeroLengthBitfield;
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000592
Anders Carlsson9392fa62010-05-26 05:41:04 +0000593 /// PrimaryBase - the primary base class (if one exists) of the class
594 /// we're laying out.
595 const CXXRecordDecl *PrimaryBase;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000596
Anders Carlsson9392fa62010-05-26 05:41:04 +0000597 /// PrimaryBaseIsVirtual - Whether the primary base of the class we're laying
598 /// out is virtual.
599 bool PrimaryBaseIsVirtual;
600
John McCall441c6232012-05-01 08:55:32 +0000601 /// HasOwnVFPtr - Whether the class provides its own vtable/vftbl
602 /// pointer, as opposed to inheriting one from a primary base class.
603 bool HasOwnVFPtr;
Eli Friedman227e4832011-10-21 22:49:56 +0000604
Eli Friedman2fe36362011-09-27 19:12:27 +0000605 /// VBPtrOffset - Virtual base table offset. Only for MS layout.
606 CharUnits VBPtrOffset;
607
Anders Carlsson376bda92010-10-31 21:01:46 +0000608 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000609
Anders Carlsson9392fa62010-05-26 05:41:04 +0000610 /// Bases - base classes and their offsets in the record.
611 BaseOffsetsMapTy Bases;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000612
Anders Carlsson9392fa62010-05-26 05:41:04 +0000613 // VBases - virtual base classes and their offsets in the record.
John McCall441c6232012-05-01 08:55:32 +0000614 ASTRecordLayout::VBaseOffsetsMapTy VBases;
Anders Carlsson9392fa62010-05-26 05:41:04 +0000615
616 /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are
617 /// primary base classes for some other direct or indirect base class.
Anders Carlsson245656e2010-11-24 22:55:48 +0000618 CXXIndirectPrimaryBaseSet IndirectPrimaryBases;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000619
Anders Carlsson9392fa62010-05-26 05:41:04 +0000620 /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in
621 /// inheritance graph order. Used for determining the primary base class.
622 const CXXRecordDecl *FirstNearlyEmptyVBase;
623
624 /// VisitedVirtualBases - A set of all the visited virtual bases, used to
625 /// avoid visiting virtual bases more than once.
626 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000627
Douglas Gregor453dbcb2012-01-26 07:55:45 +0000628 /// \brief Externally-provided size.
629 uint64_t ExternalSize;
630
631 /// \brief Externally-provided alignment.
632 uint64_t ExternalAlign;
633
634 /// \brief Externally-provided field offsets.
635 llvm::DenseMap<const FieldDecl *, uint64_t> ExternalFieldOffsets;
636
637 /// \brief Externally-provided direct, non-virtual base offsets.
638 llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalBaseOffsets;
639
640 /// \brief Externally-provided virtual base offsets.
641 llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalVirtualBaseOffsets;
642
John McCall9da23522011-11-08 04:01:03 +0000643 RecordLayoutBuilder(const ASTContext &Context,
644 EmptySubobjectMap *EmptySubobjects)
Ken Dyckea7f6c22011-02-16 02:05:21 +0000645 : Context(Context), EmptySubobjects(EmptySubobjects), Size(0),
John McCall9da23522011-11-08 04:01:03 +0000646 Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()),
Douglas Gregor394f7b62012-01-28 00:53:29 +0000647 ExternalLayout(false), InferAlignment(false),
648 Packed(false), IsUnion(false), IsMac68kAlign(false), IsMsStruct(false),
Ken Dyck834945c2011-02-17 01:49:42 +0000649 UnfilledBitsInLastByte(0), MaxFieldAlignment(CharUnits::Zero()),
650 DataSize(0), NonVirtualSize(CharUnits::Zero()),
Fariborz Jahanian340fa242011-05-02 17:20:56 +0000651 NonVirtualAlignment(CharUnits::One()),
Fariborz Jahanian855a8e72011-05-03 20:21:04 +0000652 ZeroLengthBitfield(0), PrimaryBase(0),
Eli Friedman227e4832011-10-21 22:49:56 +0000653 PrimaryBaseIsVirtual(false),
John McCall441c6232012-05-01 08:55:32 +0000654 HasOwnVFPtr(false),
Eli Friedman227e4832011-10-21 22:49:56 +0000655 VBPtrOffset(CharUnits::fromQuantity(-1)),
Eli Friedman2fe36362011-09-27 19:12:27 +0000656 FirstNearlyEmptyVBase(0) { }
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000657
John McCall9da23522011-11-08 04:01:03 +0000658 /// Reset this RecordLayoutBuilder to a fresh state, using the given
659 /// alignment as the initial alignment. This is used for the
660 /// correct layout of vb-table pointers in MSVC.
661 void resetWithTargetAlignment(CharUnits TargetAlignment) {
662 const ASTContext &Context = this->Context;
663 EmptySubobjectMap *EmptySubobjects = this->EmptySubobjects;
664 this->~RecordLayoutBuilder();
665 new (this) RecordLayoutBuilder(Context, EmptySubobjects);
666 Alignment = UnpackedAlignment = TargetAlignment;
667 }
668
Anders Carlsson9392fa62010-05-26 05:41:04 +0000669 void Layout(const RecordDecl *D);
Anders Carlssonc6cab682010-05-26 15:10:00 +0000670 void Layout(const CXXRecordDecl *D);
Anders Carlsson9392fa62010-05-26 05:41:04 +0000671 void Layout(const ObjCInterfaceDecl *D);
672
673 void LayoutFields(const RecordDecl *D);
674 void LayoutField(const FieldDecl *D);
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000675 void LayoutWideBitField(uint64_t FieldSize, uint64_t TypeSize,
676 bool FieldPacked, const FieldDecl *D);
Anders Carlsson9392fa62010-05-26 05:41:04 +0000677 void LayoutBitField(const FieldDecl *D);
John McCall9da23522011-11-08 04:01:03 +0000678
679 bool isMicrosoftCXXABI() const {
680 return Context.getTargetInfo().getCXXABI() == CXXABI_Microsoft;
681 }
682
Eli Friedman2fe36362011-09-27 19:12:27 +0000683 void MSLayoutVirtualBases(const CXXRecordDecl *RD);
Anders Carlsson9392fa62010-05-26 05:41:04 +0000684
Anders Carlsson6e264542010-05-29 17:35:14 +0000685 /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects.
686 llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator;
687
688 typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *>
689 BaseSubobjectInfoMapTy;
690
691 /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases
692 /// of the class we're laying out to their base subobject info.
693 BaseSubobjectInfoMapTy VirtualBaseInfo;
694
695 /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the
696 /// class we're laying out to their base subobject info.
697 BaseSubobjectInfoMapTy NonVirtualBaseInfo;
698
699 /// ComputeBaseSubobjectInfo - Compute the base subobject information for the
700 /// bases of the given class.
701 void ComputeBaseSubobjectInfo(const CXXRecordDecl *RD);
702
703 /// ComputeBaseSubobjectInfo - Compute the base subobject information for a
704 /// single class and all of its base classes.
705 BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
706 bool IsVirtual,
707 BaseSubobjectInfo *Derived);
Anders Carlsson9392fa62010-05-26 05:41:04 +0000708
709 /// DeterminePrimaryBase - Determine the primary base of the given class.
710 void DeterminePrimaryBase(const CXXRecordDecl *RD);
711
712 void SelectPrimaryVBase(const CXXRecordDecl *RD);
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000713
Eli Friedman227e4832011-10-21 22:49:56 +0000714 void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign);
Charles Davisc9f8aec2010-08-19 00:55:19 +0000715
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000716 /// LayoutNonVirtualBases - Determines the primary base class (if any) and
Anders Carlsson9392fa62010-05-26 05:41:04 +0000717 /// lays it out. Will then proceed to lay out all non-virtual base clasess.
718 void LayoutNonVirtualBases(const CXXRecordDecl *RD);
719
720 /// LayoutNonVirtualBase - Lays out a single non-virtual base.
Anders Carlsson07cebc52010-05-29 17:42:25 +0000721 void LayoutNonVirtualBase(const BaseSubobjectInfo *Base);
Anders Carlsson9392fa62010-05-26 05:41:04 +0000722
Anders Carlssona2311512010-10-31 22:20:42 +0000723 void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
724 CharUnits Offset);
Anders Carlsson9392fa62010-05-26 05:41:04 +0000725
John McCall9da23522011-11-08 04:01:03 +0000726 bool needsVFTable(const CXXRecordDecl *RD) const;
John McCall441c6232012-05-01 08:55:32 +0000727 bool hasNewVirtualFunction(const CXXRecordDecl *RD,
728 bool IgnoreDestructor = false) const;
John McCall9da23522011-11-08 04:01:03 +0000729 bool isPossiblePrimaryBase(const CXXRecordDecl *Base) const;
Eli Friedman97c0aef2011-10-18 00:55:28 +0000730
John McCall441c6232012-05-01 08:55:32 +0000731 void computeVtordisps(const CXXRecordDecl *RD,
732 ClassSetTy &VtordispVBases);
733
Anders Carlsson9392fa62010-05-26 05:41:04 +0000734 /// LayoutVirtualBases - Lays out all the virtual bases.
735 void LayoutVirtualBases(const CXXRecordDecl *RD,
736 const CXXRecordDecl *MostDerivedClass);
737
738 /// LayoutVirtualBase - Lays out a single virtual base.
John McCall441c6232012-05-01 08:55:32 +0000739 void LayoutVirtualBase(const BaseSubobjectInfo *Base,
740 bool IsVtordispNeed = false);
Anders Carlsson9392fa62010-05-26 05:41:04 +0000741
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +0000742 /// LayoutBase - Will lay out a base and return the offset where it was
Anders Carlssona2311512010-10-31 22:20:42 +0000743 /// placed, in chars.
744 CharUnits LayoutBase(const BaseSubobjectInfo *Base);
Anders Carlsson9392fa62010-05-26 05:41:04 +0000745
Anders Carlssonc6cab682010-05-26 15:10:00 +0000746 /// InitializeLayout - Initialize record layout for the given record decl.
Daniel Dunbarc6082fe2010-05-27 05:45:51 +0000747 void InitializeLayout(const Decl *D);
Anders Carlssonc6cab682010-05-26 15:10:00 +0000748
Anders Carlsson9392fa62010-05-26 05:41:04 +0000749 /// FinishLayout - Finalize record layout. Adjust record size based on the
750 /// alignment.
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000751 void FinishLayout(const NamedDecl *D);
Anders Carlsson9392fa62010-05-26 05:41:04 +0000752
Ken Dyck3263e092011-02-19 18:58:07 +0000753 void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment);
754 void UpdateAlignment(CharUnits NewAlignment) {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000755 UpdateAlignment(NewAlignment, NewAlignment);
756 }
757
Douglas Gregor394f7b62012-01-28 00:53:29 +0000758 /// \brief Retrieve the externally-supplied field offset for the given
759 /// field.
760 ///
761 /// \param Field The field whose offset is being queried.
762 /// \param ComputedOffset The offset that we've computed for this field.
763 uint64_t updateExternalFieldOffset(const FieldDecl *Field,
764 uint64_t ComputedOffset);
765
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +0000766 void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset,
767 uint64_t UnpackedOffset, unsigned UnpackedAlign,
768 bool isPacked, const FieldDecl *D);
769
770 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
Anders Carlsson9392fa62010-05-26 05:41:04 +0000771
Ken Dycka0c21c42011-02-24 01:13:28 +0000772 CharUnits getSize() const {
Ken Dyck99113442011-02-24 01:33:05 +0000773 assert(Size % Context.getCharWidth() == 0);
Ken Dycka0c21c42011-02-24 01:13:28 +0000774 return Context.toCharUnitsFromBits(Size);
775 }
776 uint64_t getSizeInBits() const { return Size; }
777
778 void setSize(CharUnits NewSize) { Size = Context.toBits(NewSize); }
779 void setSize(uint64_t NewSize) { Size = NewSize; }
780
Eli Friedman2fe36362011-09-27 19:12:27 +0000781 CharUnits getAligment() const { return Alignment; }
782
Ken Dycka0c21c42011-02-24 01:13:28 +0000783 CharUnits getDataSize() const {
Ken Dyck99113442011-02-24 01:33:05 +0000784 assert(DataSize % Context.getCharWidth() == 0);
Ken Dycka0c21c42011-02-24 01:13:28 +0000785 return Context.toCharUnitsFromBits(DataSize);
786 }
787 uint64_t getDataSizeInBits() const { return DataSize; }
788
789 void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); }
790 void setDataSize(uint64_t NewSize) { DataSize = NewSize; }
791
Argyrios Kyrtzidisc83d2d72010-08-15 10:17:39 +0000792 RecordLayoutBuilder(const RecordLayoutBuilder&); // DO NOT IMPLEMENT
793 void operator=(const RecordLayoutBuilder&); // DO NOT IMPLEMENT
Anders Carlsson9392fa62010-05-26 05:41:04 +0000794public:
795 static const CXXMethodDecl *ComputeKeyFunction(const CXXRecordDecl *RD);
796};
Benjamin Kramer7e220282010-05-26 09:58:31 +0000797} // end anonymous namespace
Anders Carlsson9392fa62010-05-26 05:41:04 +0000798
Anders Carlsson3f066522009-09-22 03:02:06 +0000799void
Anders Carlsson7d0918a2010-05-26 05:58:59 +0000800RecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) {
Anders Carlsson584e1df2010-03-11 03:39:12 +0000801 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +0000802 E = RD->bases_end(); I != E; ++I) {
Anders Carlsson584e1df2010-03-11 03:39:12 +0000803 assert(!I->getType()->isDependentType() &&
Sebastian Redl9994a342009-10-25 17:03:50 +0000804 "Cannot layout class with dependent bases.");
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +0000805
Mike Stump1eb44332009-09-09 15:08:12 +0000806 const CXXRecordDecl *Base =
Anders Carlsson584e1df2010-03-11 03:39:12 +0000807 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson200c5c22010-03-11 00:15:35 +0000808
Anders Carlsson584e1df2010-03-11 03:39:12 +0000809 // Check if this is a nearly empty virtual base.
Anders Carlssondae0cb52010-11-25 01:51:53 +0000810 if (I->isVirtual() && Context.isNearlyEmpty(Base)) {
Anders Carlsson584e1df2010-03-11 03:39:12 +0000811 // If it's not an indirect primary base, then we've found our primary
812 // base.
Anders Carlsson3f066522009-09-22 03:02:06 +0000813 if (!IndirectPrimaryBases.count(Base)) {
Anders Carlsson28fdd0a2010-05-26 05:20:58 +0000814 PrimaryBase = Base;
815 PrimaryBaseIsVirtual = true;
Mike Stumpd76264e2009-08-12 21:50:08 +0000816 return;
817 }
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +0000818
Anders Carlsson584e1df2010-03-11 03:39:12 +0000819 // Is this the first nearly empty virtual base?
820 if (!FirstNearlyEmptyVBase)
821 FirstNearlyEmptyVBase = Base;
Mike Stumpd76264e2009-08-12 21:50:08 +0000822 }
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +0000823
Anders Carlsson200c5c22010-03-11 00:15:35 +0000824 SelectPrimaryVBase(Base);
Anders Carlsson28fdd0a2010-05-26 05:20:58 +0000825 if (PrimaryBase)
Zhongxing Xu94ba3802010-02-15 04:28:35 +0000826 return;
Mike Stumpd76264e2009-08-12 21:50:08 +0000827 }
828}
829
Anders Carlsson200c5c22010-03-11 00:15:35 +0000830/// DeterminePrimaryBase - Determine the primary base of the given class.
Anders Carlsson7d0918a2010-05-26 05:58:59 +0000831void RecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) {
Anders Carlsson200c5c22010-03-11 00:15:35 +0000832 // If the class isn't dynamic, it won't have a primary base.
833 if (!RD->isDynamicClass())
834 return;
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +0000835
Anders Carlsson3f066522009-09-22 03:02:06 +0000836 // Compute all the primary virtual bases for all of our direct and
Mike Stump0880e752009-08-13 23:26:06 +0000837 // indirect bases, and record all their primary virtual base classes.
Anders Carlsson245656e2010-11-24 22:55:48 +0000838 RD->getIndirectPrimaryBases(IndirectPrimaryBases);
Mike Stump0880e752009-08-13 23:26:06 +0000839
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +0000840 // If the record has a dynamic base class, attempt to choose a primary base
841 // class. It is the first (in direct base class order) non-virtual dynamic
Anders Carlsson3f066522009-09-22 03:02:06 +0000842 // base class, if one exists.
Mike Stump6f376332009-08-05 22:37:18 +0000843 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +0000844 e = RD->bases_end(); i != e; ++i) {
Anders Carlssonce2009a2009-11-27 22:05:05 +0000845 // Ignore virtual bases.
846 if (i->isVirtual())
847 continue;
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +0000848
Anders Carlssonce2009a2009-11-27 22:05:05 +0000849 const CXXRecordDecl *Base =
850 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
851
John McCall9da23522011-11-08 04:01:03 +0000852 if (isPossiblePrimaryBase(Base)) {
Anders Carlssonce2009a2009-11-27 22:05:05 +0000853 // We found it.
Anders Carlsson28fdd0a2010-05-26 05:20:58 +0000854 PrimaryBase = Base;
855 PrimaryBaseIsVirtual = false;
Anders Carlssonce2009a2009-11-27 22:05:05 +0000856 return;
Mike Stump6f376332009-08-05 22:37:18 +0000857 }
858 }
859
Eli Friedman97c0aef2011-10-18 00:55:28 +0000860 // The Microsoft ABI doesn't have primary virtual bases.
John McCall9da23522011-11-08 04:01:03 +0000861 if (isMicrosoftCXXABI()) {
Eli Friedman97c0aef2011-10-18 00:55:28 +0000862 assert(!PrimaryBase && "Should not get here with a primary base!");
863 return;
864 }
865
866 // Under the Itanium ABI, if there is no non-virtual primary base class,
867 // try to compute the primary virtual base. The primary virtual base is
868 // the first nearly empty virtual base that is not an indirect primary
869 // virtual base class, if one exists.
Anders Carlsson200c5c22010-03-11 00:15:35 +0000870 if (RD->getNumVBases() != 0) {
871 SelectPrimaryVBase(RD);
Anders Carlsson28fdd0a2010-05-26 05:20:58 +0000872 if (PrimaryBase)
Anders Carlsson200c5c22010-03-11 00:15:35 +0000873 return;
874 }
Mike Stump6f376332009-08-05 22:37:18 +0000875
Eli Friedman97c0aef2011-10-18 00:55:28 +0000876 // Otherwise, it is the first indirect primary base class, if one exists.
Anders Carlsson200c5c22010-03-11 00:15:35 +0000877 if (FirstNearlyEmptyVBase) {
Anders Carlsson28fdd0a2010-05-26 05:20:58 +0000878 PrimaryBase = FirstNearlyEmptyVBase;
879 PrimaryBaseIsVirtual = true;
Mike Stump6f376332009-08-05 22:37:18 +0000880 return;
Anders Carlsson200c5c22010-03-11 00:15:35 +0000881 }
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +0000882
Anders Carlsson28fdd0a2010-05-26 05:20:58 +0000883 assert(!PrimaryBase && "Should not get here with a primary base!");
Mike Stump6f376332009-08-05 22:37:18 +0000884}
885
Anders Carlsson6e264542010-05-29 17:35:14 +0000886BaseSubobjectInfo *
887RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
888 bool IsVirtual,
889 BaseSubobjectInfo *Derived) {
890 BaseSubobjectInfo *Info;
891
892 if (IsVirtual) {
893 // Check if we already have info about this virtual base.
894 BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD];
895 if (InfoSlot) {
896 assert(InfoSlot->Class == RD && "Wrong class for virtual base info!");
897 return InfoSlot;
898 }
899
900 // We don't, create it.
901 InfoSlot = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
902 Info = InfoSlot;
903 } else {
904 Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
905 }
906
907 Info->Class = RD;
908 Info->IsVirtual = IsVirtual;
909 Info->Derived = 0;
910 Info->PrimaryVirtualBaseInfo = 0;
911
912 const CXXRecordDecl *PrimaryVirtualBase = 0;
913 BaseSubobjectInfo *PrimaryVirtualBaseInfo = 0;
914
915 // Check if this base has a primary virtual base.
916 if (RD->getNumVBases()) {
917 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlssonc9e814b2010-11-24 23:12:57 +0000918 if (Layout.isPrimaryBaseVirtual()) {
Anders Carlsson6e264542010-05-29 17:35:14 +0000919 // This base does have a primary virtual base.
920 PrimaryVirtualBase = Layout.getPrimaryBase();
921 assert(PrimaryVirtualBase && "Didn't have a primary virtual base!");
922
923 // Now check if we have base subobject info about this primary base.
924 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
925
926 if (PrimaryVirtualBaseInfo) {
927 if (PrimaryVirtualBaseInfo->Derived) {
928 // We did have info about this primary base, and it turns out that it
929 // has already been claimed as a primary virtual base for another
930 // base.
931 PrimaryVirtualBase = 0;
932 } else {
933 // We can claim this base as our primary base.
934 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
935 PrimaryVirtualBaseInfo->Derived = Info;
936 }
937 }
938 }
939 }
940
941 // Now go through all direct bases.
942 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
943 E = RD->bases_end(); I != E; ++I) {
944 bool IsVirtual = I->isVirtual();
945
946 const CXXRecordDecl *BaseDecl =
947 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
948
949 Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info));
950 }
951
952 if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) {
953 // Traversing the bases must have created the base info for our primary
954 // virtual base.
955 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
956 assert(PrimaryVirtualBaseInfo &&
957 "Did not create a primary virtual base!");
958
959 // Claim the primary virtual base as our primary virtual base.
960 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
961 PrimaryVirtualBaseInfo->Derived = Info;
962 }
963
964 return Info;
965}
966
967void RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD) {
968 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
969 E = RD->bases_end(); I != E; ++I) {
970 bool IsVirtual = I->isVirtual();
971
972 const CXXRecordDecl *BaseDecl =
973 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
974
975 // Compute the base subobject info for this base.
976 BaseSubobjectInfo *Info = ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, 0);
977
978 if (IsVirtual) {
979 // ComputeBaseInfo has already added this base for us.
980 assert(VirtualBaseInfo.count(BaseDecl) &&
981 "Did not add virtual base!");
982 } else {
983 // Add the base info to the map of non-virtual bases.
984 assert(!NonVirtualBaseInfo.count(BaseDecl) &&
985 "Non-virtual base already exists!");
986 NonVirtualBaseInfo.insert(std::make_pair(BaseDecl, Info));
987 }
988 }
989}
990
Anders Carlssone239b9d2010-03-10 22:21:28 +0000991void
Eli Friedman227e4832011-10-21 22:49:56 +0000992RecordLayoutBuilder::EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign) {
Eli Friedman97c0aef2011-10-18 00:55:28 +0000993 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
994
995 // The maximum field alignment overrides base align.
996 if (!MaxFieldAlignment.isZero()) {
997 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
998 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
999 }
1000
1001 // Round up the current record size to pointer alignment.
Eli Friedman227e4832011-10-21 22:49:56 +00001002 setSize(getSize().RoundUpToAlignment(BaseAlign));
1003 setDataSize(getSize());
Eli Friedman97c0aef2011-10-18 00:55:28 +00001004
1005 // Update the alignment.
1006 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
1007}
1008
1009void
Anders Carlsson7d0918a2010-05-26 05:58:59 +00001010RecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl *RD) {
Anders Carlsson6e264542010-05-29 17:35:14 +00001011 // Then, determine the primary base class.
Anders Carlsson200c5c22010-03-11 00:15:35 +00001012 DeterminePrimaryBase(RD);
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001013
Anders Carlsson6e264542010-05-29 17:35:14 +00001014 // Compute base subobject info.
1015 ComputeBaseSubobjectInfo(RD);
1016
Anders Carlsson200c5c22010-03-11 00:15:35 +00001017 // If we have a primary base class, lay it out.
Anders Carlsson28fdd0a2010-05-26 05:20:58 +00001018 if (PrimaryBase) {
1019 if (PrimaryBaseIsVirtual) {
Anders Carlsson6e264542010-05-29 17:35:14 +00001020 // If the primary virtual base was a primary virtual base of some other
1021 // base class we'll have to steal it.
1022 BaseSubobjectInfo *PrimaryBaseInfo = VirtualBaseInfo.lookup(PrimaryBase);
1023 PrimaryBaseInfo->Derived = 0;
1024
Anders Carlsson200c5c22010-03-11 00:15:35 +00001025 // We have a virtual primary base, insert it as an indirect primary base.
Anders Carlsson28fdd0a2010-05-26 05:20:58 +00001026 IndirectPrimaryBases.insert(PrimaryBase);
Anders Carlsson37147ea2010-03-11 05:42:17 +00001027
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001028 assert(!VisitedVirtualBases.count(PrimaryBase) &&
Anders Carlsson28fdd0a2010-05-26 05:20:58 +00001029 "vbase already visited!");
1030 VisitedVirtualBases.insert(PrimaryBase);
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001031
Anders Carlsson276b4912010-05-29 17:48:36 +00001032 LayoutVirtualBase(PrimaryBaseInfo);
Anders Carlsson07cebc52010-05-29 17:42:25 +00001033 } else {
1034 BaseSubobjectInfo *PrimaryBaseInfo =
1035 NonVirtualBaseInfo.lookup(PrimaryBase);
1036 assert(PrimaryBaseInfo &&
1037 "Did not find base info for non-virtual primary base!");
1038
1039 LayoutNonVirtualBase(PrimaryBaseInfo);
1040 }
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001041
John McCall9da23522011-11-08 04:01:03 +00001042 // If this class needs a vtable/vf-table and didn't get one from a
1043 // primary base, add it in now.
1044 } else if (needsVFTable(RD)) {
Eli Friedman97c0aef2011-10-18 00:55:28 +00001045 assert(DataSize == 0 && "Vtable pointer must be at offset zero!");
Eli Friedman97c0aef2011-10-18 00:55:28 +00001046 CharUnits PtrWidth =
1047 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Eli Friedman227e4832011-10-21 22:49:56 +00001048 CharUnits PtrAlign =
1049 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
1050 EnsureVTablePointerAlignment(PtrAlign);
John McCall441c6232012-05-01 08:55:32 +00001051 HasOwnVFPtr = true;
Eli Friedman97c0aef2011-10-18 00:55:28 +00001052 setSize(getSize() + PtrWidth);
1053 setDataSize(getSize());
1054 }
1055
John McCall9da23522011-11-08 04:01:03 +00001056 bool HasDirectVirtualBases = false;
1057 bool HasNonVirtualBaseWithVBTable = false;
1058
Anders Carlsson200c5c22010-03-11 00:15:35 +00001059 // Now lay out the non-virtual bases.
1060 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001061 E = RD->bases_end(); I != E; ++I) {
Anders Carlsson200c5c22010-03-11 00:15:35 +00001062
John McCall9da23522011-11-08 04:01:03 +00001063 // Ignore virtual bases, but remember that we saw one.
1064 if (I->isVirtual()) {
1065 HasDirectVirtualBases = true;
Anders Carlsson200c5c22010-03-11 00:15:35 +00001066 continue;
John McCall9da23522011-11-08 04:01:03 +00001067 }
Anders Carlsson200c5c22010-03-11 00:15:35 +00001068
Anders Carlsson07cebc52010-05-29 17:42:25 +00001069 const CXXRecordDecl *BaseDecl =
John McCall9da23522011-11-08 04:01:03 +00001070 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
Anders Carlsson200c5c22010-03-11 00:15:35 +00001071
John McCall9da23522011-11-08 04:01:03 +00001072 // Remember if this base has virtual bases itself.
1073 if (BaseDecl->getNumVBases())
1074 HasNonVirtualBaseWithVBTable = true;
1075
1076 // Skip the primary base, because we've already laid it out. The
1077 // !PrimaryBaseIsVirtual check is required because we might have a
1078 // non-virtual base of the same type as a primary virtual base.
Anders Carlsson07cebc52010-05-29 17:42:25 +00001079 if (BaseDecl == PrimaryBase && !PrimaryBaseIsVirtual)
Anders Carlsson200c5c22010-03-11 00:15:35 +00001080 continue;
1081
1082 // Lay out the base.
Anders Carlsson07cebc52010-05-29 17:42:25 +00001083 BaseSubobjectInfo *BaseInfo = NonVirtualBaseInfo.lookup(BaseDecl);
1084 assert(BaseInfo && "Did not find base info for non-virtual base!");
1085
1086 LayoutNonVirtualBase(BaseInfo);
Anders Carlssone239b9d2010-03-10 22:21:28 +00001087 }
Eli Friedman97c0aef2011-10-18 00:55:28 +00001088
John McCall9da23522011-11-08 04:01:03 +00001089 // In the MS ABI, add the vb-table pointer if we need one, which is
1090 // whenever we have a virtual base and we can't re-use a vb-table
1091 // pointer from a non-virtual base.
1092 if (isMicrosoftCXXABI() &&
1093 HasDirectVirtualBases && !HasNonVirtualBaseWithVBTable) {
Eli Friedman97c0aef2011-10-18 00:55:28 +00001094 CharUnits PtrWidth =
1095 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Eli Friedman227e4832011-10-21 22:49:56 +00001096 CharUnits PtrAlign =
1097 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
John McCall9da23522011-11-08 04:01:03 +00001098
1099 // MSVC potentially over-aligns the vb-table pointer by giving it
1100 // the max alignment of all the non-virtual objects in the class.
1101 // This is completely unnecessary, but we're not here to pass
1102 // judgment.
1103 //
1104 // Note that we've only laid out the non-virtual bases, so on the
1105 // first pass Alignment won't be set correctly here, but if the
1106 // vb-table doesn't end up aligned correctly we'll come through
1107 // and redo the layout from scratch with the right alignment.
1108 //
1109 // TODO: Instead of doing this, just lay out the fields as if the
1110 // vb-table were at offset zero, then retroactively bump the field
1111 // offsets up.
Eli Friedman227e4832011-10-21 22:49:56 +00001112 PtrAlign = std::max(PtrAlign, Alignment);
John McCall9da23522011-11-08 04:01:03 +00001113
1114 EnsureVTablePointerAlignment(PtrAlign);
1115 VBPtrOffset = getSize();
1116 setSize(getSize() + PtrWidth);
1117 setDataSize(getSize());
Eli Friedman97c0aef2011-10-18 00:55:28 +00001118 }
Anders Carlssone239b9d2010-03-10 22:21:28 +00001119}
1120
Anders Carlsson07cebc52010-05-29 17:42:25 +00001121void RecordLayoutBuilder::LayoutNonVirtualBase(const BaseSubobjectInfo *Base) {
Anders Carlssone3bdbee2010-03-10 22:26:24 +00001122 // Layout the base.
Anders Carlssona2311512010-10-31 22:20:42 +00001123 CharUnits Offset = LayoutBase(Base);
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001124
Anders Carlssone3bdbee2010-03-10 22:26:24 +00001125 // Add its base class offset.
Anders Carlsson07cebc52010-05-29 17:42:25 +00001126 assert(!Bases.count(Base->Class) && "base offset already exists!");
Anders Carlssona2311512010-10-31 22:20:42 +00001127 Bases.insert(std::make_pair(Base->Class, Offset));
Anders Carlsson3cd09cc2010-05-29 19:44:50 +00001128
1129 AddPrimaryVirtualBaseOffsets(Base, Offset);
Anders Carlssone239b9d2010-03-10 22:21:28 +00001130}
Mike Stump968db332009-11-05 04:02:15 +00001131
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001132void
Anders Carlsson3cd09cc2010-05-29 19:44:50 +00001133RecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
Anders Carlssona2311512010-10-31 22:20:42 +00001134 CharUnits Offset) {
Anders Carlsson3cd09cc2010-05-29 19:44:50 +00001135 // This base isn't interesting, it has no virtual bases.
1136 if (!Info->Class->getNumVBases())
1137 return;
1138
1139 // First, check if we have a virtual primary base to add offsets for.
1140 if (Info->PrimaryVirtualBaseInfo) {
1141 assert(Info->PrimaryVirtualBaseInfo->IsVirtual &&
1142 "Primary virtual base is not virtual!");
1143 if (Info->PrimaryVirtualBaseInfo->Derived == Info) {
1144 // Add the offset.
1145 assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) &&
1146 "primary vbase offset already exists!");
1147 VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class,
John McCall441c6232012-05-01 08:55:32 +00001148 ASTRecordLayout::VBaseInfo(Offset, false)));
Anders Carlsson97913572010-04-15 16:12:58 +00001149
Anders Carlsson3cd09cc2010-05-29 19:44:50 +00001150 // Traverse the primary virtual base.
1151 AddPrimaryVirtualBaseOffsets(Info->PrimaryVirtualBaseInfo, Offset);
1152 }
Anders Carlsson97913572010-04-15 16:12:58 +00001153 }
1154
Anders Carlsson3cd09cc2010-05-29 19:44:50 +00001155 // Now go through all direct non-virtual bases.
1156 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
1157 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
1158 const BaseSubobjectInfo *Base = Info->Bases[I];
1159 if (Base->IsVirtual)
Anders Carlsson97913572010-04-15 16:12:58 +00001160 continue;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001161
Anders Carlsson6a356742010-11-01 00:21:58 +00001162 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlsson3cd09cc2010-05-29 19:44:50 +00001163 AddPrimaryVirtualBaseOffsets(Base, BaseOffset);
Anders Carlsson97913572010-04-15 16:12:58 +00001164 }
1165}
1166
John McCall9da23522011-11-08 04:01:03 +00001167/// needsVFTable - Return true if this class needs a vtable or vf-table
1168/// when laid out as a base class. These are treated the same because
1169/// they're both always laid out at offset zero.
1170///
1171/// This function assumes that the class has no primary base.
1172bool RecordLayoutBuilder::needsVFTable(const CXXRecordDecl *RD) const {
1173 assert(!PrimaryBase);
1174
1175 // In the Itanium ABI, every dynamic class needs a vtable: even if
1176 // this class has no virtual functions as a base class (i.e. it's
1177 // non-polymorphic or only has virtual functions from virtual
1178 // bases),x it still needs a vtable to locate its virtual bases.
1179 if (!isMicrosoftCXXABI())
1180 return RD->isDynamicClass();
1181
1182 // In the MS ABI, we need a vfptr if the class has virtual functions
1183 // other than those declared by its virtual bases. The AST doesn't
1184 // tell us that directly, and checking manually for virtual
1185 // functions that aren't overrides is expensive, but there are
1186 // some important shortcuts:
1187
1188 // - Non-polymorphic classes have no virtual functions at all.
1189 if (!RD->isPolymorphic()) return false;
1190
1191 // - Polymorphic classes with no virtual bases must either declare
1192 // virtual functions directly or inherit them, but in the latter
1193 // case we would have a primary base.
1194 if (RD->getNumVBases() == 0) return true;
1195
1196 return hasNewVirtualFunction(RD);
1197}
1198
John McCall441c6232012-05-01 08:55:32 +00001199/// Does the given class inherit non-virtually from any of the classes
1200/// in the given set?
1201static bool hasNonVirtualBaseInSet(const CXXRecordDecl *RD,
1202 const ClassSetTy &set) {
1203 for (CXXRecordDecl::base_class_const_iterator
1204 I = RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
1205 // Ignore virtual links.
1206 if (I->isVirtual()) continue;
1207
1208 // Check whether the set contains the base.
1209 const CXXRecordDecl *base = I->getType()->getAsCXXRecordDecl();
1210 if (set.count(base))
1211 return true;
1212
1213 // Otherwise, recurse and propagate.
1214 if (hasNonVirtualBaseInSet(base, set))
1215 return true;
1216 }
1217
1218 return false;
1219}
1220
1221/// Does the given method (B::foo()) already override a method (A::foo())
1222/// such that A requires a vtordisp in B? If so, we don't need to add a
1223/// new vtordisp for B in a yet-more-derived class C providing C::foo().
1224static bool overridesMethodRequiringVtorDisp(const ASTContext &Context,
1225 const CXXMethodDecl *M) {
1226 CXXMethodDecl::method_iterator
1227 I = M->begin_overridden_methods(), E = M->end_overridden_methods();
1228 if (I == E) return false;
1229
1230 const ASTRecordLayout::VBaseOffsetsMapTy &offsets =
1231 Context.getASTRecordLayout(M->getParent()).getVBaseOffsetsMap();
1232 do {
1233 const CXXMethodDecl *overridden = *I;
1234
1235 // If the overridden method's class isn't recognized as a virtual
1236 // base in the derived class, ignore it.
1237 ASTRecordLayout::VBaseOffsetsMapTy::const_iterator
1238 it = offsets.find(overridden->getParent());
1239 if (it == offsets.end()) continue;
1240
1241 // Otherwise, check if the overridden method's class needs a vtordisp.
1242 if (it->second.hasVtorDisp()) return true;
1243
1244 } while (++I != E);
1245 return false;
1246}
1247
1248/// In the Microsoft ABI, decide which of the virtual bases require a
1249/// vtordisp field.
1250void RecordLayoutBuilder::computeVtordisps(const CXXRecordDecl *RD,
1251 ClassSetTy &vtordispVBases) {
1252 // Bail out if we have no virtual bases.
1253 assert(RD->getNumVBases());
1254
1255 // Build up the set of virtual bases that we haven't decided yet.
1256 ClassSetTy undecidedVBases;
1257 for (CXXRecordDecl::base_class_const_iterator
1258 I = RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
1259 const CXXRecordDecl *vbase = I->getType()->getAsCXXRecordDecl();
1260 undecidedVBases.insert(vbase);
1261 }
1262 assert(!undecidedVBases.empty());
1263
1264 // A virtual base requires a vtordisp field in a derived class if it
1265 // requires a vtordisp field in a base class. Walk all the direct
1266 // bases and collect this information.
1267 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1268 E = RD->bases_end(); I != E; ++I) {
1269 const CXXRecordDecl *base = I->getType()->getAsCXXRecordDecl();
1270 const ASTRecordLayout &baseLayout = Context.getASTRecordLayout(base);
1271
1272 // Iterate over the set of virtual bases provided by this class.
1273 for (ASTRecordLayout::VBaseOffsetsMapTy::const_iterator
1274 VI = baseLayout.getVBaseOffsetsMap().begin(),
1275 VE = baseLayout.getVBaseOffsetsMap().end(); VI != VE; ++VI) {
1276 // If it doesn't need a vtordisp in this base, ignore it.
1277 if (!VI->second.hasVtorDisp()) continue;
1278
1279 // If we've already seen it and decided it needs a vtordisp, ignore it.
1280 if (!undecidedVBases.erase(VI->first))
1281 continue;
1282
1283 // Add it.
1284 vtordispVBases.insert(VI->first);
1285
1286 // Quit as soon as we've decided everything.
1287 if (undecidedVBases.empty())
1288 return;
1289 }
1290 }
1291
1292 // Okay, we have virtual bases that we haven't yet decided about. A
1293 // virtual base requires a vtordisp if any the non-destructor
1294 // virtual methods declared in this class directly override a method
1295 // provided by that virtual base. (If so, we need to emit a thunk
1296 // for that method, to be used in the construction vftable, which
1297 // applies an additional 'vtordisp' this-adjustment.)
1298
1299 // Collect the set of bases directly overridden by any method in this class.
1300 // It's possible that some of these classes won't be virtual bases, or won't be
1301 // provided by virtual bases, or won't be virtual bases in the overridden
1302 // instance but are virtual bases elsewhere. Only the last matters for what
1303 // we're doing, and we can ignore those: if we don't directly override
1304 // a method provided by a virtual copy of a base class, but we do directly
1305 // override a method provided by a non-virtual copy of that base class,
1306 // then we must indirectly override the method provided by the virtual base,
1307 // and so we should already have collected it in the loop above.
1308 ClassSetTy overriddenBases;
1309 for (CXXRecordDecl::method_iterator
1310 M = RD->method_begin(), E = RD->method_end(); M != E; ++M) {
1311 // Ignore non-virtual methods and destructors.
1312 if (isa<CXXDestructorDecl>(*M) || !M->isVirtual())
1313 continue;
1314
1315 for (CXXMethodDecl::method_iterator I = M->begin_overridden_methods(),
1316 E = M->end_overridden_methods(); I != E; ++I) {
1317 const CXXMethodDecl *overriddenMethod = (*I);
1318
1319 // Ignore methods that override methods from vbases that require
1320 // require vtordisps.
1321 if (overridesMethodRequiringVtorDisp(Context, overriddenMethod))
1322 continue;
1323
1324 // As an optimization, check immediately whether we're overriding
1325 // something from the undecided set.
1326 const CXXRecordDecl *overriddenBase = overriddenMethod->getParent();
1327 if (undecidedVBases.erase(overriddenBase)) {
1328 vtordispVBases.insert(overriddenBase);
1329 if (undecidedVBases.empty()) return;
1330
1331 // We can't 'continue;' here because one of our undecided
1332 // vbases might non-virtually inherit from this base.
1333 // Consider:
1334 // struct A { virtual void foo(); };
1335 // struct B : A {};
1336 // struct C : virtual A, virtual B { virtual void foo(); };
1337 // We need a vtordisp for B here.
1338 }
1339
1340 // Otherwise, just collect it.
1341 overriddenBases.insert(overriddenBase);
1342 }
1343 }
1344
1345 // Walk the undecided v-bases and check whether they (non-virtually)
1346 // provide any of the overridden bases. We don't need to consider
1347 // virtual links because the vtordisp inheres to the layout
1348 // subobject containing the base.
1349 for (ClassSetTy::const_iterator
1350 I = undecidedVBases.begin(), E = undecidedVBases.end(); I != E; ++I) {
1351 if (hasNonVirtualBaseInSet(*I, overriddenBases))
1352 vtordispVBases.insert(*I);
1353 }
1354}
1355
John McCall9da23522011-11-08 04:01:03 +00001356/// hasNewVirtualFunction - Does the given polymorphic class declare a
1357/// virtual function that does not override a method from any of its
1358/// base classes?
Eli Friedman2fe36362011-09-27 19:12:27 +00001359bool
John McCall441c6232012-05-01 08:55:32 +00001360RecordLayoutBuilder::hasNewVirtualFunction(const CXXRecordDecl *RD,
1361 bool IgnoreDestructor) const {
John McCall9da23522011-11-08 04:01:03 +00001362 if (!RD->getNumBases())
1363 return true;
1364
Eli Friedman2fe36362011-09-27 19:12:27 +00001365 for (CXXRecordDecl::method_iterator method = RD->method_begin();
1366 method != RD->method_end();
1367 ++method) {
John McCall441c6232012-05-01 08:55:32 +00001368 if (method->isVirtual() && !method->size_overridden_methods() &&
1369 !(IgnoreDestructor && method->getKind() == Decl::CXXDestructor)) {
Eli Friedman2fe36362011-09-27 19:12:27 +00001370 return true;
1371 }
1372 }
1373 return false;
1374}
1375
John McCall9da23522011-11-08 04:01:03 +00001376/// isPossiblePrimaryBase - Is the given base class an acceptable
1377/// primary base class?
Eli Friedman97c0aef2011-10-18 00:55:28 +00001378bool
John McCall441c6232012-05-01 08:55:32 +00001379RecordLayoutBuilder::isPossiblePrimaryBase(const CXXRecordDecl *base) const {
John McCall9da23522011-11-08 04:01:03 +00001380 // In the Itanium ABI, a class can be a primary base class if it has
1381 // a vtable for any reason.
1382 if (!isMicrosoftCXXABI())
John McCall441c6232012-05-01 08:55:32 +00001383 return base->isDynamicClass();
John McCall9da23522011-11-08 04:01:03 +00001384
1385 // In the MS ABI, a class can only be a primary base class if it
1386 // provides a vf-table at a static offset. That means it has to be
1387 // non-virtual base. The existence of a separate vb-table means
1388 // that it's possible to get virtual functions only from a virtual
1389 // base, which we have to guard against.
1390
1391 // First off, it has to have virtual functions.
John McCall441c6232012-05-01 08:55:32 +00001392 if (!base->isPolymorphic()) return false;
John McCall9da23522011-11-08 04:01:03 +00001393
John McCall441c6232012-05-01 08:55:32 +00001394 // If it has no virtual bases, then the vfptr must be at a static offset.
1395 if (!base->getNumVBases()) return true;
1396
1397 // Otherwise, the necessary information is cached in the layout.
1398 const ASTRecordLayout &layout = Context.getASTRecordLayout(base);
John McCall9da23522011-11-08 04:01:03 +00001399
John McCall441c6232012-05-01 08:55:32 +00001400 // If the base has its own vfptr, it can be a primary base.
1401 if (layout.hasOwnVFPtr()) return true;
1402
1403 // If the base has a primary base class, then it can be a primary base.
1404 if (layout.getPrimaryBase()) return true;
1405
1406 // Otherwise it can't.
1407 return false;
Eli Friedman2fe36362011-09-27 19:12:27 +00001408}
1409
Anders Carlsson97913572010-04-15 16:12:58 +00001410void
Anders Carlsson7d0918a2010-05-26 05:58:59 +00001411RecordLayoutBuilder::LayoutVirtualBases(const CXXRecordDecl *RD,
Anders Carlsson97913572010-04-15 16:12:58 +00001412 const CXXRecordDecl *MostDerivedClass) {
Anders Carlsson88f42962010-03-11 04:33:54 +00001413 const CXXRecordDecl *PrimaryBase;
Anders Carlssonbdda6c12010-04-10 18:42:27 +00001414 bool PrimaryBaseIsVirtual;
Anders Carlsson37147ea2010-03-11 05:42:17 +00001415
Anders Carlssonbdda6c12010-04-10 18:42:27 +00001416 if (MostDerivedClass == RD) {
Anders Carlsson28fdd0a2010-05-26 05:20:58 +00001417 PrimaryBase = this->PrimaryBase;
1418 PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual;
Anders Carlssonbdda6c12010-04-10 18:42:27 +00001419 } else {
Anders Carlsson0f0e9b02010-04-16 15:07:51 +00001420 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlsson88f42962010-03-11 04:33:54 +00001421 PrimaryBase = Layout.getPrimaryBase();
Anders Carlssonc9e814b2010-11-24 23:12:57 +00001422 PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
Anders Carlssonbdda6c12010-04-10 18:42:27 +00001423 }
1424
Anders Carlsson622e2472010-03-11 04:24:02 +00001425 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1426 E = RD->bases_end(); I != E; ++I) {
1427 assert(!I->getType()->isDependentType() &&
Sebastian Redl9994a342009-10-25 17:03:50 +00001428 "Cannot layout class with dependent bases.");
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001429
Anders Carlsson276b4912010-05-29 17:48:36 +00001430 const CXXRecordDecl *BaseDecl =
John McCall9da23522011-11-08 04:01:03 +00001431 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
Anders Carlsson622e2472010-03-11 04:24:02 +00001432
1433 if (I->isVirtual()) {
Anders Carlsson276b4912010-05-29 17:48:36 +00001434 if (PrimaryBase != BaseDecl || !PrimaryBaseIsVirtual) {
1435 bool IndirectPrimaryBase = IndirectPrimaryBases.count(BaseDecl);
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001436
Anders Carlssonbdda6c12010-04-10 18:42:27 +00001437 // Only lay out the virtual base if it's not an indirect primary base.
1438 if (!IndirectPrimaryBase) {
1439 // Only visit virtual bases once.
Anders Carlsson276b4912010-05-29 17:48:36 +00001440 if (!VisitedVirtualBases.insert(BaseDecl))
Anders Carlssonbdda6c12010-04-10 18:42:27 +00001441 continue;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001442
Anders Carlsson276b4912010-05-29 17:48:36 +00001443 const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1444 assert(BaseInfo && "Did not find virtual base info!");
1445 LayoutVirtualBase(BaseInfo);
Anders Carlsson147b5dd2010-03-11 04:10:39 +00001446 }
Mike Stump968db332009-11-05 04:02:15 +00001447 }
Mike Stump4ef98092009-08-13 22:53:07 +00001448 }
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001449
Anders Carlsson276b4912010-05-29 17:48:36 +00001450 if (!BaseDecl->getNumVBases()) {
Anders Carlsson622e2472010-03-11 04:24:02 +00001451 // This base isn't interesting since it doesn't have any virtual bases.
1452 continue;
Mike Stumpfe3010d2009-08-16 19:04:13 +00001453 }
Anders Carlsson622e2472010-03-11 04:24:02 +00001454
Anders Carlsson276b4912010-05-29 17:48:36 +00001455 LayoutVirtualBases(BaseDecl, MostDerivedClass);
Mike Stumpeb19fa92009-08-06 13:41:24 +00001456 }
1457}
1458
John McCall9da23522011-11-08 04:01:03 +00001459void RecordLayoutBuilder::MSLayoutVirtualBases(const CXXRecordDecl *RD) {
John McCall9da23522011-11-08 04:01:03 +00001460 if (!RD->getNumVBases())
1461 return;
1462
John McCall441c6232012-05-01 08:55:32 +00001463 ClassSetTy VtordispVBases;
1464 computeVtordisps(RD, VtordispVBases);
1465
John McCall9da23522011-11-08 04:01:03 +00001466 // This is substantially simplified because there are no virtual
1467 // primary bases.
1468 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
1469 E = RD->vbases_end(); I != E; ++I) {
1470 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
1471 const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1472 assert(BaseInfo && "Did not find virtual base info!");
John McCall441c6232012-05-01 08:55:32 +00001473
1474 // If this base requires a vtordisp, add enough space for an int field.
1475 // This is apparently always 32-bits, even on x64.
1476 bool vtordispNeeded = false;
1477 if (VtordispVBases.count(BaseDecl)) {
1478 CharUnits IntSize =
1479 CharUnits::fromQuantity(Context.getTargetInfo().getIntWidth() / 8);
1480
1481 setSize(getSize() + IntSize);
1482 setDataSize(getSize());
1483 vtordispNeeded = true;
1484 }
1485
1486 LayoutVirtualBase(BaseInfo, vtordispNeeded);
John McCall9da23522011-11-08 04:01:03 +00001487 }
1488}
1489
John McCall441c6232012-05-01 08:55:32 +00001490void RecordLayoutBuilder::LayoutVirtualBase(const BaseSubobjectInfo *Base,
1491 bool IsVtordispNeed) {
Anders Carlsson3cd09cc2010-05-29 19:44:50 +00001492 assert(!Base->Derived && "Trying to lay out a primary virtual base!");
1493
Anders Carlssone3bdbee2010-03-10 22:26:24 +00001494 // Layout the base.
Anders Carlssona2311512010-10-31 22:20:42 +00001495 CharUnits Offset = LayoutBase(Base);
Anders Carlssone3bdbee2010-03-10 22:26:24 +00001496
1497 // Add its base class offset.
Anders Carlsson276b4912010-05-29 17:48:36 +00001498 assert(!VBases.count(Base->Class) && "vbase offset already exists!");
John McCall441c6232012-05-01 08:55:32 +00001499 VBases.insert(std::make_pair(Base->Class,
1500 ASTRecordLayout::VBaseInfo(Offset, IsVtordispNeed)));
1501
1502 if (!isMicrosoftCXXABI())
1503 AddPrimaryVirtualBaseOffsets(Base, Offset);
Anders Carlssone239b9d2010-03-10 22:21:28 +00001504}
1505
Anders Carlssona2311512010-10-31 22:20:42 +00001506CharUnits RecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) {
Anders Carlssonb1d880b2010-05-29 20:47:33 +00001507 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class);
Anders Carlssone239b9d2010-03-10 22:21:28 +00001508
Douglas Gregor453dbcb2012-01-26 07:55:45 +00001509
1510 CharUnits Offset;
1511
1512 // Query the external layout to see if it provides an offset.
1513 bool HasExternalLayout = false;
1514 if (ExternalLayout) {
1515 llvm::DenseMap<const CXXRecordDecl *, CharUnits>::iterator Known;
1516 if (Base->IsVirtual) {
1517 Known = ExternalVirtualBaseOffsets.find(Base->Class);
1518 if (Known != ExternalVirtualBaseOffsets.end()) {
1519 Offset = Known->second;
1520 HasExternalLayout = true;
1521 }
1522 } else {
1523 Known = ExternalBaseOffsets.find(Base->Class);
1524 if (Known != ExternalBaseOffsets.end()) {
1525 Offset = Known->second;
1526 HasExternalLayout = true;
1527 }
1528 }
1529 }
1530
Anders Carlssone239b9d2010-03-10 22:21:28 +00001531 // If we have an empty base class, try to place it at offset 0.
Anders Carlssonb1d880b2010-05-29 20:47:33 +00001532 if (Base->Class->isEmpty() &&
Douglas Gregor453dbcb2012-01-26 07:55:45 +00001533 (!HasExternalLayout || Offset == CharUnits::Zero()) &&
Anders Carlssona3d43802010-10-31 22:13:23 +00001534 EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) {
Ken Dyckf079b732011-02-28 02:01:38 +00001535 setSize(std::max(getSize(), Layout.getSize()));
Anders Carlssone239b9d2010-03-10 22:21:28 +00001536
Anders Carlssona2311512010-10-31 22:20:42 +00001537 return CharUnits::Zero();
Anders Carlssone239b9d2010-03-10 22:21:28 +00001538 }
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001539
Ken Dyck3263e092011-02-19 18:58:07 +00001540 CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlign();
1541 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
Argyrios Kyrtzidis43ddd9f2010-12-09 00:35:20 +00001542
1543 // The maximum field alignment overrides base align.
Ken Dyck834945c2011-02-17 01:49:42 +00001544 if (!MaxFieldAlignment.isZero()) {
Ken Dyck3263e092011-02-19 18:58:07 +00001545 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1546 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
Argyrios Kyrtzidis43ddd9f2010-12-09 00:35:20 +00001547 }
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001548
Douglas Gregor453dbcb2012-01-26 07:55:45 +00001549 if (!HasExternalLayout) {
1550 // Round up the current record size to the base's alignment boundary.
1551 Offset = getDataSize().RoundUpToAlignment(BaseAlign);
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001552
Douglas Gregor453dbcb2012-01-26 07:55:45 +00001553 // Try to place the base.
1554 while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset))
1555 Offset += BaseAlign;
1556 } else {
1557 bool Allowed = EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset);
1558 (void)Allowed;
1559 assert(Allowed && "Base subobject externally placed at overlapping offset");
1560 }
1561
Anders Carlssonb1d880b2010-05-29 20:47:33 +00001562 if (!Base->Class->isEmpty()) {
Anders Carlssone239b9d2010-03-10 22:21:28 +00001563 // Update the data size.
Ken Dyckf079b732011-02-28 02:01:38 +00001564 setDataSize(Offset + Layout.getNonVirtualSize());
Anders Carlssone239b9d2010-03-10 22:21:28 +00001565
Ken Dyckf079b732011-02-28 02:01:38 +00001566 setSize(std::max(getSize(), getDataSize()));
Anders Carlssone239b9d2010-03-10 22:21:28 +00001567 } else
Ken Dyckf079b732011-02-28 02:01:38 +00001568 setSize(std::max(getSize(), Offset + Layout.getSize()));
Anders Carlssone239b9d2010-03-10 22:21:28 +00001569
1570 // Remember max struct/class alignment.
Argyrios Kyrtzidis43ddd9f2010-12-09 00:35:20 +00001571 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
Anders Carlssone239b9d2010-03-10 22:21:28 +00001572
Ken Dyckf079b732011-02-28 02:01:38 +00001573 return Offset;
Anders Carlssone239b9d2010-03-10 22:21:28 +00001574}
1575
Daniel Dunbarc6082fe2010-05-27 05:45:51 +00001576void RecordLayoutBuilder::InitializeLayout(const Decl *D) {
1577 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
1578 IsUnion = RD->isUnion();
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001579
Anders Carlssona5dd7222009-08-08 19:38:24 +00001580 Packed = D->hasAttr<PackedAttr>();
Fariborz Jahanian62055b02011-04-26 23:52:16 +00001581
1582 IsMsStruct = D->hasAttr<MsStructAttr>();
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001583
Daniel Dunbar88934e82011-10-05 21:04:55 +00001584 // Honor the default struct packing maximum alignment flag.
David Blaikie4e4d0842012-03-11 07:00:24 +00001585 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) {
Daniel Dunbar88934e82011-10-05 21:04:55 +00001586 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
1587 }
1588
Daniel Dunbarc6082fe2010-05-27 05:45:51 +00001589 // mac68k alignment supersedes maximum field alignment and attribute aligned,
1590 // and forces all structures to have 2-byte alignment. The IBM docs on it
1591 // allude to additional (more complicated) semantics, especially with regard
1592 // to bit-fields, but gcc appears not to follow that.
1593 if (D->hasAttr<AlignMac68kAttr>()) {
1594 IsMac68kAlign = true;
Ken Dyck834945c2011-02-17 01:49:42 +00001595 MaxFieldAlignment = CharUnits::fromQuantity(2);
Ken Dyckea7f6c22011-02-16 02:05:21 +00001596 Alignment = CharUnits::fromQuantity(2);
Daniel Dunbarc6082fe2010-05-27 05:45:51 +00001597 } else {
1598 if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>())
Ken Dyck834945c2011-02-17 01:49:42 +00001599 MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment());
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001600
Sean Huntcf807c42010-08-18 23:23:40 +00001601 if (unsigned MaxAlign = D->getMaxAlignment())
Ken Dyck3263e092011-02-19 18:58:07 +00001602 UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign));
Daniel Dunbarc6082fe2010-05-27 05:45:51 +00001603 }
Douglas Gregor453dbcb2012-01-26 07:55:45 +00001604
1605 // If there is an external AST source, ask it for the various offsets.
1606 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
1607 if (ExternalASTSource *External = Context.getExternalSource()) {
1608 ExternalLayout = External->layoutRecordType(RD,
1609 ExternalSize,
1610 ExternalAlign,
1611 ExternalFieldOffsets,
1612 ExternalBaseOffsets,
1613 ExternalVirtualBaseOffsets);
1614
1615 // Update based on external alignment.
1616 if (ExternalLayout) {
Douglas Gregor394f7b62012-01-28 00:53:29 +00001617 if (ExternalAlign > 0) {
1618 Alignment = Context.toCharUnitsFromBits(ExternalAlign);
1619 UnpackedAlignment = Alignment;
1620 } else {
1621 // The external source didn't have alignment information; infer it.
1622 InferAlignment = true;
1623 }
Douglas Gregor453dbcb2012-01-26 07:55:45 +00001624 }
1625 }
Anders Carlssonc6cab682010-05-26 15:10:00 +00001626}
Anders Carlsson74cbe222009-07-19 00:18:47 +00001627
Anders Carlssonc6cab682010-05-26 15:10:00 +00001628void RecordLayoutBuilder::Layout(const RecordDecl *D) {
1629 InitializeLayout(D);
Anders Carlssona2df41c2009-07-18 21:48:39 +00001630 LayoutFields(D);
Mike Stump1eb44332009-09-09 15:08:12 +00001631
Anders Carlssonbda4c102009-07-18 20:20:21 +00001632 // Finally, round the size of the total struct up to the alignment of the
1633 // struct itself.
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001634 FinishLayout(D);
Anders Carlssonc6cab682010-05-26 15:10:00 +00001635}
1636
1637void RecordLayoutBuilder::Layout(const CXXRecordDecl *RD) {
1638 InitializeLayout(RD);
1639
Anders Carlssonc6cab682010-05-26 15:10:00 +00001640 // Lay out the vtable and the non-virtual bases.
1641 LayoutNonVirtualBases(RD);
1642
1643 LayoutFields(RD);
1644
Ken Dyck90ce2db2011-03-10 01:53:59 +00001645 NonVirtualSize = Context.toCharUnitsFromBits(
1646 llvm::RoundUpToAlignment(getSizeInBits(),
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001647 Context.getTargetInfo().getCharAlign()));
Ken Dyckea7f6c22011-02-16 02:05:21 +00001648 NonVirtualAlignment = Alignment;
Anders Carlssonc6cab682010-05-26 15:10:00 +00001649
John McCall441c6232012-05-01 08:55:32 +00001650 if (isMicrosoftCXXABI()) {
1651 if (NonVirtualSize != NonVirtualSize.RoundUpToAlignment(Alignment)) {
John McCall9da23522011-11-08 04:01:03 +00001652 CharUnits AlignMember =
1653 NonVirtualSize.RoundUpToAlignment(Alignment) - NonVirtualSize;
Anders Carlssonc6cab682010-05-26 15:10:00 +00001654
John McCall9da23522011-11-08 04:01:03 +00001655 setSize(getSize() + AlignMember);
1656 setDataSize(getSize());
Anders Carlssonc6cab682010-05-26 15:10:00 +00001657
John McCall9da23522011-11-08 04:01:03 +00001658 NonVirtualSize = Context.toCharUnitsFromBits(
1659 llvm::RoundUpToAlignment(getSizeInBits(),
1660 Context.getTargetInfo().getCharAlign()));
John McCall441c6232012-05-01 08:55:32 +00001661 }
John McCall9da23522011-11-08 04:01:03 +00001662
1663 MSLayoutVirtualBases(RD);
John McCall9da23522011-11-08 04:01:03 +00001664 } else {
1665 // Lay out the virtual bases and add the primary virtual base offsets.
1666 LayoutVirtualBases(RD, RD);
1667 }
1668
1669 // Finally, round the size of the total struct up to the alignment
Eli Friedman901dd662011-12-01 00:37:01 +00001670 // of the struct itself.
1671 FinishLayout(RD);
Anders Carlssonc6cab682010-05-26 15:10:00 +00001672
Anders Carlssona1e87162010-04-10 21:24:48 +00001673#ifndef NDEBUG
Anders Carlssonc6cab682010-05-26 15:10:00 +00001674 // Check that we have base offsets for all bases.
1675 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1676 E = RD->bases_end(); I != E; ++I) {
1677 if (I->isVirtual())
1678 continue;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001679
Anders Carlssonc6cab682010-05-26 15:10:00 +00001680 const CXXRecordDecl *BaseDecl =
1681 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1682
1683 assert(Bases.count(BaseDecl) && "Did not find base offset!");
1684 }
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001685
Anders Carlssonc6cab682010-05-26 15:10:00 +00001686 // And all virtual bases.
1687 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
1688 E = RD->vbases_end(); I != E; ++I) {
1689 const CXXRecordDecl *BaseDecl =
1690 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001691
Anders Carlssonc6cab682010-05-26 15:10:00 +00001692 assert(VBases.count(BaseDecl) && "Did not find base offset!");
Anders Carlssona1e87162010-04-10 21:24:48 +00001693 }
1694#endif
Anders Carlssonbda4c102009-07-18 20:20:21 +00001695}
1696
Anders Carlsson7d0918a2010-05-26 05:58:59 +00001697void RecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) {
Anders Carlsson93fab9d2009-07-18 20:50:59 +00001698 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
Anders Carlsson0f0e9b02010-04-16 15:07:51 +00001699 const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD);
Anders Carlsson93fab9d2009-07-18 20:50:59 +00001700
Ken Dyck3263e092011-02-19 18:58:07 +00001701 UpdateAlignment(SL.getAlignment());
Mike Stump1eb44332009-09-09 15:08:12 +00001702
Anders Carlsson93fab9d2009-07-18 20:50:59 +00001703 // We start laying out ivars not at the end of the superclass
1704 // structure, but at the next byte following the last field.
Ken Dycka0c21c42011-02-24 01:13:28 +00001705 setSize(SL.getDataSize());
Ken Dyckf079b732011-02-28 02:01:38 +00001706 setDataSize(getSize());
Anders Carlsson93fab9d2009-07-18 20:50:59 +00001707 }
Mike Stump1eb44332009-09-09 15:08:12 +00001708
Daniel Dunbarc6082fe2010-05-27 05:45:51 +00001709 InitializeLayout(D);
Anders Carlsson93fab9d2009-07-18 20:50:59 +00001710 // Layout each ivar sequentially.
Jordy Rosedb8264e2011-07-22 02:08:32 +00001711 for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD;
1712 IVD = IVD->getNextIvar())
Fariborz Jahanianbf9eb882011-06-28 18:05:25 +00001713 LayoutField(IVD);
Mike Stump1eb44332009-09-09 15:08:12 +00001714
Anders Carlsson93fab9d2009-07-18 20:50:59 +00001715 // Finally, round the size of the total struct up to the alignment of the
1716 // struct itself.
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001717 FinishLayout(D);
Anders Carlsson93fab9d2009-07-18 20:50:59 +00001718}
1719
Anders Carlsson7d0918a2010-05-26 05:58:59 +00001720void RecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
Anders Carlssona2df41c2009-07-18 21:48:39 +00001721 // Layout each field, for now, just sequentially, respecting alignment. In
1722 // the future, this will need to be tweakable by targets.
Fariborz Jahanian62055b02011-04-26 23:52:16 +00001723 const FieldDecl *LastFD = 0;
Fariborz Jahanian855a8e72011-05-03 20:21:04 +00001724 ZeroLengthBitfield = 0;
Fariborz Jahanian6ec50ad2011-05-11 16:58:31 +00001725 unsigned RemainingInAlignment = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001726 for (RecordDecl::field_iterator Field = D->field_begin(),
Fariborz Jahanian62055b02011-04-26 23:52:16 +00001727 FieldEnd = D->field_end(); Field != FieldEnd; ++Field) {
1728 if (IsMsStruct) {
David Blaikie581deb32012-06-06 20:45:41 +00001729 FieldDecl *FD = *Field;
Fariborz Jahanian855a8e72011-05-03 20:21:04 +00001730 if (Context.ZeroBitfieldFollowsBitfield(FD, LastFD))
1731 ZeroLengthBitfield = FD;
Fariborz Jahanian62055b02011-04-26 23:52:16 +00001732 // Zero-length bitfields following non-bitfield members are
1733 // ignored:
Fariborz Jahanian855a8e72011-05-03 20:21:04 +00001734 else if (Context.ZeroBitfieldFollowsNonBitfield(FD, LastFD))
Fariborz Jahanian62055b02011-04-26 23:52:16 +00001735 continue;
Fariborz Jahanian31e7f222011-05-06 22:42:22 +00001736 // FIXME. streamline these conditions into a simple one.
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001737 else if (Context.BitfieldFollowsBitfield(FD, LastFD) ||
Chad Rosierdd7fddb2011-08-04 23:34:15 +00001738 Context.BitfieldFollowsNonBitfield(FD, LastFD) ||
1739 Context.NonBitfieldFollowsBitfield(FD, LastFD)) {
Fariborz Jahanian31e7f222011-05-06 22:42:22 +00001740 // 1) Adjacent bit fields are packed into the same 1-, 2-, or
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001741 // 4-byte allocation unit if the integral types are the same
1742 // size and if the next bit field fits into the current
1743 // allocation unit without crossing the boundary imposed by the
1744 // common alignment requirements of the bit fields.
Fariborz Jahanian31e7f222011-05-06 22:42:22 +00001745 // 2) Establish a new alignment for a bitfield following
Fariborz Jahanian52bbe7a2011-05-06 21:56:12 +00001746 // a non-bitfield if size of their types differ.
Fariborz Jahanian31e7f222011-05-06 22:42:22 +00001747 // 3) Establish a new alignment for a non-bitfield following
1748 // a bitfield if size of their types differ.
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001749 std::pair<uint64_t, unsigned> FieldInfo =
1750 Context.getTypeInfo(FD->getType());
1751 uint64_t TypeSize = FieldInfo.first;
1752 unsigned FieldAlign = FieldInfo.second;
Fariborz Jahanian30364d02011-05-09 22:03:17 +00001753 // This check is needed for 'long long' in -m32 mode.
Fariborz Jahanian364a59e2011-12-12 21:16:36 +00001754 if (TypeSize > FieldAlign &&
1755 (Context.hasSameType(FD->getType(),
1756 Context.UnsignedLongLongTy)
1757 ||Context.hasSameType(FD->getType(),
1758 Context.LongLongTy)))
Fariborz Jahanian30364d02011-05-09 22:03:17 +00001759 FieldAlign = TypeSize;
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001760 FieldInfo = Context.getTypeInfo(LastFD->getType());
1761 uint64_t TypeSizeLastFD = FieldInfo.first;
1762 unsigned FieldAlignLastFD = FieldInfo.second;
Fariborz Jahanian30364d02011-05-09 22:03:17 +00001763 // This check is needed for 'long long' in -m32 mode.
Fariborz Jahanian364a59e2011-12-12 21:16:36 +00001764 if (TypeSizeLastFD > FieldAlignLastFD &&
1765 (Context.hasSameType(LastFD->getType(),
1766 Context.UnsignedLongLongTy)
1767 || Context.hasSameType(LastFD->getType(),
1768 Context.LongLongTy)))
Fariborz Jahanian30364d02011-05-09 22:03:17 +00001769 FieldAlignLastFD = TypeSizeLastFD;
Fariborz Jahanian6ec50ad2011-05-11 16:58:31 +00001770
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001771 if (TypeSizeLastFD != TypeSize) {
Fariborz Jahanian6ec50ad2011-05-11 16:58:31 +00001772 if (RemainingInAlignment &&
1773 LastFD && LastFD->isBitField() &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001774 LastFD->getBitWidthValue(Context)) {
Fariborz Jahanian6ec50ad2011-05-11 16:58:31 +00001775 // If previous field was a bitfield with some remaining unfilled
1776 // bits, pad the field so current field starts on its type boundary.
1777 uint64_t FieldOffset =
1778 getDataSizeInBits() - UnfilledBitsInLastByte;
1779 uint64_t NewSizeInBits = RemainingInAlignment + FieldOffset;
1780 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001781 Context.getTargetInfo().getCharAlign()));
Fariborz Jahanian6ec50ad2011-05-11 16:58:31 +00001782 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1783 RemainingInAlignment = 0;
1784 }
1785
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001786 uint64_t UnpaddedFieldOffset =
1787 getDataSizeInBits() - UnfilledBitsInLastByte;
1788 FieldAlign = std::max(FieldAlign, FieldAlignLastFD);
Fariborz Jahanian6ec50ad2011-05-11 16:58:31 +00001789
Fariborz Jahanianed63e032011-05-10 19:00:50 +00001790 // The maximum field alignment overrides the aligned attribute.
1791 if (!MaxFieldAlignment.isZero()) {
1792 unsigned MaxFieldAlignmentInBits =
1793 Context.toBits(MaxFieldAlignment);
1794 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1795 }
Fariborz Jahanian6ec50ad2011-05-11 16:58:31 +00001796
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001797 uint64_t NewSizeInBits =
1798 llvm::RoundUpToAlignment(UnpaddedFieldOffset, FieldAlign);
1799 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001800 Context.getTargetInfo().getCharAlign()));
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001801 UnfilledBitsInLastByte = getDataSizeInBits() - NewSizeInBits;
1802 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1803 }
Fariborz Jahanian6ec50ad2011-05-11 16:58:31 +00001804 if (FD->isBitField()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001805 uint64_t FieldSize = FD->getBitWidthValue(Context);
Fariborz Jahanian6ec50ad2011-05-11 16:58:31 +00001806 assert (FieldSize > 0 && "LayoutFields - ms_struct layout");
1807 if (RemainingInAlignment < FieldSize)
1808 RemainingInAlignment = TypeSize - FieldSize;
1809 else
1810 RemainingInAlignment -= FieldSize;
1811 }
1812 }
1813 else if (FD->isBitField()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001814 uint64_t FieldSize = FD->getBitWidthValue(Context);
Fariborz Jahanian6ec50ad2011-05-11 16:58:31 +00001815 std::pair<uint64_t, unsigned> FieldInfo =
1816 Context.getTypeInfo(FD->getType());
1817 uint64_t TypeSize = FieldInfo.first;
1818 RemainingInAlignment = TypeSize - FieldSize;
Fariborz Jahanian9b3acaa2011-05-04 18:51:37 +00001819 }
Fariborz Jahanian62055b02011-04-26 23:52:16 +00001820 LastFD = FD;
1821 }
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001822 else if (!Context.getTargetInfo().useBitFieldTypeAlignment() &&
1823 Context.getTargetInfo().useZeroLengthBitfieldAlignment()) {
David Blaikie581deb32012-06-06 20:45:41 +00001824 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
1825 ZeroLengthBitfield = *Field;
Chad Rosier61a62212011-08-04 01:21:14 +00001826 }
David Blaikie581deb32012-06-06 20:45:41 +00001827 LayoutField(*Field);
Fariborz Jahanian62055b02011-04-26 23:52:16 +00001828 }
Fariborz Jahanian6ec50ad2011-05-11 16:58:31 +00001829 if (IsMsStruct && RemainingInAlignment &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001830 LastFD && LastFD->isBitField() && LastFD->getBitWidthValue(Context)) {
Fariborz Jahanian6ec50ad2011-05-11 16:58:31 +00001831 // If we ended a bitfield before the full length of the type then
1832 // pad the struct out to the full length of the last type.
1833 uint64_t FieldOffset =
1834 getDataSizeInBits() - UnfilledBitsInLastByte;
1835 uint64_t NewSizeInBits = RemainingInAlignment + FieldOffset;
1836 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001837 Context.getTargetInfo().getCharAlign()));
Fariborz Jahanian6ec50ad2011-05-11 16:58:31 +00001838 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1839 }
Anders Carlssona2df41c2009-07-18 21:48:39 +00001840}
1841
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001842void RecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize,
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001843 uint64_t TypeSize,
1844 bool FieldPacked,
1845 const FieldDecl *D) {
David Blaikie4e4d0842012-03-11 07:00:24 +00001846 assert(Context.getLangOpts().CPlusPlus &&
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001847 "Can only have wide bit-fields in C++!");
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001848
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001849 // Itanium C++ ABI 2.4:
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001850 // If sizeof(T)*8 < n, let T' be the largest integral POD type with
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001851 // sizeof(T')*8 <= n.
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001852
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001853 QualType IntegralPODTypes[] = {
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001854 Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy,
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001855 Context.UnsignedLongTy, Context.UnsignedLongLongTy
1856 };
1857
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001858 QualType Type;
1859 for (unsigned I = 0, E = llvm::array_lengthof(IntegralPODTypes);
1860 I != E; ++I) {
1861 uint64_t Size = Context.getTypeSize(IntegralPODTypes[I]);
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001862
1863 if (Size > FieldSize)
1864 break;
1865
1866 Type = IntegralPODTypes[I];
1867 }
1868 assert(!Type.isNull() && "Did not find a type!");
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001869
Ken Dyck3b3e1a12011-03-01 01:36:00 +00001870 CharUnits TypeAlign = Context.getTypeAlignInChars(Type);
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001871
1872 // We're not going to use any of the unfilled bits in the last byte.
1873 UnfilledBitsInLastByte = 0;
1874
Anders Carlssonde9f1532010-04-17 20:21:41 +00001875 uint64_t FieldOffset;
Ken Dycka0c21c42011-02-24 01:13:28 +00001876 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastByte;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001877
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001878 if (IsUnion) {
Ken Dycka0c21c42011-02-24 01:13:28 +00001879 setDataSize(std::max(getDataSizeInBits(), FieldSize));
Anders Carlssonde9f1532010-04-17 20:21:41 +00001880 FieldOffset = 0;
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001881 } else {
Chad Rosierb8fca902011-08-05 22:38:04 +00001882 // The bitfield is allocated starting at the next offset aligned
1883 // appropriately for T', with length n bits.
Ken Dyck3b3e1a12011-03-01 01:36:00 +00001884 FieldOffset = llvm::RoundUpToAlignment(getDataSizeInBits(),
1885 Context.toBits(TypeAlign));
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001886
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001887 uint64_t NewSizeInBits = FieldOffset + FieldSize;
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001888
Ken Dyckd5e3ed02011-03-10 02:00:35 +00001889 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001890 Context.getTargetInfo().getCharAlign()));
Ken Dycka0c21c42011-02-24 01:13:28 +00001891 UnfilledBitsInLastByte = getDataSizeInBits() - NewSizeInBits;
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001892 }
1893
1894 // Place this field at the current location.
1895 FieldOffsets.push_back(FieldOffset);
1896
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001897 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset,
Ken Dyck3b3e1a12011-03-01 01:36:00 +00001898 Context.toBits(TypeAlign), FieldPacked, D);
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001899
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001900 // Update the size.
Ken Dycka0c21c42011-02-24 01:13:28 +00001901 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00001902
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001903 // Remember max struct/class alignment.
Ken Dyck3b3e1a12011-03-01 01:36:00 +00001904 UpdateAlignment(TypeAlign);
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001905}
1906
Anders Carlsson7d0918a2010-05-26 05:58:59 +00001907void RecordLayoutBuilder::LayoutBitField(const FieldDecl *D) {
Anders Carlsson42dbcc42009-11-22 17:37:31 +00001908 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
Ken Dycka0c21c42011-02-24 01:13:28 +00001909 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastByte;
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001910 uint64_t FieldOffset = IsUnion ? 0 : UnpaddedFieldOffset;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00001911 uint64_t FieldSize = D->getBitWidthValue(Context);
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001912
Anders Carlsson0f0e9b02010-04-16 15:07:51 +00001913 std::pair<uint64_t, unsigned> FieldInfo = Context.getTypeInfo(D->getType());
Anders Carlsson42dbcc42009-11-22 17:37:31 +00001914 uint64_t TypeSize = FieldInfo.first;
1915 unsigned FieldAlign = FieldInfo.second;
Fariborz Jahanian855a8e72011-05-03 20:21:04 +00001916
Fariborz Jahanian30364d02011-05-09 22:03:17 +00001917 // This check is needed for 'long long' in -m32 mode.
Fariborz Jahanian364a59e2011-12-12 21:16:36 +00001918 if (IsMsStruct && (TypeSize > FieldAlign) &&
1919 (Context.hasSameType(D->getType(),
1920 Context.UnsignedLongLongTy)
1921 || Context.hasSameType(D->getType(), Context.LongLongTy)))
Fariborz Jahanian30364d02011-05-09 22:03:17 +00001922 FieldAlign = TypeSize;
Chad Rosier61a62212011-08-04 01:21:14 +00001923
Fariborz Jahanian855a8e72011-05-03 20:21:04 +00001924 if (ZeroLengthBitfield) {
Chad Rosierb8fca902011-08-05 22:38:04 +00001925 std::pair<uint64_t, unsigned> FieldInfo;
1926 unsigned ZeroLengthBitfieldAlignment;
1927 if (IsMsStruct) {
1928 // If a zero-length bitfield is inserted after a bitfield,
1929 // and the alignment of the zero-length bitfield is
1930 // greater than the member that follows it, `bar', `bar'
1931 // will be aligned as the type of the zero-length bitfield.
1932 if (ZeroLengthBitfield != D) {
1933 FieldInfo = Context.getTypeInfo(ZeroLengthBitfield->getType());
1934 ZeroLengthBitfieldAlignment = FieldInfo.second;
1935 // Ignore alignment of subsequent zero-length bitfields.
1936 if ((ZeroLengthBitfieldAlignment > FieldAlign) || (FieldSize == 0))
1937 FieldAlign = ZeroLengthBitfieldAlignment;
1938 if (FieldSize)
1939 ZeroLengthBitfield = 0;
1940 }
1941 } else {
1942 // The alignment of a zero-length bitfield affects the alignment
1943 // of the next member. The alignment is the max of the zero
1944 // length bitfield's alignment and a target specific fixed value.
1945 unsigned ZeroLengthBitfieldBoundary =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001946 Context.getTargetInfo().getZeroLengthBitfieldBoundary();
Chad Rosierb8fca902011-08-05 22:38:04 +00001947 if (ZeroLengthBitfieldBoundary > FieldAlign)
1948 FieldAlign = ZeroLengthBitfieldBoundary;
Fariborz Jahanian855a8e72011-05-03 20:21:04 +00001949 }
1950 }
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001951
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001952 if (FieldSize > TypeSize) {
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001953 LayoutWideBitField(FieldSize, TypeSize, FieldPacked, D);
Anders Carlsson4cf6f5f2010-04-16 15:57:11 +00001954 return;
1955 }
1956
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001957 // The align if the field is not packed. This is to check if the attribute
1958 // was unnecessary (-Wpacked).
1959 unsigned UnpackedFieldAlign = FieldAlign;
1960 uint64_t UnpackedFieldOffset = FieldOffset;
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001961 if (!Context.getTargetInfo().useBitFieldTypeAlignment() && !ZeroLengthBitfield)
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001962 UnpackedFieldAlign = 1;
1963
Chad Rosierb8fca902011-08-05 22:38:04 +00001964 if (FieldPacked ||
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001965 (!Context.getTargetInfo().useBitFieldTypeAlignment() && !ZeroLengthBitfield))
Anders Carlsson42dbcc42009-11-22 17:37:31 +00001966 FieldAlign = 1;
Sean Huntcf807c42010-08-18 23:23:40 +00001967 FieldAlign = std::max(FieldAlign, D->getMaxAlignment());
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001968 UnpackedFieldAlign = std::max(UnpackedFieldAlign, D->getMaxAlignment());
Anders Carlsson42dbcc42009-11-22 17:37:31 +00001969
1970 // The maximum field alignment overrides the aligned attribute.
Eli Friedmanbff22ac2011-12-02 02:38:48 +00001971 if (!MaxFieldAlignment.isZero() && FieldSize != 0) {
Ken Dyck834945c2011-02-17 01:49:42 +00001972 unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment);
1973 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1974 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001975 }
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001976
Douglas Gregor394f7b62012-01-28 00:53:29 +00001977 // Check if we need to add padding to give the field the correct alignment.
1978 if (FieldSize == 0 ||
1979 (MaxFieldAlignment.isZero() &&
1980 (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize))
1981 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001982
Douglas Gregor394f7b62012-01-28 00:53:29 +00001983 if (FieldSize == 0 ||
1984 (MaxFieldAlignment.isZero() &&
1985 (UnpackedFieldOffset & (UnpackedFieldAlign-1)) + FieldSize > TypeSize))
1986 UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1987 UnpackedFieldAlign);
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001988
Chad Rosierb8fca902011-08-05 22:38:04 +00001989 // Padding members don't affect overall alignment, unless zero length bitfield
1990 // alignment is enabled.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00001991 if (!D->getIdentifier() && !Context.getTargetInfo().useZeroLengthBitfieldAlignment())
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00001992 FieldAlign = UnpackedFieldAlign = 1;
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00001993
Chad Rosierb8fca902011-08-05 22:38:04 +00001994 if (!IsMsStruct)
1995 ZeroLengthBitfield = 0;
1996
Douglas Gregor394f7b62012-01-28 00:53:29 +00001997 if (ExternalLayout)
1998 FieldOffset = updateExternalFieldOffset(D, FieldOffset);
1999
Anders Carlsson42dbcc42009-11-22 17:37:31 +00002000 // Place this field at the current location.
2001 FieldOffsets.push_back(FieldOffset);
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002002
Douglas Gregor453dbcb2012-01-26 07:55:45 +00002003 if (!ExternalLayout)
2004 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset,
2005 UnpackedFieldAlign, FieldPacked, D);
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002006
Anders Carlssone4fc0d92009-11-22 19:13:51 +00002007 // Update DataSize to include the last byte containing (part of) the bitfield.
2008 if (IsUnion) {
2009 // FIXME: I think FieldSize should be TypeSize here.
Ken Dycka0c21c42011-02-24 01:13:28 +00002010 setDataSize(std::max(getDataSizeInBits(), FieldSize));
Anders Carlssone4fc0d92009-11-22 19:13:51 +00002011 } else {
2012 uint64_t NewSizeInBits = FieldOffset + FieldSize;
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002013
Ken Dyckd5e3ed02011-03-10 02:00:35 +00002014 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002015 Context.getTargetInfo().getCharAlign()));
Ken Dycka0c21c42011-02-24 01:13:28 +00002016 UnfilledBitsInLastByte = getDataSizeInBits() - NewSizeInBits;
Anders Carlssone4fc0d92009-11-22 19:13:51 +00002017 }
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002018
Anders Carlssone4fc0d92009-11-22 19:13:51 +00002019 // Update the size.
Ken Dycka0c21c42011-02-24 01:13:28 +00002020 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002021
Anders Carlsson42dbcc42009-11-22 17:37:31 +00002022 // Remember max struct/class alignment.
Ken Dyck3263e092011-02-19 18:58:07 +00002023 UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign),
2024 Context.toCharUnitsFromBits(UnpackedFieldAlign));
Anders Carlsson42dbcc42009-11-22 17:37:31 +00002025}
2026
Douglas Gregor453dbcb2012-01-26 07:55:45 +00002027void RecordLayoutBuilder::LayoutField(const FieldDecl *D) {
Anders Carlsson42dbcc42009-11-22 17:37:31 +00002028 if (D->isBitField()) {
2029 LayoutBitField(D);
2030 return;
2031 }
2032
Ken Dycka0c21c42011-02-24 01:13:28 +00002033 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastByte;
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002034
Anders Carlssone4fc0d92009-11-22 19:13:51 +00002035 // Reset the unfilled bits.
2036 UnfilledBitsInLastByte = 0;
2037
Anders Carlsson42dbcc42009-11-22 17:37:31 +00002038 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
Ken Dyck9ed9a252011-02-20 02:06:09 +00002039 CharUnits FieldOffset =
Ken Dycka0c21c42011-02-24 01:13:28 +00002040 IsUnion ? CharUnits::Zero() : getDataSize();
Ken Dyck9ed9a252011-02-20 02:06:09 +00002041 CharUnits FieldSize;
2042 CharUnits FieldAlign;
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002043
Anders Carlsson42dbcc42009-11-22 17:37:31 +00002044 if (D->getType()->isIncompleteArrayType()) {
2045 // This is a flexible array member; we can't directly
2046 // query getTypeInfo about these, so we figure it out here.
2047 // Flexible array members don't have any size, but they
2048 // have to be aligned appropriately for their element type.
Ken Dyck9ed9a252011-02-20 02:06:09 +00002049 FieldSize = CharUnits::Zero();
Anders Carlsson0f0e9b02010-04-16 15:07:51 +00002050 const ArrayType* ATy = Context.getAsArrayType(D->getType());
Ken Dyck9ed9a252011-02-20 02:06:09 +00002051 FieldAlign = Context.getTypeAlignInChars(ATy->getElementType());
Anders Carlsson42dbcc42009-11-22 17:37:31 +00002052 } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) {
2053 unsigned AS = RT->getPointeeType().getAddressSpace();
Ken Dyck9ed9a252011-02-20 02:06:09 +00002054 FieldSize =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002055 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(AS));
Ken Dyck9ed9a252011-02-20 02:06:09 +00002056 FieldAlign =
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002057 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(AS));
Anders Carlssonbda4c102009-07-18 20:20:21 +00002058 } else {
Ken Dyck9ed9a252011-02-20 02:06:09 +00002059 std::pair<CharUnits, CharUnits> FieldInfo =
2060 Context.getTypeInfoInChars(D->getType());
Anders Carlsson42dbcc42009-11-22 17:37:31 +00002061 FieldSize = FieldInfo.first;
2062 FieldAlign = FieldInfo.second;
Chad Rosier61a62212011-08-04 01:21:14 +00002063
Fariborz Jahanian855a8e72011-05-03 20:21:04 +00002064 if (ZeroLengthBitfield) {
Chad Rosier61a62212011-08-04 01:21:14 +00002065 CharUnits ZeroLengthBitfieldBoundary =
2066 Context.toCharUnitsFromBits(
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002067 Context.getTargetInfo().getZeroLengthBitfieldBoundary());
Chad Rosier61a62212011-08-04 01:21:14 +00002068 if (ZeroLengthBitfieldBoundary == CharUnits::Zero()) {
2069 // If a zero-length bitfield is inserted after a bitfield,
2070 // and the alignment of the zero-length bitfield is
2071 // greater than the member that follows it, `bar', `bar'
2072 // will be aligned as the type of the zero-length bitfield.
2073 std::pair<CharUnits, CharUnits> FieldInfo =
2074 Context.getTypeInfoInChars(ZeroLengthBitfield->getType());
2075 CharUnits ZeroLengthBitfieldAlignment = FieldInfo.second;
2076 if (ZeroLengthBitfieldAlignment > FieldAlign)
2077 FieldAlign = ZeroLengthBitfieldAlignment;
Chad Rosier0e7bf402011-08-04 19:25:14 +00002078 } else if (ZeroLengthBitfieldBoundary > FieldAlign) {
Chad Rosier61a62212011-08-04 01:21:14 +00002079 // Align 'bar' based on a fixed alignment specified by the target.
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002080 assert(Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
Chad Rosier6e43f3f2011-08-04 17:52:43 +00002081 "ZeroLengthBitfieldBoundary should only be used in conjunction"
2082 " with useZeroLengthBitfieldAlignment.");
Chad Rosier61a62212011-08-04 01:21:14 +00002083 FieldAlign = ZeroLengthBitfieldBoundary;
2084 }
Fariborz Jahanian855a8e72011-05-03 20:21:04 +00002085 ZeroLengthBitfield = 0;
2086 }
Douglas Gregor6f755502011-02-01 15:15:22 +00002087
David Blaikie4e4d0842012-03-11 07:00:24 +00002088 if (Context.getLangOpts().MSBitfields || IsMsStruct) {
Douglas Gregor6f755502011-02-01 15:15:22 +00002089 // If MS bitfield layout is required, figure out what type is being
2090 // laid out and align the field to the width of that type.
2091
2092 // Resolve all typedefs down to their base type and round up the field
2093 // alignment if necessary.
2094 QualType T = Context.getBaseElementType(D->getType());
2095 if (const BuiltinType *BTy = T->getAs<BuiltinType>()) {
Ken Dyck9ed9a252011-02-20 02:06:09 +00002096 CharUnits TypeSize = Context.getTypeSizeInChars(BTy);
Douglas Gregor6f755502011-02-01 15:15:22 +00002097 if (TypeSize > FieldAlign)
2098 FieldAlign = TypeSize;
2099 }
2100 }
Anders Carlssonbda4c102009-07-18 20:20:21 +00002101 }
Mike Stump1eb44332009-09-09 15:08:12 +00002102
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002103 // The align if the field is not packed. This is to check if the attribute
2104 // was unnecessary (-Wpacked).
Ken Dyck9ed9a252011-02-20 02:06:09 +00002105 CharUnits UnpackedFieldAlign = FieldAlign;
2106 CharUnits UnpackedFieldOffset = FieldOffset;
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002107
Anders Carlsson42dbcc42009-11-22 17:37:31 +00002108 if (FieldPacked)
Ken Dyck9ed9a252011-02-20 02:06:09 +00002109 FieldAlign = CharUnits::One();
2110 CharUnits MaxAlignmentInChars =
2111 Context.toCharUnitsFromBits(D->getMaxAlignment());
2112 FieldAlign = std::max(FieldAlign, MaxAlignmentInChars);
2113 UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars);
Anders Carlsson42dbcc42009-11-22 17:37:31 +00002114
2115 // The maximum field alignment overrides the aligned attribute.
Ken Dyck834945c2011-02-17 01:49:42 +00002116 if (!MaxFieldAlignment.isZero()) {
Ken Dyck9ed9a252011-02-20 02:06:09 +00002117 FieldAlign = std::min(FieldAlign, MaxFieldAlignment);
2118 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment);
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002119 }
Anders Carlsson42dbcc42009-11-22 17:37:31 +00002120
Douglas Gregor394f7b62012-01-28 00:53:29 +00002121 // Round up the current record size to the field's alignment boundary.
2122 FieldOffset = FieldOffset.RoundUpToAlignment(FieldAlign);
2123 UnpackedFieldOffset =
2124 UnpackedFieldOffset.RoundUpToAlignment(UnpackedFieldAlign);
2125
2126 if (ExternalLayout) {
2127 FieldOffset = Context.toCharUnitsFromBits(
2128 updateExternalFieldOffset(D, Context.toBits(FieldOffset)));
2129
2130 if (!IsUnion && EmptySubobjects) {
2131 // Record the fact that we're placing a field at this offset.
2132 bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset);
2133 (void)Allowed;
2134 assert(Allowed && "Externally-placed field cannot be placed here");
2135 }
2136 } else {
Douglas Gregor453dbcb2012-01-26 07:55:45 +00002137 if (!IsUnion && EmptySubobjects) {
2138 // Check if we can place the field at this offset.
2139 while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) {
2140 // We couldn't place the field at the offset. Try again at a new offset.
2141 FieldOffset += FieldAlign;
2142 }
Anders Carlsson42dbcc42009-11-22 17:37:31 +00002143 }
Anders Carlsson42dbcc42009-11-22 17:37:31 +00002144 }
Douglas Gregor453dbcb2012-01-26 07:55:45 +00002145
Anders Carlssonbda4c102009-07-18 20:20:21 +00002146 // Place this field at the current location.
Ken Dyck9ed9a252011-02-20 02:06:09 +00002147 FieldOffsets.push_back(Context.toBits(FieldOffset));
Mike Stump1eb44332009-09-09 15:08:12 +00002148
Douglas Gregor453dbcb2012-01-26 07:55:45 +00002149 if (!ExternalLayout)
2150 CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset,
2151 Context.toBits(UnpackedFieldOffset),
2152 Context.toBits(UnpackedFieldAlign), FieldPacked, D);
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002153
Anders Carlssonbda4c102009-07-18 20:20:21 +00002154 // Reserve space for this field.
Eli Friedmancd7a21b2012-01-12 23:27:03 +00002155 uint64_t FieldSizeInBits = Context.toBits(FieldSize);
Anders Carlssonbda4c102009-07-18 20:20:21 +00002156 if (IsUnion)
Eli Friedman83be12c2012-01-12 23:48:56 +00002157 setDataSize(std::max(getDataSizeInBits(), FieldSizeInBits));
Anders Carlssonbda4c102009-07-18 20:20:21 +00002158 else
Eli Friedman83be12c2012-01-12 23:48:56 +00002159 setDataSize(FieldOffset + FieldSize);
Mike Stump1eb44332009-09-09 15:08:12 +00002160
Eli Friedman83be12c2012-01-12 23:48:56 +00002161 // Update the size.
2162 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Mike Stump1eb44332009-09-09 15:08:12 +00002163
Anders Carlssonbda4c102009-07-18 20:20:21 +00002164 // Remember max struct/class alignment.
Ken Dyck9ed9a252011-02-20 02:06:09 +00002165 UpdateAlignment(FieldAlign, UnpackedFieldAlign);
Anders Carlssonbda4c102009-07-18 20:20:21 +00002166}
2167
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002168void RecordLayoutBuilder::FinishLayout(const NamedDecl *D) {
Douglas Gregor394f7b62012-01-28 00:53:29 +00002169 if (ExternalLayout) {
2170 setSize(ExternalSize);
2171 return;
2172 }
2173
Anders Carlssonbda4c102009-07-18 20:20:21 +00002174 // In C++, records cannot be of size 0.
David Blaikie4e4d0842012-03-11 07:00:24 +00002175 if (Context.getLangOpts().CPlusPlus && getSizeInBits() == 0) {
Fariborz Jahanianadf082e2011-02-02 19:36:18 +00002176 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2177 // Compatibility with gcc requires a class (pod or non-pod)
2178 // which is not empty but of size 0; such as having fields of
2179 // array of zero-length, remains of Size 0
2180 if (RD->isEmpty())
Ken Dyckf079b732011-02-28 02:01:38 +00002181 setSize(CharUnits::One());
Fariborz Jahanianadf082e2011-02-02 19:36:18 +00002182 }
2183 else
Ken Dyckf079b732011-02-28 02:01:38 +00002184 setSize(CharUnits::One());
Fariborz Jahanianadf082e2011-02-02 19:36:18 +00002185 }
Eli Friedman901dd662011-12-01 00:37:01 +00002186
2187 // MSVC doesn't round up to the alignment of the record with virtual bases.
2188 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2189 if (isMicrosoftCXXABI() && RD->getNumVBases())
2190 return;
2191 }
2192
Anders Carlssonbda4c102009-07-18 20:20:21 +00002193 // Finally, round the size of the record up to the alignment of the
2194 // record itself.
Ken Dycka0c21c42011-02-24 01:13:28 +00002195 uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastByte;
Ken Dyckf079b732011-02-28 02:01:38 +00002196 uint64_t UnpackedSizeInBits =
Ken Dycka0c21c42011-02-24 01:13:28 +00002197 llvm::RoundUpToAlignment(getSizeInBits(),
2198 Context.toBits(UnpackedAlignment));
Ken Dyckf079b732011-02-28 02:01:38 +00002199 CharUnits UnpackedSize = Context.toCharUnitsFromBits(UnpackedSizeInBits);
Ken Dycka0c21c42011-02-24 01:13:28 +00002200 setSize(llvm::RoundUpToAlignment(getSizeInBits(), Context.toBits(Alignment)));
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002201
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002202 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002203 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
2204 // Warn if padding was introduced to the struct/class/union.
Ken Dycka0c21c42011-02-24 01:13:28 +00002205 if (getSizeInBits() > UnpaddedSize) {
2206 unsigned PadSize = getSizeInBits() - UnpaddedSize;
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002207 bool InBits = true;
2208 if (PadSize % CharBitNum == 0) {
2209 PadSize = PadSize / CharBitNum;
2210 InBits = false;
2211 }
2212 Diag(RD->getLocation(), diag::warn_padded_struct_size)
2213 << Context.getTypeDeclType(RD)
2214 << PadSize
2215 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
2216 }
2217
2218 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
2219 // bother since there won't be alignment issues.
Ken Dycka0c21c42011-02-24 01:13:28 +00002220 if (Packed && UnpackedAlignment > CharUnits::One() &&
Ken Dyckf079b732011-02-28 02:01:38 +00002221 getSize() == UnpackedSize)
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002222 Diag(D->getLocation(), diag::warn_unnecessary_packed)
2223 << Context.getTypeDeclType(RD);
2224 }
Anders Carlssonbda4c102009-07-18 20:20:21 +00002225}
2226
Ken Dyck3263e092011-02-19 18:58:07 +00002227void RecordLayoutBuilder::UpdateAlignment(CharUnits NewAlignment,
2228 CharUnits UnpackedNewAlignment) {
Douglas Gregor453dbcb2012-01-26 07:55:45 +00002229 // The alignment is not modified when using 'mac68k' alignment or when
Douglas Gregor394f7b62012-01-28 00:53:29 +00002230 // we have an externally-supplied layout that also provides overall alignment.
2231 if (IsMac68kAlign || (ExternalLayout && !InferAlignment))
Daniel Dunbarc6082fe2010-05-27 05:45:51 +00002232 return;
2233
Ken Dyck3263e092011-02-19 18:58:07 +00002234 if (NewAlignment > Alignment) {
2235 assert(llvm::isPowerOf2_32(NewAlignment.getQuantity() &&
2236 "Alignment not a power of 2"));
2237 Alignment = NewAlignment;
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002238 }
2239
Ken Dyck3263e092011-02-19 18:58:07 +00002240 if (UnpackedNewAlignment > UnpackedAlignment) {
2241 assert(llvm::isPowerOf2_32(UnpackedNewAlignment.getQuantity() &&
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002242 "Alignment not a power of 2"));
Ken Dyck3263e092011-02-19 18:58:07 +00002243 UnpackedAlignment = UnpackedNewAlignment;
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002244 }
2245}
2246
Douglas Gregor394f7b62012-01-28 00:53:29 +00002247uint64_t
2248RecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field,
2249 uint64_t ComputedOffset) {
2250 assert(ExternalFieldOffsets.find(Field) != ExternalFieldOffsets.end() &&
2251 "Field does not have an external offset");
2252
2253 uint64_t ExternalFieldOffset = ExternalFieldOffsets[Field];
2254
2255 if (InferAlignment && ExternalFieldOffset < ComputedOffset) {
2256 // The externally-supplied field offset is before the field offset we
2257 // computed. Assume that the structure is packed.
2258 Alignment = CharUnits::fromQuantity(1);
2259 InferAlignment = false;
2260 }
2261
2262 // Use the externally-supplied field offset.
2263 return ExternalFieldOffset;
2264}
2265
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002266void RecordLayoutBuilder::CheckFieldPadding(uint64_t Offset,
2267 uint64_t UnpaddedOffset,
2268 uint64_t UnpackedOffset,
2269 unsigned UnpackedAlign,
2270 bool isPacked,
2271 const FieldDecl *D) {
2272 // We let objc ivars without warning, objc interfaces generally are not used
2273 // for padding tricks.
2274 if (isa<ObjCIvarDecl>(D))
Anders Carlssonbda4c102009-07-18 20:20:21 +00002275 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002276
Ted Kremenekae5860e2011-09-06 19:40:45 +00002277 // Don't warn about structs created without a SourceLocation. This can
2278 // be done by clients of the AST, such as codegen.
2279 if (D->getLocation().isInvalid())
2280 return;
2281
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002282 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
Mike Stump1eb44332009-09-09 15:08:12 +00002283
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002284 // Warn if padding was introduced to the struct/class.
2285 if (!IsUnion && Offset > UnpaddedOffset) {
2286 unsigned PadSize = Offset - UnpaddedOffset;
2287 bool InBits = true;
2288 if (PadSize % CharBitNum == 0) {
2289 PadSize = PadSize / CharBitNum;
2290 InBits = false;
2291 }
2292 if (D->getIdentifier())
2293 Diag(D->getLocation(), diag::warn_padded_struct_field)
2294 << (D->getParent()->isStruct() ? 0 : 1) // struct|class
2295 << Context.getTypeDeclType(D->getParent())
2296 << PadSize
2297 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1) // plural or not
2298 << D->getIdentifier();
2299 else
2300 Diag(D->getLocation(), diag::warn_padded_struct_anon_field)
2301 << (D->getParent()->isStruct() ? 0 : 1) // struct|class
2302 << Context.getTypeDeclType(D->getParent())
2303 << PadSize
2304 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
2305 }
2306
2307 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
2308 // bother since there won't be alignment issues.
2309 if (isPacked && UnpackedAlign > CharBitNum && Offset == UnpackedOffset)
2310 Diag(D->getLocation(), diag::warn_unnecessary_packed)
2311 << D->getIdentifier();
Anders Carlssonbda4c102009-07-18 20:20:21 +00002312}
Mike Stump1eb44332009-09-09 15:08:12 +00002313
Anders Carlssonf53df232009-12-07 04:35:11 +00002314const CXXMethodDecl *
Anders Carlsson7d0918a2010-05-26 05:58:59 +00002315RecordLayoutBuilder::ComputeKeyFunction(const CXXRecordDecl *RD) {
Daniel Dunbar8d8ab742010-04-19 20:44:53 +00002316 // If a class isn't polymorphic it doesn't have a key function.
Anders Carlssonf53df232009-12-07 04:35:11 +00002317 if (!RD->isPolymorphic())
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00002318 return 0;
Eli Friedman61eab882009-12-08 03:56:49 +00002319
Eli Friedmancb5d2d02011-06-10 21:53:06 +00002320 // A class that is not externally visible doesn't have a key function. (Or
Eli Friedman61eab882009-12-08 03:56:49 +00002321 // at least, there's no point to assigning a key function to such a class;
2322 // this doesn't affect the ABI.)
Eli Friedmancb5d2d02011-06-10 21:53:06 +00002323 if (RD->getLinkage() != ExternalLinkage)
Eli Friedman61eab882009-12-08 03:56:49 +00002324 return 0;
2325
Argyrios Kyrtzidis3bd5b6c2010-10-13 02:39:41 +00002326 // Template instantiations don't have key functions,see Itanium C++ ABI 5.2.6.
2327 // Same behavior as GCC.
2328 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
2329 if (TSK == TSK_ImplicitInstantiation ||
2330 TSK == TSK_ExplicitInstantiationDefinition)
2331 return 0;
2332
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002333 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
2334 E = RD->method_end(); I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00002335 const CXXMethodDecl *MD = *I;
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002336
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00002337 if (!MD->isVirtual())
2338 continue;
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002339
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00002340 if (MD->isPure())
2341 continue;
Eli Friedman61eab882009-12-08 03:56:49 +00002342
Anders Carlsson5ec02ae2009-12-02 17:15:43 +00002343 // Ignore implicit member functions, they are always marked as inline, but
2344 // they don't have a body until they're defined.
2345 if (MD->isImplicit())
2346 continue;
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002347
Douglas Gregorbd6d6192010-01-05 19:06:31 +00002348 if (MD->isInlineSpecified())
2349 continue;
Eli Friedmand7d7f672009-12-06 20:50:05 +00002350
2351 if (MD->hasInlineBody())
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00002352 continue;
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002353
Benjamin Kramerc23aca42012-08-03 15:43:22 +00002354 // Ignore inline deleted or defaulted functions.
Benjamin Kramerf3fce802012-08-03 08:39:58 +00002355 if (!MD->isUserProvided())
2356 continue;
2357
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00002358 // We found it.
2359 return MD;
2360 }
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002361
Anders Carlsson1a5e0d72009-11-30 23:41:22 +00002362 return 0;
2363}
2364
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002365DiagnosticBuilder
2366RecordLayoutBuilder::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidis33e4e702010-11-18 20:06:41 +00002367 return Context.getDiagnostics().Report(Loc, DiagID);
Argyrios Kyrtzidis78a916e2010-09-22 14:32:24 +00002368}
2369
Anders Carlsson1e641ce2010-05-26 04:56:53 +00002370/// getASTRecordLayout - Get or compute information about the layout of the
2371/// specified record (struct/union/class), which indicates its size and field
2372/// position information.
Jay Foad4ba2a172011-01-12 09:06:06 +00002373const ASTRecordLayout &
2374ASTContext::getASTRecordLayout(const RecordDecl *D) const {
John McCall65959352011-10-07 02:39:22 +00002375 // These asserts test different things. A record has a definition
2376 // as soon as we begin to parse the definition. That definition is
2377 // not a complete definition (which is what isDefinition() tests)
2378 // until we *finish* parsing the definition.
Sean Callananfd5a5f52012-02-08 00:04:52 +00002379
2380 if (D->hasExternalLexicalStorage() && !D->getDefinition())
2381 getExternalSource()->CompleteType(const_cast<RecordDecl*>(D));
2382
Anders Carlsson1e641ce2010-05-26 04:56:53 +00002383 D = D->getDefinition();
2384 assert(D && "Cannot get layout of forward declarations!");
John McCall5e1cdac2011-10-07 06:10:15 +00002385 assert(D->isCompleteDefinition() && "Cannot layout type before complete!");
Anders Carlsson1e641ce2010-05-26 04:56:53 +00002386
2387 // Look up this layout, if already laid out, return what we have.
2388 // Note that we can't save a reference to the entry because this function
2389 // is recursive.
2390 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
2391 if (Entry) return *Entry;
2392
Anders Carlsson2f64e372010-05-26 05:10:47 +00002393 const ASTRecordLayout *NewEntry;
2394
2395 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
Anders Carlsson261febd2010-05-27 00:07:01 +00002396 EmptySubobjectMap EmptySubobjects(*this, RD);
John McCall9da23522011-11-08 04:01:03 +00002397 RecordLayoutBuilder Builder(*this, &EmptySubobjects);
2398 Builder.Layout(RD);
Anders Carlsson58b16b62010-05-27 05:41:06 +00002399
John McCall9da23522011-11-08 04:01:03 +00002400 // MSVC gives the vb-table pointer an alignment equal to that of
2401 // the non-virtual part of the structure. That's an inherently
2402 // multi-pass operation. If our first pass doesn't give us
2403 // adequate alignment, try again with the specified minimum
2404 // alignment. This is *much* more maintainable than computing the
2405 // alignment in advance in a separately-coded pass; it's also
2406 // significantly more efficient in the common case where the
2407 // vb-table doesn't need extra padding.
2408 if (Builder.VBPtrOffset != CharUnits::fromQuantity(-1) &&
2409 (Builder.VBPtrOffset % Builder.NonVirtualAlignment) != 0) {
2410 Builder.resetWithTargetAlignment(Builder.NonVirtualAlignment);
2411 Builder.Layout(RD);
Eli Friedman2fe36362011-09-27 19:12:27 +00002412 }
2413
Anders Carlsson2f64e372010-05-26 05:10:47 +00002414 // FIXME: This is not always correct. See the part about bitfields at
2415 // http://www.codesourcery.com/public/cxx-abi/abi.html#POD for more info.
2416 // FIXME: IsPODForThePurposeOfLayout should be stored in the record layout.
Eli Friedman2fe36362011-09-27 19:12:27 +00002417 // This does not affect the calculations of MSVC layouts
2418 bool IsPODForThePurposeOfLayout =
John McCall9da23522011-11-08 04:01:03 +00002419 (!Builder.isMicrosoftCXXABI() && cast<CXXRecordDecl>(D)->isPOD());
Anders Carlsson2f64e372010-05-26 05:10:47 +00002420
2421 // FIXME: This should be done in FinalizeLayout.
Ken Dyckf079b732011-02-28 02:01:38 +00002422 CharUnits DataSize =
John McCall9da23522011-11-08 04:01:03 +00002423 IsPODForThePurposeOfLayout ? Builder.getSize() : Builder.getDataSize();
Ken Dyckf079b732011-02-28 02:01:38 +00002424 CharUnits NonVirtualSize =
John McCall9da23522011-11-08 04:01:03 +00002425 IsPODForThePurposeOfLayout ? DataSize : Builder.NonVirtualSize;
Anders Carlsson2f64e372010-05-26 05:10:47 +00002426
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00002427 NewEntry =
John McCall9da23522011-11-08 04:01:03 +00002428 new (*this) ASTRecordLayout(*this, Builder.getSize(),
2429 Builder.Alignment,
John McCall441c6232012-05-01 08:55:32 +00002430 Builder.HasOwnVFPtr,
John McCall9da23522011-11-08 04:01:03 +00002431 Builder.VBPtrOffset,
Ken Dyckf079b732011-02-28 02:01:38 +00002432 DataSize,
John McCall9da23522011-11-08 04:01:03 +00002433 Builder.FieldOffsets.data(),
2434 Builder.FieldOffsets.size(),
Ken Dycka1fdb0b2011-02-16 01:52:01 +00002435 NonVirtualSize,
John McCall9da23522011-11-08 04:01:03 +00002436 Builder.NonVirtualAlignment,
Anders Carlsson261febd2010-05-27 00:07:01 +00002437 EmptySubobjects.SizeOfLargestEmptySubobject,
John McCall9da23522011-11-08 04:01:03 +00002438 Builder.PrimaryBase,
2439 Builder.PrimaryBaseIsVirtual,
2440 Builder.Bases, Builder.VBases);
Anders Carlsson2f64e372010-05-26 05:10:47 +00002441 } else {
John McCall9da23522011-11-08 04:01:03 +00002442 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
Anders Carlsson2f64e372010-05-26 05:10:47 +00002443 Builder.Layout(D);
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00002444
Anders Carlsson2f64e372010-05-26 05:10:47 +00002445 NewEntry =
Ken Dyckf079b732011-02-28 02:01:38 +00002446 new (*this) ASTRecordLayout(*this, Builder.getSize(),
Ken Dyckea7f6c22011-02-16 02:05:21 +00002447 Builder.Alignment,
Ken Dyckf079b732011-02-28 02:01:38 +00002448 Builder.getSize(),
Anders Carlsson2f64e372010-05-26 05:10:47 +00002449 Builder.FieldOffsets.data(),
2450 Builder.FieldOffsets.size());
2451 }
2452
Anders Carlsson1e641ce2010-05-26 04:56:53 +00002453 ASTRecordLayouts[D] = NewEntry;
2454
David Blaikie4e4d0842012-03-11 07:00:24 +00002455 if (getLangOpts().DumpRecordLayouts) {
Anders Carlsson1e641ce2010-05-26 04:56:53 +00002456 llvm::errs() << "\n*** Dumping AST Record Layout\n";
David Blaikie4e4d0842012-03-11 07:00:24 +00002457 DumpRecordLayout(D, llvm::errs(), getLangOpts().DumpRecordLayoutsSimple);
Anders Carlsson1e641ce2010-05-26 04:56:53 +00002458 }
2459
2460 return *NewEntry;
2461}
2462
2463const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) {
2464 RD = cast<CXXRecordDecl>(RD->getDefinition());
2465 assert(RD && "Cannot get key function for forward declarations!");
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00002466
Anders Carlsson1e641ce2010-05-26 04:56:53 +00002467 const CXXMethodDecl *&Entry = KeyFunctions[RD];
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00002468 if (!Entry)
Anders Carlsson7d0918a2010-05-26 05:58:59 +00002469 Entry = RecordLayoutBuilder::ComputeKeyFunction(RD);
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00002470
Anders Carlsson1e641ce2010-05-26 04:56:53 +00002471 return Entry;
2472}
2473
Richard Smith2d6a5672012-01-14 04:30:29 +00002474static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) {
2475 const ASTRecordLayout &Layout = C.getASTRecordLayout(FD->getParent());
2476 return Layout.getFieldOffset(FD->getFieldIndex());
2477}
2478
2479uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const {
2480 uint64_t OffsetInBits;
2481 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
2482 OffsetInBits = ::getFieldOffset(*this, FD);
2483 } else {
2484 const IndirectFieldDecl *IFD = cast<IndirectFieldDecl>(VD);
2485
2486 OffsetInBits = 0;
2487 for (IndirectFieldDecl::chain_iterator CI = IFD->chain_begin(),
2488 CE = IFD->chain_end();
2489 CI != CE; ++CI)
2490 OffsetInBits += ::getFieldOffset(*this, cast<FieldDecl>(*CI));
2491 }
2492
2493 return OffsetInBits;
2494}
2495
Eric Christopher68395a72011-10-05 06:00:51 +00002496/// getObjCLayout - Get or compute information about the layout of the
2497/// given interface.
Anders Carlsson1e641ce2010-05-26 04:56:53 +00002498///
2499/// \param Impl - If given, also include the layout of the interface's
2500/// implementation. This may differ by including synthesized ivars.
2501const ASTRecordLayout &
2502ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
Jay Foad4ba2a172011-01-12 09:06:06 +00002503 const ObjCImplementationDecl *Impl) const {
Douglas Gregore7aa27a2011-12-20 15:50:13 +00002504 // Retrieve the definition
Sean Callanancad313b2012-03-15 16:33:08 +00002505 if (D->hasExternalLexicalStorage() && !D->getDefinition())
2506 getExternalSource()->CompleteType(const_cast<ObjCInterfaceDecl*>(D));
Douglas Gregore7aa27a2011-12-20 15:50:13 +00002507 D = D->getDefinition();
2508 assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!");
Anders Carlsson1e641ce2010-05-26 04:56:53 +00002509
2510 // Look up this layout, if already laid out, return what we have.
2511 ObjCContainerDecl *Key =
2512 Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
2513 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
2514 return *Entry;
2515
2516 // Add in synthesized ivar count if laying out an implementation.
2517 if (Impl) {
2518 unsigned SynthCount = CountNonClassIvars(D);
2519 // If there aren't any sythesized ivars then reuse the interface
2520 // entry. Note we can't cache this because we simply free all
2521 // entries later; however we shouldn't look up implementations
2522 // frequently.
2523 if (SynthCount == 0)
2524 return getObjCLayout(D, 0);
2525 }
2526
John McCall9da23522011-11-08 04:01:03 +00002527 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
Anders Carlsson36cdc612010-05-26 05:04:25 +00002528 Builder.Layout(D);
2529
Anders Carlsson1e641ce2010-05-26 04:56:53 +00002530 const ASTRecordLayout *NewEntry =
Ken Dyckf079b732011-02-28 02:01:38 +00002531 new (*this) ASTRecordLayout(*this, Builder.getSize(),
Ken Dyckea7f6c22011-02-16 02:05:21 +00002532 Builder.Alignment,
Ken Dyckf079b732011-02-28 02:01:38 +00002533 Builder.getDataSize(),
Anders Carlsson36cdc612010-05-26 05:04:25 +00002534 Builder.FieldOffsets.data(),
2535 Builder.FieldOffsets.size());
Daniel Dunbar0aa7edb2010-05-27 02:25:46 +00002536
Anders Carlsson1e641ce2010-05-26 04:56:53 +00002537 ObjCLayouts[Key] = NewEntry;
2538
2539 return *NewEntry;
2540}
2541
Chris Lattner5f9e2722011-07-23 10:55:15 +00002542static void PrintOffset(raw_ostream &OS,
Anders Carlsson3069a0d2010-10-31 23:45:59 +00002543 CharUnits Offset, unsigned IndentLevel) {
Benjamin Kramere4ebbf72011-11-05 09:02:52 +00002544 OS << llvm::format("%4" PRId64 " | ", (int64_t)Offset.getQuantity());
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002545 OS.indent(IndentLevel * 2);
2546}
2547
Chris Lattner5f9e2722011-07-23 10:55:15 +00002548static void DumpCXXRecordLayout(raw_ostream &OS,
Jay Foad4ba2a172011-01-12 09:06:06 +00002549 const CXXRecordDecl *RD, const ASTContext &C,
Anders Carlsson3069a0d2010-10-31 23:45:59 +00002550 CharUnits Offset,
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002551 unsigned IndentLevel,
2552 const char* Description,
2553 bool IncludeVirtualBases) {
Anders Carlsson3069a0d2010-10-31 23:45:59 +00002554 const ASTRecordLayout &Layout = C.getASTRecordLayout(RD);
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002555
2556 PrintOffset(OS, Offset, IndentLevel);
Dan Gohmancb421fa2010-04-19 16:39:44 +00002557 OS << C.getTypeDeclType(const_cast<CXXRecordDecl *>(RD)).getAsString();
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002558 if (Description)
2559 OS << ' ' << Description;
2560 if (RD->isEmpty())
2561 OS << " (empty)";
2562 OS << '\n';
2563
2564 IndentLevel++;
2565
Anders Carlsson3069a0d2010-10-31 23:45:59 +00002566 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
John McCall441c6232012-05-01 08:55:32 +00002567 bool HasVfptr = Layout.hasOwnVFPtr();
Eli Friedman2fe36362011-09-27 19:12:27 +00002568 bool HasVbptr = Layout.getVBPtrOffset() != CharUnits::fromQuantity(-1);
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002569
2570 // Vtable pointer.
Eli Friedman227e4832011-10-21 22:49:56 +00002571 if (RD->isDynamicClass() && !PrimaryBase &&
2572 C.getTargetInfo().getCXXABI() != CXXABI_Microsoft) {
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002573 PrintOffset(OS, Offset, IndentLevel);
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002574 OS << '(' << *RD << " vtable pointer)\n";
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002575 }
Eli Friedman2fe36362011-09-27 19:12:27 +00002576
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002577 // Dump (non-virtual) bases
2578 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
2579 E = RD->bases_end(); I != E; ++I) {
2580 assert(!I->getType()->isDependentType() &&
2581 "Cannot layout class with dependent bases.");
2582 if (I->isVirtual())
2583 continue;
2584
2585 const CXXRecordDecl *Base =
2586 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
2587
Anders Carlsson3069a0d2010-10-31 23:45:59 +00002588 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002589
2590 DumpCXXRecordLayout(OS, Base, C, BaseOffset, IndentLevel,
2591 Base == PrimaryBase ? "(primary base)" : "(base)",
2592 /*IncludeVirtualBases=*/false);
2593 }
Eli Friedman227e4832011-10-21 22:49:56 +00002594
2595 // vfptr and vbptr (for Microsoft C++ ABI)
2596 if (HasVfptr) {
John McCall441c6232012-05-01 08:55:32 +00002597 PrintOffset(OS, Offset, IndentLevel);
Eli Friedman227e4832011-10-21 22:49:56 +00002598 OS << '(' << *RD << " vftable pointer)\n";
2599 }
Eli Friedman2fe36362011-09-27 19:12:27 +00002600 if (HasVbptr) {
2601 PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel);
Benjamin Kramerb8989f22011-10-14 18:45:37 +00002602 OS << '(' << *RD << " vbtable pointer)\n";
Eli Friedman2fe36362011-09-27 19:12:27 +00002603 }
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002604
2605 // Dump fields.
2606 uint64_t FieldNo = 0;
2607 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2608 E = RD->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie581deb32012-06-06 20:45:41 +00002609 const FieldDecl &Field = **I;
Anders Carlsson3069a0d2010-10-31 23:45:59 +00002610 CharUnits FieldOffset = Offset +
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00002611 C.toCharUnitsFromBits(Layout.getFieldOffset(FieldNo));
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002612
David Blaikie262bc182012-04-30 02:36:29 +00002613 if (const RecordType *RT = Field.getType()->getAs<RecordType>()) {
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002614 if (const CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2615 DumpCXXRecordLayout(OS, D, C, FieldOffset, IndentLevel,
David Blaikie262bc182012-04-30 02:36:29 +00002616 Field.getName().data(),
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002617 /*IncludeVirtualBases=*/true);
2618 continue;
2619 }
2620 }
2621
2622 PrintOffset(OS, FieldOffset, IndentLevel);
David Blaikie262bc182012-04-30 02:36:29 +00002623 OS << Field.getType().getAsString() << ' ' << Field << '\n';
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002624 }
2625
2626 if (!IncludeVirtualBases)
2627 return;
2628
2629 // Dump virtual bases.
John McCall441c6232012-05-01 08:55:32 +00002630 const ASTRecordLayout::VBaseOffsetsMapTy &vtordisps =
2631 Layout.getVBaseOffsetsMap();
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002632 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
2633 E = RD->vbases_end(); I != E; ++I) {
2634 assert(I->isVirtual() && "Found non-virtual class!");
2635 const CXXRecordDecl *VBase =
2636 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
2637
Anders Carlsson3069a0d2010-10-31 23:45:59 +00002638 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
John McCall441c6232012-05-01 08:55:32 +00002639
2640 if (vtordisps.find(VBase)->second.hasVtorDisp()) {
2641 PrintOffset(OS, VBaseOffset - CharUnits::fromQuantity(4), IndentLevel);
2642 OS << "(vtordisp for vbase " << *VBase << ")\n";
2643 }
2644
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002645 DumpCXXRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel,
2646 VBase == PrimaryBase ?
2647 "(primary virtual base)" : "(virtual base)",
2648 /*IncludeVirtualBases=*/false);
2649 }
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002650
Ken Dyck5f022d82011-02-09 01:59:34 +00002651 OS << " sizeof=" << Layout.getSize().getQuantity();
Ken Dyckec299032011-02-11 02:20:09 +00002652 OS << ", dsize=" << Layout.getDataSize().getQuantity();
Ken Dyckdac54c12011-02-15 02:32:40 +00002653 OS << ", align=" << Layout.getAlignment().getQuantity() << '\n';
Ken Dyck5c3633f2011-02-01 01:52:10 +00002654 OS << " nvsize=" << Layout.getNonVirtualSize().getQuantity();
Ken Dyck68cf1a52011-02-08 02:02:47 +00002655 OS << ", nvalign=" << Layout.getNonVirtualAlign().getQuantity() << '\n';
Daniel Dunbarbf9e48c2010-04-08 02:59:49 +00002656 OS << '\n';
2657}
Daniel Dunbar8d8ab742010-04-19 20:44:53 +00002658
2659void ASTContext::DumpRecordLayout(const RecordDecl *RD,
Douglas Gregor453dbcb2012-01-26 07:55:45 +00002660 raw_ostream &OS,
2661 bool Simple) const {
Daniel Dunbar8d8ab742010-04-19 20:44:53 +00002662 const ASTRecordLayout &Info = getASTRecordLayout(RD);
2663
2664 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Douglas Gregor453dbcb2012-01-26 07:55:45 +00002665 if (!Simple)
2666 return DumpCXXRecordLayout(OS, CXXRD, *this, CharUnits(), 0, 0,
2667 /*IncludeVirtualBases=*/true);
Daniel Dunbar8d8ab742010-04-19 20:44:53 +00002668
2669 OS << "Type: " << getTypeDeclType(RD).getAsString() << "\n";
Douglas Gregor453dbcb2012-01-26 07:55:45 +00002670 if (!Simple) {
2671 OS << "Record: ";
2672 RD->dump();
2673 }
Daniel Dunbar8d8ab742010-04-19 20:44:53 +00002674 OS << "\nLayout: ";
2675 OS << "<ASTRecordLayout\n";
Ken Dyckdd76a9a2011-02-11 01:54:29 +00002676 OS << " Size:" << toBits(Info.getSize()) << "\n";
Ken Dyckec299032011-02-11 02:20:09 +00002677 OS << " DataSize:" << toBits(Info.getDataSize()) << "\n";
Ken Dyckdac54c12011-02-15 02:32:40 +00002678 OS << " Alignment:" << toBits(Info.getAlignment()) << "\n";
Daniel Dunbar8d8ab742010-04-19 20:44:53 +00002679 OS << " FieldOffsets: [";
2680 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) {
2681 if (i) OS << ", ";
2682 OS << Info.getFieldOffset(i);
2683 }
2684 OS << "]>\n";
2685}