blob: 08f6d5c54b47bcde632a44c728206dbcec150127 [file] [log] [blame]
Anders Carlsson35a36eb2010-05-26 05:41:04 +00001//=== RecordLayoutBuilder.cpp - Helper class for building record layouts ---==//
Anders Carlsson79474332009-07-18 20:20:21 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
Chandler Carruth3a022472012-12-04 09:13:33 +000010#include "clang/AST/RecordLayout.h"
Benjamin Kramer2ef30312012-07-04 18:45:14 +000011#include "clang/AST/ASTContext.h"
Anders Carlsson79474332009-07-18 20:20:21 +000012#include "clang/AST/Attr.h"
Anders Carlsson5adde292010-11-24 22:55:48 +000013#include "clang/AST/CXXInheritance.h"
Anders Carlsson79474332009-07-18 20:20:21 +000014#include "clang/AST/Decl.h"
Anders Carlsson6d9f6f32009-07-19 00:18:47 +000015#include "clang/AST/DeclCXX.h"
Anders Carlsson4f516282009-07-18 20:50:59 +000016#include "clang/AST/DeclObjC.h"
Anders Carlsson79474332009-07-18 20:20:21 +000017#include "clang/AST/Expr.h"
Anders Carlsson79474332009-07-18 20:20:21 +000018#include "clang/Basic/TargetInfo.h"
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +000019#include "clang/Sema/SemaDiagnostic.h"
Daniel Dunbaraa423af2010-04-08 02:59:49 +000020#include "llvm/ADT/SmallSet.h"
Ted Kremenekf75d0892011-03-19 01:00:36 +000021#include "llvm/Support/CrashRecoveryContext.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000022#include "llvm/Support/Format.h"
23#include "llvm/Support/MathExtras.h"
Anders Carlsson79474332009-07-18 20:20:21 +000024
25using namespace clang;
26
Benjamin Kramerc7656cd2010-05-26 09:58:31 +000027namespace {
Anders Carlssonf58de112010-05-26 15:32:58 +000028
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000029/// BaseSubobjectInfo - Represents a single base subobject in a complete class.
30/// For a class hierarchy like
31///
32/// class A { };
33/// class B : A { };
34/// class C : A, B { };
35///
36/// The BaseSubobjectInfo graph for C will have three BaseSubobjectInfo
37/// instances, one for B and two for A.
38///
39/// If a base is virtual, it will only have one BaseSubobjectInfo allocated.
40struct BaseSubobjectInfo {
41 /// Class - The class for this base info.
Anders Carlsson056818f2010-05-28 21:13:31 +000042 const CXXRecordDecl *Class;
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000043
44 /// IsVirtual - Whether the BaseInfo represents a virtual base or not.
Anders Carlsson056818f2010-05-28 21:13:31 +000045 bool IsVirtual;
46
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000047 /// Bases - Information about the base subobjects.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000048 SmallVector<BaseSubobjectInfo*, 4> Bases;
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000049
Anders Carlssone3c24c72010-05-29 17:35:14 +000050 /// PrimaryVirtualBaseInfo - Holds the base info for the primary virtual base
51 /// of this base info (if one exists).
52 BaseSubobjectInfo *PrimaryVirtualBaseInfo;
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000053
54 // FIXME: Document.
55 const BaseSubobjectInfo *Derived;
Anders Carlsson056818f2010-05-28 21:13:31 +000056};
57
Anders Carlssonf58de112010-05-26 15:32:58 +000058/// EmptySubobjectMap - Keeps track of which empty subobjects exist at different
59/// offsets while laying out a C++ class.
60class EmptySubobjectMap {
Jay Foad39c79802011-01-12 09:06:06 +000061 const ASTContext &Context;
Anders Carlsson233e2722010-10-31 21:54:55 +000062 uint64_t CharWidth;
63
Anders Carlssonf58de112010-05-26 15:32:58 +000064 /// Class - The class whose empty entries we're keeping track of.
65 const CXXRecordDecl *Class;
Daniel Dunbar592a85c2010-05-27 02:25:46 +000066
Anders Carlsson439edd12010-05-27 05:41:06 +000067 /// EmptyClassOffsets - A map from offsets to empty record decls.
Chris Lattner0e62c1c2011-07-23 10:55:15 +000068 typedef SmallVector<const CXXRecordDecl *, 1> ClassVectorTy;
Anders Carlssonf8f756d2010-10-31 21:22:43 +000069 typedef llvm::DenseMap<CharUnits, ClassVectorTy> EmptyClassOffsetsMapTy;
Anders Carlsson439edd12010-05-27 05:41:06 +000070 EmptyClassOffsetsMapTy EmptyClassOffsets;
71
Anders Carlssoncc5de092010-06-08 15:56:03 +000072 /// MaxEmptyClassOffset - The highest offset known to contain an empty
73 /// base subobject.
Anders Carlsson725190f2010-10-31 21:39:24 +000074 CharUnits MaxEmptyClassOffset;
Anders Carlssoncc5de092010-06-08 15:56:03 +000075
Daniel Dunbar592a85c2010-05-27 02:25:46 +000076 /// ComputeEmptySubobjectSizes - Compute the size of the largest base or
Anders Carlssonc5ca1f72010-05-26 15:54:25 +000077 /// member subobject that is empty.
78 void ComputeEmptySubobjectSizes();
Anders Carlsson439edd12010-05-27 05:41:06 +000079
Anders Carlsson725190f2010-10-31 21:39:24 +000080 void AddSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset);
Anders Carlssondb319762010-05-27 18:20:57 +000081
Anders Carlssona7f3cdb2010-05-28 21:24:37 +000082 void UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +000083 CharUnits Offset, bool PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +000084
Anders Carlssondb319762010-05-27 18:20:57 +000085 void UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
86 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +000087 CharUnits Offset);
88 void UpdateEmptyFieldSubobjects(const FieldDecl *FD, CharUnits Offset);
Anders Carlssondb319762010-05-27 18:20:57 +000089
Anders Carlssoncc5de092010-06-08 15:56:03 +000090 /// AnyEmptySubobjectsBeyondOffset - Returns whether there are any empty
91 /// subobjects beyond the given offset.
Anders Carlsson725190f2010-10-31 21:39:24 +000092 bool AnyEmptySubobjectsBeyondOffset(CharUnits Offset) const {
Anders Carlssoncc5de092010-06-08 15:56:03 +000093 return Offset <= MaxEmptyClassOffset;
94 }
95
Anders Carlsson233e2722010-10-31 21:54:55 +000096 CharUnits
97 getFieldOffset(const ASTRecordLayout &Layout, unsigned FieldNo) const {
98 uint64_t FieldOffset = Layout.getFieldOffset(FieldNo);
99 assert(FieldOffset % CharWidth == 0 &&
100 "Field offset not at char boundary!");
101
Ken Dyck7c4026b2011-01-24 01:28:50 +0000102 return Context.toCharUnitsFromBits(FieldOffset);
Anders Carlssonf8f756d2010-10-31 21:22:43 +0000103 }
Anders Carlssonf8f756d2010-10-31 21:22:43 +0000104
Charles Davisc2c576a2010-08-19 00:55:19 +0000105protected:
Anders Carlsson725190f2010-10-31 21:39:24 +0000106 bool CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
107 CharUnits Offset) const;
Charles Davisc2c576a2010-08-19 00:55:19 +0000108
109 bool CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000110 CharUnits Offset);
Charles Davisc2c576a2010-08-19 00:55:19 +0000111
112 bool CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
113 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000114 CharUnits Offset) const;
Charles Davisc2c576a2010-08-19 00:55:19 +0000115 bool CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
Anders Carlsson233e2722010-10-31 21:54:55 +0000116 CharUnits Offset) const;
Charles Davisc2c576a2010-08-19 00:55:19 +0000117
Anders Carlssonf58de112010-05-26 15:32:58 +0000118public:
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000119 /// This holds the size of the largest empty subobject (either a base
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000120 /// or a member). Will be zero if the record being built doesn't contain
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000121 /// any empty classes.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000122 CharUnits SizeOfLargestEmptySubobject;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000123
Jay Foad39c79802011-01-12 09:06:06 +0000124 EmptySubobjectMap(const ASTContext &Context, const CXXRecordDecl *Class)
Anders Carlsson28466ab2010-10-31 22:13:23 +0000125 : Context(Context), CharWidth(Context.getCharWidth()), Class(Class) {
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000126 ComputeEmptySubobjectSizes();
127 }
128
129 /// CanPlaceBaseAtOffset - Return whether the given base class can be placed
130 /// at the given offset.
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000131 /// Returns false if placing the record will result in two components
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000132 /// (direct or indirect) of the same type having the same offset.
Anders Carlssoncc5de092010-06-08 15:56:03 +0000133 bool CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000134 CharUnits Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000135
136 /// CanPlaceFieldAtOffset - Return whether a field can be placed at the given
137 /// offset.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000138 bool CanPlaceFieldAtOffset(const FieldDecl *FD, CharUnits Offset);
Anders Carlssonf58de112010-05-26 15:32:58 +0000139};
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000140
141void EmptySubobjectMap::ComputeEmptySubobjectSizes() {
142 // Check the bases.
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 Carlsson28466ab2010-10-31 22:13:23 +0000148 CharUnits EmptySize;
Anders Carlssonc5ca1f72010-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 Dyckc8ae5502011-02-09 01:59:34 +0000152 EmptySize = Layout.getSize();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000153 } else {
154 // Otherwise, we get the largest empty subobject for the decl.
155 EmptySize = Layout.getSizeOfLargestEmptySubobject();
156 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000157
Anders Carlsson28466ab2010-10-31 22:13:23 +0000158 if (EmptySize > SizeOfLargestEmptySubobject)
159 SizeOfLargestEmptySubobject = EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000160 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000161
Anders Carlssonc5ca1f72010-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 Dunbar592a85c2010-05-27 02:25:46 +0000165
166 const RecordType *RT =
David Blaikie40ed2972012-06-06 20:45:41 +0000167 Context.getBaseElementType(I->getType())->getAs<RecordType>();
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000168
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000169 // We only care about record types.
170 if (!RT)
171 continue;
172
Anders Carlsson28466ab2010-10-31 22:13:23 +0000173 CharUnits EmptySize;
Anders Carlssonc5ca1f72010-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 Dyckc8ae5502011-02-09 01:59:34 +0000178 EmptySize = Layout.getSize();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000179 } else {
180 // Otherwise, we get the largest empty subobject for the decl.
181 EmptySize = Layout.getSizeOfLargestEmptySubobject();
182 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000183
Anders Carlsson28466ab2010-10-31 22:13:23 +0000184 if (EmptySize > SizeOfLargestEmptySubobject)
185 SizeOfLargestEmptySubobject = EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000186 }
187}
188
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000189bool
Anders Carlssondb319762010-05-27 18:20:57 +0000190EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
Anders Carlsson725190f2010-10-31 21:39:24 +0000191 CharUnits Offset) const {
Anders Carlssondb319762010-05-27 18:20:57 +0000192 // We only need to check empty bases.
193 if (!RD->isEmpty())
194 return true;
195
Anders Carlsson725190f2010-10-31 21:39:24 +0000196 EmptyClassOffsetsMapTy::const_iterator I = EmptyClassOffsets.find(Offset);
Anders Carlssondb319762010-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 Carlsson725190f2010-10-31 21:39:24 +0000209 CharUnits Offset) {
Anders Carlssondb319762010-05-27 18:20:57 +0000210 // We only care about empty bases.
211 if (!RD->isEmpty())
212 return;
213
Rafael Espindola7bcde192010-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 Carlsson725190f2010-10-31 21:39:24 +0000216 ClassVectorTy& Classes = EmptyClassOffsets[Offset];
Rafael Espindola7bcde192010-12-29 23:02:58 +0000217 if (std::find(Classes.begin(), Classes.end(), RD) != Classes.end())
218 return;
219
Anders Carlssondb319762010-05-27 18:20:57 +0000220 Classes.push_back(RD);
Anders Carlssoncc5de092010-06-08 15:56:03 +0000221
222 // Update the empty class offset.
Anders Carlsson725190f2010-10-31 21:39:24 +0000223 if (Offset > MaxEmptyClassOffset)
224 MaxEmptyClassOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000225}
226
227bool
Anders Carlsson28466ab2010-10-31 22:13:23 +0000228EmptySubobjectMap::CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
229 CharUnits Offset) {
Anders Carlsson45c1d282010-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 Carlsson28466ab2010-10-31 22:13:23 +0000232 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000233 return true;
234
Anders Carlsson28466ab2010-10-31 22:13:23 +0000235 if (!CanPlaceSubobjectAtOffset(Info->Class, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000236 return false;
237
Anders Carlsson439edd12010-05-27 05:41:06 +0000238 // Traverse all non-virtual bases.
Anders Carlssona7774a62010-05-29 21:10:24 +0000239 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
Anders Carlsson439edd12010-05-27 05:41:06 +0000240 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
Anders Carlssona7f3cdb2010-05-28 21:24:37 +0000241 BaseSubobjectInfo* Base = Info->Bases[I];
Anders Carlsson439edd12010-05-27 05:41:06 +0000242 if (Base->IsVirtual)
243 continue;
244
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000245 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlsson439edd12010-05-27 05:41:06 +0000246
247 if (!CanPlaceBaseSubobjectAtOffset(Base, BaseOffset))
248 return false;
249 }
250
Anders Carlssone3c24c72010-05-29 17:35:14 +0000251 if (Info->PrimaryVirtualBaseInfo) {
252 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
Anders Carlsson439edd12010-05-27 05:41:06 +0000253
254 if (Info == PrimaryVirtualBaseInfo->Derived) {
255 if (!CanPlaceBaseSubobjectAtOffset(PrimaryVirtualBaseInfo, Offset))
256 return false;
257 }
258 }
259
Anders Carlssondb319762010-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 Blaikie40ed2972012-06-06 20:45:41 +0000264 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000265 continue;
266
Anders Carlsson28466ab2010-10-31 22:13:23 +0000267 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
David Blaikie40ed2972012-06-06 20:45:41 +0000268 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000269 return false;
270 }
271
Anders Carlsson439edd12010-05-27 05:41:06 +0000272 return true;
273}
274
Anders Carlssona7f3cdb2010-05-28 21:24:37 +0000275void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000276 CharUnits Offset,
Anders Carlssoncc59cc52010-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 Carlsson28466ab2010-10-31 22:13:23 +0000287 AddSubobjectAtOffset(Info->Class, Offset);
Anders Carlssona7774a62010-05-29 21:10:24 +0000288
Anders Carlsson439edd12010-05-27 05:41:06 +0000289 // Traverse all non-virtual bases.
Anders Carlssona7774a62010-05-29 21:10:24 +0000290 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
Anders Carlsson439edd12010-05-27 05:41:06 +0000291 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
Anders Carlssona7f3cdb2010-05-28 21:24:37 +0000292 BaseSubobjectInfo* Base = Info->Bases[I];
Anders Carlsson439edd12010-05-27 05:41:06 +0000293 if (Base->IsVirtual)
294 continue;
Anders Carlssona7774a62010-05-29 21:10:24 +0000295
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000296 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000297 UpdateEmptyBaseSubobjects(Base, BaseOffset, PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +0000298 }
299
Anders Carlssone3c24c72010-05-29 17:35:14 +0000300 if (Info->PrimaryVirtualBaseInfo) {
301 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
Anders Carlsson439edd12010-05-27 05:41:06 +0000302
303 if (Info == PrimaryVirtualBaseInfo->Derived)
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000304 UpdateEmptyBaseSubobjects(PrimaryVirtualBaseInfo, Offset,
305 PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +0000306 }
Anders Carlssondb319762010-05-27 18:20:57 +0000307
Anders Carlssondb319762010-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 Blaikie40ed2972012-06-06 20:45:41 +0000312 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000313 continue;
Anders Carlssona7774a62010-05-29 21:10:24 +0000314
Anders Carlsson28466ab2010-10-31 22:13:23 +0000315 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
David Blaikie40ed2972012-06-06 20:45:41 +0000316 UpdateEmptyFieldSubobjects(*I, FieldOffset);
Anders Carlssondb319762010-05-27 18:20:57 +0000317 }
Anders Carlsson439edd12010-05-27 05:41:06 +0000318}
319
Anders Carlssona60b86a2010-05-29 20:49:49 +0000320bool EmptySubobjectMap::CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000321 CharUnits Offset) {
Anders Carlssonc121b4e2010-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 Carlsson28466ab2010-10-31 22:13:23 +0000324 if (SizeOfLargestEmptySubobject.isZero())
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000325 return true;
326
Anders Carlsson439edd12010-05-27 05:41:06 +0000327 if (!CanPlaceBaseSubobjectAtOffset(Info, Offset))
328 return false;
Anders Carlssondb319762010-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 Carlssoncc59cc52010-06-13 18:00:18 +0000332 UpdateEmptyBaseSubobjects(Info, Offset, Info->Class->isEmpty());
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000333 return true;
334}
335
Anders Carlssondb319762010-05-27 18:20:57 +0000336bool
337EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
338 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000339 CharUnits Offset) const {
Anders Carlsson45c1d282010-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 Carlsson28466ab2010-10-31 22:13:23 +0000342 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000343 return true;
344
Anders Carlsson28466ab2010-10-31 22:13:23 +0000345 if (!CanPlaceSubobjectAtOffset(RD, Offset))
Anders Carlssondb319762010-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 Carlsson0a14ee92010-11-01 00:21:58 +0000359 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
Anders Carlssondb319762010-05-27 18:20:57 +0000360 if (!CanPlaceFieldSubobjectAtOffset(BaseDecl, Class, BaseOffset))
361 return false;
362 }
363
Anders Carlsson44687202010-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 Carlsson3f018712010-10-31 23:45:59 +0000371 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
Anders Carlsson44687202010-06-08 19:09:24 +0000372 if (!CanPlaceFieldSubobjectAtOffset(VBaseDecl, Class, VBaseOffset))
373 return false;
374 }
375 }
376
Anders Carlssondb319762010-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 Blaikie40ed2972012-06-06 20:45:41 +0000381 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000382 continue;
383
Anders Carlsson28466ab2010-10-31 22:13:23 +0000384 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
Anders Carlssondb319762010-05-27 18:20:57 +0000385
David Blaikie40ed2972012-06-06 20:45:41 +0000386 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000387 return false;
388 }
389
390 return true;
391}
392
Anders Carlsson233e2722010-10-31 21:54:55 +0000393bool
394EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
395 CharUnits Offset) const {
Anders Carlsson45c1d282010-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 Carlsson233e2722010-10-31 21:54:55 +0000398 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000399 return true;
400
Anders Carlssondb319762010-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 Carlsson28466ab2010-10-31 22:13:23 +0000404 return CanPlaceFieldSubobjectAtOffset(RD, RD, Offset);
Anders Carlssondb319762010-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 Carlsson233e2722010-10-31 21:54:55 +0000418 CharUnits ElementOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000419 for (uint64_t I = 0; I != NumElements; ++I) {
Anders Carlsson45c1d282010-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 Carlsson233e2722010-10-31 21:54:55 +0000422 if (!AnyEmptySubobjectsBeyondOffset(ElementOffset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000423 return true;
424
Anders Carlsson28466ab2010-10-31 22:13:23 +0000425 if (!CanPlaceFieldSubobjectAtOffset(RD, RD, ElementOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000426 return false;
427
Ken Dyckc8ae5502011-02-09 01:59:34 +0000428 ElementOffset += Layout.getSize();
Anders Carlssondb319762010-05-27 18:20:57 +0000429 }
430 }
431
432 return true;
433}
434
435bool
Anders Carlsson28466ab2010-10-31 22:13:23 +0000436EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl *FD,
437 CharUnits Offset) {
438 if (!CanPlaceFieldSubobjectAtOffset(FD, Offset))
Anders Carlssondb319762010-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 Carlsson28466ab2010-10-31 22:13:23 +0000449 CharUnits Offset) {
Anders Carlssonae111dc2010-06-13 17:49:16 +0000450 // We know that the only empty subobjects that can conflict with empty
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000451 // field subobjects are subobjects of empty bases that can be placed at offset
Anders Carlssonae111dc2010-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 Carlsson28466ab2010-10-31 22:13:23 +0000458 AddSubobjectAtOffset(RD, Offset);
Anders Carlssondb319762010-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 Carlsson0a14ee92010-11-01 00:21:58 +0000471 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
Anders Carlssondb319762010-05-27 18:20:57 +0000472 UpdateEmptyFieldSubobjects(BaseDecl, Class, BaseOffset);
473 }
474
Anders Carlsson44687202010-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 Carlsson3f018712010-10-31 23:45:59 +0000482 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
Anders Carlsson44687202010-06-08 19:09:24 +0000483 UpdateEmptyFieldSubobjects(VBaseDecl, Class, VBaseOffset);
484 }
485 }
486
Anders Carlssondb319762010-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 Blaikie40ed2972012-06-06 20:45:41 +0000491 if (I->isBitField())
Anders Carlsson09814d32010-11-01 15:14:51 +0000492 continue;
493
Anders Carlsson28466ab2010-10-31 22:13:23 +0000494 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
Anders Carlssondb319762010-05-27 18:20:57 +0000495
David Blaikie40ed2972012-06-06 20:45:41 +0000496 UpdateEmptyFieldSubobjects(*I, FieldOffset);
Anders Carlssondb319762010-05-27 18:20:57 +0000497 }
498}
499
500void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const FieldDecl *FD,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000501 CharUnits Offset) {
Anders Carlssondb319762010-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 Carlsson28466ab2010-10-31 22:13:23 +0000520 CharUnits ElementOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000521
522 for (uint64_t I = 0; I != NumElements; ++I) {
Anders Carlssonae111dc2010-06-13 17:49:16 +0000523 // We know that the only empty subobjects that can conflict with empty
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000524 // field subobjects are subobjects of empty bases that can be placed at
Anders Carlssonae111dc2010-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 Carlssondb319762010-05-27 18:20:57 +0000531 UpdateEmptyFieldSubobjects(RD, RD, ElementOffset);
Ken Dyckc8ae5502011-02-09 01:59:34 +0000532 ElementOffset += Layout.getSize();
Anders Carlssondb319762010-05-27 18:20:57 +0000533 }
534 }
535}
536
John McCalle42a3362012-05-01 08:55:32 +0000537typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> ClassSetTy;
538
Anders Carlssonc2226202010-05-26 05:58:59 +0000539class RecordLayoutBuilder {
Charles Davisc2c576a2010-08-19 00:55:19 +0000540protected:
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000541 // FIXME: Remove this and make the appropriate fields public.
542 friend class clang::ASTContext;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000543
Jay Foad39c79802011-01-12 09:06:06 +0000544 const ASTContext &Context;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000545
Anders Carlssonf58de112010-05-26 15:32:58 +0000546 EmptySubobjectMap *EmptySubobjects;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000547
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000548 /// Size - The current size of the record layout.
549 uint64_t Size;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000550
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000551 /// Alignment - The current alignment of the record layout.
Ken Dyck4731d5b2011-02-16 02:05:21 +0000552 CharUnits Alignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000553
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000554 /// \brief The alignment if attribute packed is not used.
Ken Dyck1300b3b2011-02-16 02:11:31 +0000555 CharUnits UnpackedAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000556
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000557 SmallVector<uint64_t, 16> FieldOffsets;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000558
Douglas Gregore9fc3772012-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 Gregor44ba7892012-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 Gregore9fc3772012-01-26 07:55:45 +0000566
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000567 /// Packed - Whether the record is packed or not.
Daniel Dunbar6da10982010-05-27 05:45:51 +0000568 unsigned Packed : 1;
569
570 unsigned IsUnion : 1;
571
572 unsigned IsMac68kAlign : 1;
Fariborz Jahanianbcb23a12011-04-26 23:52:16 +0000573
574 unsigned IsMsStruct : 1;
Anders Carlsson35a36eb2010-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 Dunbar592a85c2010-05-27 02:25:46 +0000580
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000581 /// MaxFieldAlignment - The maximum allowed field alignment. This is set by
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000582 /// #pragma pack.
Ken Dyck02ced6f2011-02-17 01:49:42 +0000583 CharUnits MaxFieldAlignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000584
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000585 /// DataSize - The data size of the record being laid out.
586 uint64_t DataSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000587
Ken Dyckaf1c83f2011-02-16 01:52:01 +0000588 CharUnits NonVirtualSize;
Ken Dycka2d3dda2011-02-16 01:43:15 +0000589 CharUnits NonVirtualAlignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000590
Fariborz Jahanianfc0fe6e2011-05-03 20:21:04 +0000591 FieldDecl *ZeroLengthBitfield;
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000592
Anders Carlsson35a36eb2010-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 Dunbar592a85c2010-05-27 02:25:46 +0000596
Anders Carlsson35a36eb2010-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 McCalle42a3362012-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 Friedman43114f92011-10-21 22:49:56 +0000604
Eli Friedman84d2d3a2011-09-27 19:12:27 +0000605 /// VBPtrOffset - Virtual base table offset. Only for MS layout.
606 CharUnits VBPtrOffset;
607
Anders Carlsson22f57202010-10-31 21:01:46 +0000608 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000609
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000610 /// Bases - base classes and their offsets in the record.
611 BaseOffsetsMapTy Bases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000612
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000613 // VBases - virtual base classes and their offsets in the record.
John McCalle42a3362012-05-01 08:55:32 +0000614 ASTRecordLayout::VBaseOffsetsMapTy VBases;
Anders Carlsson35a36eb2010-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 Carlsson5adde292010-11-24 22:55:48 +0000618 CXXIndirectPrimaryBaseSet IndirectPrimaryBases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000619
Anders Carlsson35a36eb2010-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 Dunbar592a85c2010-05-27 02:25:46 +0000627
Douglas Gregore9fc3772012-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 McCall0153cd32011-11-08 04:01:03 +0000643 RecordLayoutBuilder(const ASTContext &Context,
644 EmptySubobjectMap *EmptySubobjects)
Ken Dyck4731d5b2011-02-16 02:05:21 +0000645 : Context(Context), EmptySubobjects(EmptySubobjects), Size(0),
John McCall0153cd32011-11-08 04:01:03 +0000646 Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()),
Douglas Gregor44ba7892012-01-28 00:53:29 +0000647 ExternalLayout(false), InferAlignment(false),
648 Packed(false), IsUnion(false), IsMac68kAlign(false), IsMsStruct(false),
Ken Dyck02ced6f2011-02-17 01:49:42 +0000649 UnfilledBitsInLastByte(0), MaxFieldAlignment(CharUnits::Zero()),
650 DataSize(0), NonVirtualSize(CharUnits::Zero()),
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000651 NonVirtualAlignment(CharUnits::One()),
Fariborz Jahanianfc0fe6e2011-05-03 20:21:04 +0000652 ZeroLengthBitfield(0), PrimaryBase(0),
Eli Friedman43114f92011-10-21 22:49:56 +0000653 PrimaryBaseIsVirtual(false),
John McCalle42a3362012-05-01 08:55:32 +0000654 HasOwnVFPtr(false),
Eli Friedman43114f92011-10-21 22:49:56 +0000655 VBPtrOffset(CharUnits::fromQuantity(-1)),
Eli Friedman84d2d3a2011-09-27 19:12:27 +0000656 FirstNearlyEmptyVBase(0) { }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000657
John McCall0153cd32011-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 Carlsson35a36eb2010-05-26 05:41:04 +0000669 void Layout(const RecordDecl *D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000670 void Layout(const CXXRecordDecl *D);
Anders Carlsson35a36eb2010-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 Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000675 void LayoutWideBitField(uint64_t FieldSize, uint64_t TypeSize,
676 bool FieldPacked, const FieldDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000677 void LayoutBitField(const FieldDecl *D);
John McCall0153cd32011-11-08 04:01:03 +0000678
John McCall359b8852013-01-25 22:30:49 +0000679 TargetCXXABI getCXXABI() const {
680 return Context.getTargetInfo().getCXXABI();
681 }
682
John McCall0153cd32011-11-08 04:01:03 +0000683 bool isMicrosoftCXXABI() const {
John McCall359b8852013-01-25 22:30:49 +0000684 return getCXXABI().isMicrosoft();
John McCall0153cd32011-11-08 04:01:03 +0000685 }
686
Eli Friedman84d2d3a2011-09-27 19:12:27 +0000687 void MSLayoutVirtualBases(const CXXRecordDecl *RD);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000688
Anders Carlssone3c24c72010-05-29 17:35:14 +0000689 /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects.
690 llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator;
691
692 typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *>
693 BaseSubobjectInfoMapTy;
694
695 /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases
696 /// of the class we're laying out to their base subobject info.
697 BaseSubobjectInfoMapTy VirtualBaseInfo;
698
699 /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the
700 /// class we're laying out to their base subobject info.
701 BaseSubobjectInfoMapTy NonVirtualBaseInfo;
702
703 /// ComputeBaseSubobjectInfo - Compute the base subobject information for the
704 /// bases of the given class.
705 void ComputeBaseSubobjectInfo(const CXXRecordDecl *RD);
706
707 /// ComputeBaseSubobjectInfo - Compute the base subobject information for a
708 /// single class and all of its base classes.
709 BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
710 bool IsVirtual,
711 BaseSubobjectInfo *Derived);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000712
713 /// DeterminePrimaryBase - Determine the primary base of the given class.
714 void DeterminePrimaryBase(const CXXRecordDecl *RD);
715
716 void SelectPrimaryVBase(const CXXRecordDecl *RD);
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000717
Eli Friedman43114f92011-10-21 22:49:56 +0000718 void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign);
Charles Davisc2c576a2010-08-19 00:55:19 +0000719
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000720 /// LayoutNonVirtualBases - Determines the primary base class (if any) and
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000721 /// lays it out. Will then proceed to lay out all non-virtual base clasess.
722 void LayoutNonVirtualBases(const CXXRecordDecl *RD);
723
724 /// LayoutNonVirtualBase - Lays out a single non-virtual base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +0000725 void LayoutNonVirtualBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000726
Anders Carlssona2f8e412010-10-31 22:20:42 +0000727 void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
728 CharUnits Offset);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000729
John McCall0153cd32011-11-08 04:01:03 +0000730 bool needsVFTable(const CXXRecordDecl *RD) const;
John McCalle42a3362012-05-01 08:55:32 +0000731 bool hasNewVirtualFunction(const CXXRecordDecl *RD,
732 bool IgnoreDestructor = false) const;
John McCall0153cd32011-11-08 04:01:03 +0000733 bool isPossiblePrimaryBase(const CXXRecordDecl *Base) const;
Eli Friedman5e9534b2011-10-18 00:55:28 +0000734
John McCalle42a3362012-05-01 08:55:32 +0000735 void computeVtordisps(const CXXRecordDecl *RD,
736 ClassSetTy &VtordispVBases);
737
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000738 /// LayoutVirtualBases - Lays out all the virtual bases.
739 void LayoutVirtualBases(const CXXRecordDecl *RD,
740 const CXXRecordDecl *MostDerivedClass);
741
742 /// LayoutVirtualBase - Lays out a single virtual base.
John McCalle42a3362012-05-01 08:55:32 +0000743 void LayoutVirtualBase(const BaseSubobjectInfo *Base,
744 bool IsVtordispNeed = false);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000745
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000746 /// LayoutBase - Will lay out a base and return the offset where it was
Anders Carlssona2f8e412010-10-31 22:20:42 +0000747 /// placed, in chars.
748 CharUnits LayoutBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000749
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000750 /// InitializeLayout - Initialize record layout for the given record decl.
Daniel Dunbar6da10982010-05-27 05:45:51 +0000751 void InitializeLayout(const Decl *D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000752
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000753 /// FinishLayout - Finalize record layout. Adjust record size based on the
754 /// alignment.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000755 void FinishLayout(const NamedDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000756
Ken Dyck85ef0432011-02-19 18:58:07 +0000757 void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment);
758 void UpdateAlignment(CharUnits NewAlignment) {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000759 UpdateAlignment(NewAlignment, NewAlignment);
760 }
761
Douglas Gregor44ba7892012-01-28 00:53:29 +0000762 /// \brief Retrieve the externally-supplied field offset for the given
763 /// field.
764 ///
765 /// \param Field The field whose offset is being queried.
766 /// \param ComputedOffset The offset that we've computed for this field.
767 uint64_t updateExternalFieldOffset(const FieldDecl *Field,
768 uint64_t ComputedOffset);
769
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000770 void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset,
771 uint64_t UnpackedOffset, unsigned UnpackedAlign,
772 bool isPacked, const FieldDecl *D);
773
774 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000775
Ken Dyckecfc7552011-02-24 01:13:28 +0000776 CharUnits getSize() const {
Ken Dyck3c215f22011-02-24 01:33:05 +0000777 assert(Size % Context.getCharWidth() == 0);
Ken Dyckecfc7552011-02-24 01:13:28 +0000778 return Context.toCharUnitsFromBits(Size);
779 }
780 uint64_t getSizeInBits() const { return Size; }
781
782 void setSize(CharUnits NewSize) { Size = Context.toBits(NewSize); }
783 void setSize(uint64_t NewSize) { Size = NewSize; }
784
Eli Friedman84d2d3a2011-09-27 19:12:27 +0000785 CharUnits getAligment() const { return Alignment; }
786
Ken Dyckecfc7552011-02-24 01:13:28 +0000787 CharUnits getDataSize() const {
Ken Dyck3c215f22011-02-24 01:33:05 +0000788 assert(DataSize % Context.getCharWidth() == 0);
Ken Dyckecfc7552011-02-24 01:13:28 +0000789 return Context.toCharUnitsFromBits(DataSize);
790 }
791 uint64_t getDataSizeInBits() const { return DataSize; }
792
793 void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); }
794 void setDataSize(uint64_t NewSize) { DataSize = NewSize; }
795
Dmitri Gribenkoa664e5b2012-09-15 20:20:27 +0000796 RecordLayoutBuilder(const RecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
797 void operator=(const RecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000798public:
799 static const CXXMethodDecl *ComputeKeyFunction(const CXXRecordDecl *RD);
800};
Benjamin Kramerc7656cd2010-05-26 09:58:31 +0000801} // end anonymous namespace
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000802
Anders Carlsson81430692009-09-22 03:02:06 +0000803void
Anders Carlssonc2226202010-05-26 05:58:59 +0000804RecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) {
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000805 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000806 E = RD->bases_end(); I != E; ++I) {
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000807 assert(!I->getType()->isDependentType() &&
Sebastian Redl1054fae2009-10-25 17:03:50 +0000808 "Cannot layout class with dependent bases.");
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000809
Mike Stump11289f42009-09-09 15:08:12 +0000810 const CXXRecordDecl *Base =
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000811 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000812
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000813 // Check if this is a nearly empty virtual base.
Anders Carlsson60a62632010-11-25 01:51:53 +0000814 if (I->isVirtual() && Context.isNearlyEmpty(Base)) {
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000815 // If it's not an indirect primary base, then we've found our primary
816 // base.
Anders Carlsson81430692009-09-22 03:02:06 +0000817 if (!IndirectPrimaryBases.count(Base)) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000818 PrimaryBase = Base;
819 PrimaryBaseIsVirtual = true;
Mike Stump6f3793b2009-08-12 21:50:08 +0000820 return;
821 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000822
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000823 // Is this the first nearly empty virtual base?
824 if (!FirstNearlyEmptyVBase)
825 FirstNearlyEmptyVBase = Base;
Mike Stump6f3793b2009-08-12 21:50:08 +0000826 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000827
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000828 SelectPrimaryVBase(Base);
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000829 if (PrimaryBase)
Zhongxing Xuec345b72010-02-15 04:28:35 +0000830 return;
Mike Stump6f3793b2009-08-12 21:50:08 +0000831 }
832}
833
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000834/// DeterminePrimaryBase - Determine the primary base of the given class.
Anders Carlssonc2226202010-05-26 05:58:59 +0000835void RecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) {
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000836 // If the class isn't dynamic, it won't have a primary base.
837 if (!RD->isDynamicClass())
838 return;
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000839
Anders Carlsson81430692009-09-22 03:02:06 +0000840 // Compute all the primary virtual bases for all of our direct and
Mike Stump590a7c72009-08-13 23:26:06 +0000841 // indirect bases, and record all their primary virtual base classes.
Anders Carlsson5adde292010-11-24 22:55:48 +0000842 RD->getIndirectPrimaryBases(IndirectPrimaryBases);
Mike Stump590a7c72009-08-13 23:26:06 +0000843
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000844 // If the record has a dynamic base class, attempt to choose a primary base
845 // class. It is the first (in direct base class order) non-virtual dynamic
Anders Carlsson81430692009-09-22 03:02:06 +0000846 // base class, if one exists.
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000847 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000848 e = RD->bases_end(); i != e; ++i) {
Anders Carlsson03ff3792009-11-27 22:05:05 +0000849 // Ignore virtual bases.
850 if (i->isVirtual())
851 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000852
Anders Carlsson03ff3792009-11-27 22:05:05 +0000853 const CXXRecordDecl *Base =
854 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
855
John McCall0153cd32011-11-08 04:01:03 +0000856 if (isPossiblePrimaryBase(Base)) {
Anders Carlsson03ff3792009-11-27 22:05:05 +0000857 // We found it.
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000858 PrimaryBase = Base;
859 PrimaryBaseIsVirtual = false;
Anders Carlsson03ff3792009-11-27 22:05:05 +0000860 return;
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000861 }
862 }
863
Eli Friedman5e9534b2011-10-18 00:55:28 +0000864 // The Microsoft ABI doesn't have primary virtual bases.
John McCall0153cd32011-11-08 04:01:03 +0000865 if (isMicrosoftCXXABI()) {
Eli Friedman5e9534b2011-10-18 00:55:28 +0000866 assert(!PrimaryBase && "Should not get here with a primary base!");
867 return;
868 }
869
870 // Under the Itanium ABI, if there is no non-virtual primary base class,
871 // try to compute the primary virtual base. The primary virtual base is
872 // the first nearly empty virtual base that is not an indirect primary
873 // virtual base class, if one exists.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000874 if (RD->getNumVBases() != 0) {
875 SelectPrimaryVBase(RD);
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000876 if (PrimaryBase)
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000877 return;
878 }
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000879
Eli Friedman5e9534b2011-10-18 00:55:28 +0000880 // Otherwise, it is the first indirect primary base class, if one exists.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000881 if (FirstNearlyEmptyVBase) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000882 PrimaryBase = FirstNearlyEmptyVBase;
883 PrimaryBaseIsVirtual = true;
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000884 return;
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000885 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000886
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000887 assert(!PrimaryBase && "Should not get here with a primary base!");
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000888}
889
Anders Carlssone3c24c72010-05-29 17:35:14 +0000890BaseSubobjectInfo *
891RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
892 bool IsVirtual,
893 BaseSubobjectInfo *Derived) {
894 BaseSubobjectInfo *Info;
895
896 if (IsVirtual) {
897 // Check if we already have info about this virtual base.
898 BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD];
899 if (InfoSlot) {
900 assert(InfoSlot->Class == RD && "Wrong class for virtual base info!");
901 return InfoSlot;
902 }
903
904 // We don't, create it.
905 InfoSlot = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
906 Info = InfoSlot;
907 } else {
908 Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
909 }
910
911 Info->Class = RD;
912 Info->IsVirtual = IsVirtual;
913 Info->Derived = 0;
914 Info->PrimaryVirtualBaseInfo = 0;
915
916 const CXXRecordDecl *PrimaryVirtualBase = 0;
917 BaseSubobjectInfo *PrimaryVirtualBaseInfo = 0;
918
919 // Check if this base has a primary virtual base.
920 if (RD->getNumVBases()) {
921 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlsson7f95cd12010-11-24 23:12:57 +0000922 if (Layout.isPrimaryBaseVirtual()) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000923 // This base does have a primary virtual base.
924 PrimaryVirtualBase = Layout.getPrimaryBase();
925 assert(PrimaryVirtualBase && "Didn't have a primary virtual base!");
926
927 // Now check if we have base subobject info about this primary base.
928 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
929
930 if (PrimaryVirtualBaseInfo) {
931 if (PrimaryVirtualBaseInfo->Derived) {
932 // We did have info about this primary base, and it turns out that it
933 // has already been claimed as a primary virtual base for another
934 // base.
935 PrimaryVirtualBase = 0;
936 } else {
937 // We can claim this base as our primary base.
938 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
939 PrimaryVirtualBaseInfo->Derived = Info;
940 }
941 }
942 }
943 }
944
945 // Now go through all direct bases.
946 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
947 E = RD->bases_end(); I != E; ++I) {
948 bool IsVirtual = I->isVirtual();
949
950 const CXXRecordDecl *BaseDecl =
951 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
952
953 Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info));
954 }
955
956 if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) {
957 // Traversing the bases must have created the base info for our primary
958 // virtual base.
959 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
960 assert(PrimaryVirtualBaseInfo &&
961 "Did not create a primary virtual base!");
962
963 // Claim the primary virtual base as our primary virtual base.
964 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
965 PrimaryVirtualBaseInfo->Derived = Info;
966 }
967
968 return Info;
969}
970
971void RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD) {
972 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
973 E = RD->bases_end(); I != E; ++I) {
974 bool IsVirtual = I->isVirtual();
975
976 const CXXRecordDecl *BaseDecl =
977 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
978
979 // Compute the base subobject info for this base.
980 BaseSubobjectInfo *Info = ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, 0);
981
982 if (IsVirtual) {
983 // ComputeBaseInfo has already added this base for us.
984 assert(VirtualBaseInfo.count(BaseDecl) &&
985 "Did not add virtual base!");
986 } else {
987 // Add the base info to the map of non-virtual bases.
988 assert(!NonVirtualBaseInfo.count(BaseDecl) &&
989 "Non-virtual base already exists!");
990 NonVirtualBaseInfo.insert(std::make_pair(BaseDecl, Info));
991 }
992 }
993}
994
Anders Carlsson09ffa322010-03-10 22:21:28 +0000995void
Eli Friedman43114f92011-10-21 22:49:56 +0000996RecordLayoutBuilder::EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign) {
Eli Friedman5e9534b2011-10-18 00:55:28 +0000997 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
998
999 // The maximum field alignment overrides base align.
1000 if (!MaxFieldAlignment.isZero()) {
1001 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1002 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
1003 }
1004
1005 // Round up the current record size to pointer alignment.
Eli Friedman43114f92011-10-21 22:49:56 +00001006 setSize(getSize().RoundUpToAlignment(BaseAlign));
1007 setDataSize(getSize());
Eli Friedman5e9534b2011-10-18 00:55:28 +00001008
1009 // Update the alignment.
1010 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
1011}
1012
1013void
Anders Carlssonc2226202010-05-26 05:58:59 +00001014RecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl *RD) {
Anders Carlssone3c24c72010-05-29 17:35:14 +00001015 // Then, determine the primary base class.
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001016 DeterminePrimaryBase(RD);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001017
Anders Carlssone3c24c72010-05-29 17:35:14 +00001018 // Compute base subobject info.
1019 ComputeBaseSubobjectInfo(RD);
1020
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001021 // If we have a primary base class, lay it out.
Anders Carlssond20e7cd2010-05-26 05:20:58 +00001022 if (PrimaryBase) {
1023 if (PrimaryBaseIsVirtual) {
Anders Carlssone3c24c72010-05-29 17:35:14 +00001024 // If the primary virtual base was a primary virtual base of some other
1025 // base class we'll have to steal it.
1026 BaseSubobjectInfo *PrimaryBaseInfo = VirtualBaseInfo.lookup(PrimaryBase);
1027 PrimaryBaseInfo->Derived = 0;
1028
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001029 // We have a virtual primary base, insert it as an indirect primary base.
Anders Carlssond20e7cd2010-05-26 05:20:58 +00001030 IndirectPrimaryBases.insert(PrimaryBase);
Anders Carlssonfe900962010-03-11 05:42:17 +00001031
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001032 assert(!VisitedVirtualBases.count(PrimaryBase) &&
Anders Carlssond20e7cd2010-05-26 05:20:58 +00001033 "vbase already visited!");
1034 VisitedVirtualBases.insert(PrimaryBase);
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001035
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001036 LayoutVirtualBase(PrimaryBaseInfo);
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001037 } else {
1038 BaseSubobjectInfo *PrimaryBaseInfo =
1039 NonVirtualBaseInfo.lookup(PrimaryBase);
1040 assert(PrimaryBaseInfo &&
1041 "Did not find base info for non-virtual primary base!");
1042
1043 LayoutNonVirtualBase(PrimaryBaseInfo);
1044 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001045
John McCall0153cd32011-11-08 04:01:03 +00001046 // If this class needs a vtable/vf-table and didn't get one from a
1047 // primary base, add it in now.
1048 } else if (needsVFTable(RD)) {
Eli Friedman5e9534b2011-10-18 00:55:28 +00001049 assert(DataSize == 0 && "Vtable pointer must be at offset zero!");
Eli Friedman5e9534b2011-10-18 00:55:28 +00001050 CharUnits PtrWidth =
1051 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Eli Friedman43114f92011-10-21 22:49:56 +00001052 CharUnits PtrAlign =
1053 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
1054 EnsureVTablePointerAlignment(PtrAlign);
John McCalle42a3362012-05-01 08:55:32 +00001055 HasOwnVFPtr = true;
Eli Friedman5e9534b2011-10-18 00:55:28 +00001056 setSize(getSize() + PtrWidth);
1057 setDataSize(getSize());
1058 }
1059
John McCall0153cd32011-11-08 04:01:03 +00001060 bool HasDirectVirtualBases = false;
1061 bool HasNonVirtualBaseWithVBTable = false;
1062
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001063 // Now lay out the non-virtual bases.
1064 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001065 E = RD->bases_end(); I != E; ++I) {
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001066
John McCall0153cd32011-11-08 04:01:03 +00001067 // Ignore virtual bases, but remember that we saw one.
1068 if (I->isVirtual()) {
1069 HasDirectVirtualBases = true;
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001070 continue;
John McCall0153cd32011-11-08 04:01:03 +00001071 }
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001072
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001073 const CXXRecordDecl *BaseDecl =
John McCall0153cd32011-11-08 04:01:03 +00001074 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001075
John McCall0153cd32011-11-08 04:01:03 +00001076 // Remember if this base has virtual bases itself.
1077 if (BaseDecl->getNumVBases())
1078 HasNonVirtualBaseWithVBTable = true;
1079
1080 // Skip the primary base, because we've already laid it out. The
1081 // !PrimaryBaseIsVirtual check is required because we might have a
1082 // non-virtual base of the same type as a primary virtual base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001083 if (BaseDecl == PrimaryBase && !PrimaryBaseIsVirtual)
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001084 continue;
1085
1086 // Lay out the base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001087 BaseSubobjectInfo *BaseInfo = NonVirtualBaseInfo.lookup(BaseDecl);
1088 assert(BaseInfo && "Did not find base info for non-virtual base!");
1089
1090 LayoutNonVirtualBase(BaseInfo);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001091 }
Eli Friedman5e9534b2011-10-18 00:55:28 +00001092
John McCall0153cd32011-11-08 04:01:03 +00001093 // In the MS ABI, add the vb-table pointer if we need one, which is
1094 // whenever we have a virtual base and we can't re-use a vb-table
1095 // pointer from a non-virtual base.
1096 if (isMicrosoftCXXABI() &&
1097 HasDirectVirtualBases && !HasNonVirtualBaseWithVBTable) {
Eli Friedman5e9534b2011-10-18 00:55:28 +00001098 CharUnits PtrWidth =
1099 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Eli Friedman43114f92011-10-21 22:49:56 +00001100 CharUnits PtrAlign =
1101 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
John McCall0153cd32011-11-08 04:01:03 +00001102
1103 // MSVC potentially over-aligns the vb-table pointer by giving it
1104 // the max alignment of all the non-virtual objects in the class.
1105 // This is completely unnecessary, but we're not here to pass
1106 // judgment.
1107 //
1108 // Note that we've only laid out the non-virtual bases, so on the
1109 // first pass Alignment won't be set correctly here, but if the
1110 // vb-table doesn't end up aligned correctly we'll come through
1111 // and redo the layout from scratch with the right alignment.
1112 //
1113 // TODO: Instead of doing this, just lay out the fields as if the
1114 // vb-table were at offset zero, then retroactively bump the field
1115 // offsets up.
Eli Friedman43114f92011-10-21 22:49:56 +00001116 PtrAlign = std::max(PtrAlign, Alignment);
John McCall0153cd32011-11-08 04:01:03 +00001117
1118 EnsureVTablePointerAlignment(PtrAlign);
1119 VBPtrOffset = getSize();
1120 setSize(getSize() + PtrWidth);
1121 setDataSize(getSize());
Eli Friedman5e9534b2011-10-18 00:55:28 +00001122 }
Anders Carlsson09ffa322010-03-10 22:21:28 +00001123}
1124
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001125void RecordLayoutBuilder::LayoutNonVirtualBase(const BaseSubobjectInfo *Base) {
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001126 // Layout the base.
Anders Carlssona2f8e412010-10-31 22:20:42 +00001127 CharUnits Offset = LayoutBase(Base);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001128
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001129 // Add its base class offset.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001130 assert(!Bases.count(Base->Class) && "base offset already exists!");
Anders Carlssona2f8e412010-10-31 22:20:42 +00001131 Bases.insert(std::make_pair(Base->Class, Offset));
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001132
1133 AddPrimaryVirtualBaseOffsets(Base, Offset);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001134}
Mike Stump2b84dd32009-11-05 04:02:15 +00001135
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001136void
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001137RecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
Anders Carlssona2f8e412010-10-31 22:20:42 +00001138 CharUnits Offset) {
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001139 // This base isn't interesting, it has no virtual bases.
1140 if (!Info->Class->getNumVBases())
1141 return;
1142
1143 // First, check if we have a virtual primary base to add offsets for.
1144 if (Info->PrimaryVirtualBaseInfo) {
1145 assert(Info->PrimaryVirtualBaseInfo->IsVirtual &&
1146 "Primary virtual base is not virtual!");
1147 if (Info->PrimaryVirtualBaseInfo->Derived == Info) {
1148 // Add the offset.
1149 assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) &&
1150 "primary vbase offset already exists!");
1151 VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class,
John McCalle42a3362012-05-01 08:55:32 +00001152 ASTRecordLayout::VBaseInfo(Offset, false)));
Anders Carlssonea7b1822010-04-15 16:12:58 +00001153
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001154 // Traverse the primary virtual base.
1155 AddPrimaryVirtualBaseOffsets(Info->PrimaryVirtualBaseInfo, Offset);
1156 }
Anders Carlssonea7b1822010-04-15 16:12:58 +00001157 }
1158
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001159 // Now go through all direct non-virtual bases.
1160 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
1161 for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
1162 const BaseSubobjectInfo *Base = Info->Bases[I];
1163 if (Base->IsVirtual)
Anders Carlssonea7b1822010-04-15 16:12:58 +00001164 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001165
Anders Carlsson0a14ee92010-11-01 00:21:58 +00001166 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001167 AddPrimaryVirtualBaseOffsets(Base, BaseOffset);
Anders Carlssonea7b1822010-04-15 16:12:58 +00001168 }
1169}
1170
John McCall0153cd32011-11-08 04:01:03 +00001171/// needsVFTable - Return true if this class needs a vtable or vf-table
1172/// when laid out as a base class. These are treated the same because
1173/// they're both always laid out at offset zero.
1174///
1175/// This function assumes that the class has no primary base.
1176bool RecordLayoutBuilder::needsVFTable(const CXXRecordDecl *RD) const {
1177 assert(!PrimaryBase);
1178
1179 // In the Itanium ABI, every dynamic class needs a vtable: even if
1180 // this class has no virtual functions as a base class (i.e. it's
1181 // non-polymorphic or only has virtual functions from virtual
1182 // bases),x it still needs a vtable to locate its virtual bases.
1183 if (!isMicrosoftCXXABI())
1184 return RD->isDynamicClass();
1185
1186 // In the MS ABI, we need a vfptr if the class has virtual functions
1187 // other than those declared by its virtual bases. The AST doesn't
1188 // tell us that directly, and checking manually for virtual
1189 // functions that aren't overrides is expensive, but there are
1190 // some important shortcuts:
1191
1192 // - Non-polymorphic classes have no virtual functions at all.
1193 if (!RD->isPolymorphic()) return false;
1194
1195 // - Polymorphic classes with no virtual bases must either declare
1196 // virtual functions directly or inherit them, but in the latter
1197 // case we would have a primary base.
1198 if (RD->getNumVBases() == 0) return true;
1199
1200 return hasNewVirtualFunction(RD);
1201}
1202
John McCalle42a3362012-05-01 08:55:32 +00001203/// Does the given class inherit non-virtually from any of the classes
1204/// in the given set?
1205static bool hasNonVirtualBaseInSet(const CXXRecordDecl *RD,
1206 const ClassSetTy &set) {
1207 for (CXXRecordDecl::base_class_const_iterator
1208 I = RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
1209 // Ignore virtual links.
1210 if (I->isVirtual()) continue;
1211
1212 // Check whether the set contains the base.
1213 const CXXRecordDecl *base = I->getType()->getAsCXXRecordDecl();
1214 if (set.count(base))
1215 return true;
1216
1217 // Otherwise, recurse and propagate.
1218 if (hasNonVirtualBaseInSet(base, set))
1219 return true;
1220 }
1221
1222 return false;
1223}
1224
1225/// Does the given method (B::foo()) already override a method (A::foo())
1226/// such that A requires a vtordisp in B? If so, we don't need to add a
1227/// new vtordisp for B in a yet-more-derived class C providing C::foo().
1228static bool overridesMethodRequiringVtorDisp(const ASTContext &Context,
1229 const CXXMethodDecl *M) {
1230 CXXMethodDecl::method_iterator
1231 I = M->begin_overridden_methods(), E = M->end_overridden_methods();
1232 if (I == E) return false;
1233
1234 const ASTRecordLayout::VBaseOffsetsMapTy &offsets =
1235 Context.getASTRecordLayout(M->getParent()).getVBaseOffsetsMap();
1236 do {
1237 const CXXMethodDecl *overridden = *I;
1238
1239 // If the overridden method's class isn't recognized as a virtual
1240 // base in the derived class, ignore it.
1241 ASTRecordLayout::VBaseOffsetsMapTy::const_iterator
1242 it = offsets.find(overridden->getParent());
1243 if (it == offsets.end()) continue;
1244
1245 // Otherwise, check if the overridden method's class needs a vtordisp.
1246 if (it->second.hasVtorDisp()) return true;
1247
1248 } while (++I != E);
1249 return false;
1250}
1251
1252/// In the Microsoft ABI, decide which of the virtual bases require a
1253/// vtordisp field.
1254void RecordLayoutBuilder::computeVtordisps(const CXXRecordDecl *RD,
1255 ClassSetTy &vtordispVBases) {
1256 // Bail out if we have no virtual bases.
1257 assert(RD->getNumVBases());
1258
1259 // Build up the set of virtual bases that we haven't decided yet.
1260 ClassSetTy undecidedVBases;
1261 for (CXXRecordDecl::base_class_const_iterator
1262 I = RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
1263 const CXXRecordDecl *vbase = I->getType()->getAsCXXRecordDecl();
1264 undecidedVBases.insert(vbase);
1265 }
1266 assert(!undecidedVBases.empty());
1267
1268 // A virtual base requires a vtordisp field in a derived class if it
1269 // requires a vtordisp field in a base class. Walk all the direct
1270 // bases and collect this information.
1271 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1272 E = RD->bases_end(); I != E; ++I) {
1273 const CXXRecordDecl *base = I->getType()->getAsCXXRecordDecl();
1274 const ASTRecordLayout &baseLayout = Context.getASTRecordLayout(base);
1275
1276 // Iterate over the set of virtual bases provided by this class.
1277 for (ASTRecordLayout::VBaseOffsetsMapTy::const_iterator
1278 VI = baseLayout.getVBaseOffsetsMap().begin(),
1279 VE = baseLayout.getVBaseOffsetsMap().end(); VI != VE; ++VI) {
1280 // If it doesn't need a vtordisp in this base, ignore it.
1281 if (!VI->second.hasVtorDisp()) continue;
1282
1283 // If we've already seen it and decided it needs a vtordisp, ignore it.
1284 if (!undecidedVBases.erase(VI->first))
1285 continue;
1286
1287 // Add it.
1288 vtordispVBases.insert(VI->first);
1289
1290 // Quit as soon as we've decided everything.
1291 if (undecidedVBases.empty())
1292 return;
1293 }
1294 }
1295
1296 // Okay, we have virtual bases that we haven't yet decided about. A
1297 // virtual base requires a vtordisp if any the non-destructor
1298 // virtual methods declared in this class directly override a method
1299 // provided by that virtual base. (If so, we need to emit a thunk
1300 // for that method, to be used in the construction vftable, which
1301 // applies an additional 'vtordisp' this-adjustment.)
1302
1303 // Collect the set of bases directly overridden by any method in this class.
1304 // It's possible that some of these classes won't be virtual bases, or won't be
1305 // provided by virtual bases, or won't be virtual bases in the overridden
1306 // instance but are virtual bases elsewhere. Only the last matters for what
1307 // we're doing, and we can ignore those: if we don't directly override
1308 // a method provided by a virtual copy of a base class, but we do directly
1309 // override a method provided by a non-virtual copy of that base class,
1310 // then we must indirectly override the method provided by the virtual base,
1311 // and so we should already have collected it in the loop above.
1312 ClassSetTy overriddenBases;
1313 for (CXXRecordDecl::method_iterator
1314 M = RD->method_begin(), E = RD->method_end(); M != E; ++M) {
1315 // Ignore non-virtual methods and destructors.
1316 if (isa<CXXDestructorDecl>(*M) || !M->isVirtual())
1317 continue;
1318
1319 for (CXXMethodDecl::method_iterator I = M->begin_overridden_methods(),
1320 E = M->end_overridden_methods(); I != E; ++I) {
1321 const CXXMethodDecl *overriddenMethod = (*I);
1322
1323 // Ignore methods that override methods from vbases that require
1324 // require vtordisps.
1325 if (overridesMethodRequiringVtorDisp(Context, overriddenMethod))
1326 continue;
1327
1328 // As an optimization, check immediately whether we're overriding
1329 // something from the undecided set.
1330 const CXXRecordDecl *overriddenBase = overriddenMethod->getParent();
1331 if (undecidedVBases.erase(overriddenBase)) {
1332 vtordispVBases.insert(overriddenBase);
1333 if (undecidedVBases.empty()) return;
1334
1335 // We can't 'continue;' here because one of our undecided
1336 // vbases might non-virtually inherit from this base.
1337 // Consider:
1338 // struct A { virtual void foo(); };
1339 // struct B : A {};
1340 // struct C : virtual A, virtual B { virtual void foo(); };
1341 // We need a vtordisp for B here.
1342 }
1343
1344 // Otherwise, just collect it.
1345 overriddenBases.insert(overriddenBase);
1346 }
1347 }
1348
1349 // Walk the undecided v-bases and check whether they (non-virtually)
1350 // provide any of the overridden bases. We don't need to consider
1351 // virtual links because the vtordisp inheres to the layout
1352 // subobject containing the base.
1353 for (ClassSetTy::const_iterator
1354 I = undecidedVBases.begin(), E = undecidedVBases.end(); I != E; ++I) {
1355 if (hasNonVirtualBaseInSet(*I, overriddenBases))
1356 vtordispVBases.insert(*I);
1357 }
1358}
1359
John McCall0153cd32011-11-08 04:01:03 +00001360/// hasNewVirtualFunction - Does the given polymorphic class declare a
1361/// virtual function that does not override a method from any of its
1362/// base classes?
Eli Friedman84d2d3a2011-09-27 19:12:27 +00001363bool
John McCalle42a3362012-05-01 08:55:32 +00001364RecordLayoutBuilder::hasNewVirtualFunction(const CXXRecordDecl *RD,
1365 bool IgnoreDestructor) const {
John McCall0153cd32011-11-08 04:01:03 +00001366 if (!RD->getNumBases())
1367 return true;
1368
Eli Friedman84d2d3a2011-09-27 19:12:27 +00001369 for (CXXRecordDecl::method_iterator method = RD->method_begin();
1370 method != RD->method_end();
1371 ++method) {
John McCalle42a3362012-05-01 08:55:32 +00001372 if (method->isVirtual() && !method->size_overridden_methods() &&
1373 !(IgnoreDestructor && method->getKind() == Decl::CXXDestructor)) {
Eli Friedman84d2d3a2011-09-27 19:12:27 +00001374 return true;
1375 }
1376 }
1377 return false;
1378}
1379
John McCall0153cd32011-11-08 04:01:03 +00001380/// isPossiblePrimaryBase - Is the given base class an acceptable
1381/// primary base class?
Eli Friedman5e9534b2011-10-18 00:55:28 +00001382bool
John McCalle42a3362012-05-01 08:55:32 +00001383RecordLayoutBuilder::isPossiblePrimaryBase(const CXXRecordDecl *base) const {
John McCall0153cd32011-11-08 04:01:03 +00001384 // In the Itanium ABI, a class can be a primary base class if it has
1385 // a vtable for any reason.
1386 if (!isMicrosoftCXXABI())
John McCalle42a3362012-05-01 08:55:32 +00001387 return base->isDynamicClass();
John McCall0153cd32011-11-08 04:01:03 +00001388
1389 // In the MS ABI, a class can only be a primary base class if it
1390 // provides a vf-table at a static offset. That means it has to be
1391 // non-virtual base. The existence of a separate vb-table means
1392 // that it's possible to get virtual functions only from a virtual
1393 // base, which we have to guard against.
1394
1395 // First off, it has to have virtual functions.
John McCalle42a3362012-05-01 08:55:32 +00001396 if (!base->isPolymorphic()) return false;
John McCall0153cd32011-11-08 04:01:03 +00001397
John McCalle42a3362012-05-01 08:55:32 +00001398 // If it has no virtual bases, then the vfptr must be at a static offset.
1399 if (!base->getNumVBases()) return true;
1400
1401 // Otherwise, the necessary information is cached in the layout.
1402 const ASTRecordLayout &layout = Context.getASTRecordLayout(base);
John McCall0153cd32011-11-08 04:01:03 +00001403
John McCalle42a3362012-05-01 08:55:32 +00001404 // If the base has its own vfptr, it can be a primary base.
1405 if (layout.hasOwnVFPtr()) return true;
1406
1407 // If the base has a primary base class, then it can be a primary base.
1408 if (layout.getPrimaryBase()) return true;
1409
1410 // Otherwise it can't.
1411 return false;
Eli Friedman84d2d3a2011-09-27 19:12:27 +00001412}
1413
Anders Carlssonea7b1822010-04-15 16:12:58 +00001414void
Anders Carlssonc2226202010-05-26 05:58:59 +00001415RecordLayoutBuilder::LayoutVirtualBases(const CXXRecordDecl *RD,
Anders Carlssonea7b1822010-04-15 16:12:58 +00001416 const CXXRecordDecl *MostDerivedClass) {
Anders Carlssonde710c92010-03-11 04:33:54 +00001417 const CXXRecordDecl *PrimaryBase;
Anders Carlsson291279e2010-04-10 18:42:27 +00001418 bool PrimaryBaseIsVirtual;
Anders Carlssonfe900962010-03-11 05:42:17 +00001419
Anders Carlsson291279e2010-04-10 18:42:27 +00001420 if (MostDerivedClass == RD) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +00001421 PrimaryBase = this->PrimaryBase;
1422 PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual;
Anders Carlsson291279e2010-04-10 18:42:27 +00001423 } else {
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001424 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlssonde710c92010-03-11 04:33:54 +00001425 PrimaryBase = Layout.getPrimaryBase();
Anders Carlsson7f95cd12010-11-24 23:12:57 +00001426 PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
Anders Carlsson291279e2010-04-10 18:42:27 +00001427 }
1428
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001429 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1430 E = RD->bases_end(); I != E; ++I) {
1431 assert(!I->getType()->isDependentType() &&
Sebastian Redl1054fae2009-10-25 17:03:50 +00001432 "Cannot layout class with dependent bases.");
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001433
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001434 const CXXRecordDecl *BaseDecl =
John McCall0153cd32011-11-08 04:01:03 +00001435 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001436
1437 if (I->isVirtual()) {
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001438 if (PrimaryBase != BaseDecl || !PrimaryBaseIsVirtual) {
1439 bool IndirectPrimaryBase = IndirectPrimaryBases.count(BaseDecl);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001440
Anders Carlsson291279e2010-04-10 18:42:27 +00001441 // Only lay out the virtual base if it's not an indirect primary base.
1442 if (!IndirectPrimaryBase) {
1443 // Only visit virtual bases once.
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001444 if (!VisitedVirtualBases.insert(BaseDecl))
Anders Carlsson291279e2010-04-10 18:42:27 +00001445 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001446
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001447 const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1448 assert(BaseInfo && "Did not find virtual base info!");
1449 LayoutVirtualBase(BaseInfo);
Anders Carlsson6a848892010-03-11 04:10:39 +00001450 }
Mike Stump2b84dd32009-11-05 04:02:15 +00001451 }
Mike Stumpc2f591b2009-08-13 22:53:07 +00001452 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001453
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001454 if (!BaseDecl->getNumVBases()) {
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001455 // This base isn't interesting since it doesn't have any virtual bases.
1456 continue;
Mike Stump996576f32009-08-16 19:04:13 +00001457 }
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001458
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001459 LayoutVirtualBases(BaseDecl, MostDerivedClass);
Mike Stump6b2556f2009-08-06 13:41:24 +00001460 }
1461}
1462
John McCall0153cd32011-11-08 04:01:03 +00001463void RecordLayoutBuilder::MSLayoutVirtualBases(const CXXRecordDecl *RD) {
John McCall0153cd32011-11-08 04:01:03 +00001464 if (!RD->getNumVBases())
1465 return;
1466
John McCalle42a3362012-05-01 08:55:32 +00001467 ClassSetTy VtordispVBases;
1468 computeVtordisps(RD, VtordispVBases);
1469
John McCall0153cd32011-11-08 04:01:03 +00001470 // This is substantially simplified because there are no virtual
1471 // primary bases.
1472 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
1473 E = RD->vbases_end(); I != E; ++I) {
1474 const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
1475 const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1476 assert(BaseInfo && "Did not find virtual base info!");
John McCalle42a3362012-05-01 08:55:32 +00001477
1478 // If this base requires a vtordisp, add enough space for an int field.
1479 // This is apparently always 32-bits, even on x64.
1480 bool vtordispNeeded = false;
1481 if (VtordispVBases.count(BaseDecl)) {
1482 CharUnits IntSize =
1483 CharUnits::fromQuantity(Context.getTargetInfo().getIntWidth() / 8);
1484
1485 setSize(getSize() + IntSize);
1486 setDataSize(getSize());
1487 vtordispNeeded = true;
1488 }
1489
1490 LayoutVirtualBase(BaseInfo, vtordispNeeded);
John McCall0153cd32011-11-08 04:01:03 +00001491 }
1492}
1493
John McCalle42a3362012-05-01 08:55:32 +00001494void RecordLayoutBuilder::LayoutVirtualBase(const BaseSubobjectInfo *Base,
1495 bool IsVtordispNeed) {
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001496 assert(!Base->Derived && "Trying to lay out a primary virtual base!");
1497
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001498 // Layout the base.
Anders Carlssona2f8e412010-10-31 22:20:42 +00001499 CharUnits Offset = LayoutBase(Base);
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001500
1501 // Add its base class offset.
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001502 assert(!VBases.count(Base->Class) && "vbase offset already exists!");
John McCalle42a3362012-05-01 08:55:32 +00001503 VBases.insert(std::make_pair(Base->Class,
1504 ASTRecordLayout::VBaseInfo(Offset, IsVtordispNeed)));
1505
1506 if (!isMicrosoftCXXABI())
1507 AddPrimaryVirtualBaseOffsets(Base, Offset);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001508}
1509
Anders Carlssona2f8e412010-10-31 22:20:42 +00001510CharUnits RecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) {
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001511 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001512
Douglas Gregore9fc3772012-01-26 07:55:45 +00001513
1514 CharUnits Offset;
1515
1516 // Query the external layout to see if it provides an offset.
1517 bool HasExternalLayout = false;
1518 if (ExternalLayout) {
1519 llvm::DenseMap<const CXXRecordDecl *, CharUnits>::iterator Known;
1520 if (Base->IsVirtual) {
1521 Known = ExternalVirtualBaseOffsets.find(Base->Class);
1522 if (Known != ExternalVirtualBaseOffsets.end()) {
1523 Offset = Known->second;
1524 HasExternalLayout = true;
1525 }
1526 } else {
1527 Known = ExternalBaseOffsets.find(Base->Class);
1528 if (Known != ExternalBaseOffsets.end()) {
1529 Offset = Known->second;
1530 HasExternalLayout = true;
1531 }
1532 }
1533 }
1534
Anders Carlsson09ffa322010-03-10 22:21:28 +00001535 // If we have an empty base class, try to place it at offset 0.
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001536 if (Base->Class->isEmpty() &&
Douglas Gregore9fc3772012-01-26 07:55:45 +00001537 (!HasExternalLayout || Offset == CharUnits::Zero()) &&
Anders Carlsson28466ab2010-10-31 22:13:23 +00001538 EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) {
Ken Dyck1b4420e2011-02-28 02:01:38 +00001539 setSize(std::max(getSize(), Layout.getSize()));
Anders Carlsson09ffa322010-03-10 22:21:28 +00001540
Anders Carlssona2f8e412010-10-31 22:20:42 +00001541 return CharUnits::Zero();
Anders Carlsson09ffa322010-03-10 22:21:28 +00001542 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001543
Ken Dyck85ef0432011-02-19 18:58:07 +00001544 CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlign();
1545 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001546
1547 // The maximum field alignment overrides base align.
Ken Dyck02ced6f2011-02-17 01:49:42 +00001548 if (!MaxFieldAlignment.isZero()) {
Ken Dyck85ef0432011-02-19 18:58:07 +00001549 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1550 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001551 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001552
Douglas Gregore9fc3772012-01-26 07:55:45 +00001553 if (!HasExternalLayout) {
1554 // Round up the current record size to the base's alignment boundary.
1555 Offset = getDataSize().RoundUpToAlignment(BaseAlign);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001556
Douglas Gregore9fc3772012-01-26 07:55:45 +00001557 // Try to place the base.
1558 while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset))
1559 Offset += BaseAlign;
1560 } else {
1561 bool Allowed = EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset);
1562 (void)Allowed;
1563 assert(Allowed && "Base subobject externally placed at overlapping offset");
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001564
1565 if (InferAlignment && Offset < getDataSize().RoundUpToAlignment(BaseAlign)){
1566 // The externally-supplied base offset is before the base offset we
1567 // computed. Assume that the structure is packed.
1568 Alignment = CharUnits::One();
1569 InferAlignment = false;
1570 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001571 }
1572
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001573 if (!Base->Class->isEmpty()) {
Anders Carlsson09ffa322010-03-10 22:21:28 +00001574 // Update the data size.
Ken Dyck1b4420e2011-02-28 02:01:38 +00001575 setDataSize(Offset + Layout.getNonVirtualSize());
Anders Carlsson09ffa322010-03-10 22:21:28 +00001576
Ken Dyck1b4420e2011-02-28 02:01:38 +00001577 setSize(std::max(getSize(), getDataSize()));
Anders Carlsson09ffa322010-03-10 22:21:28 +00001578 } else
Ken Dyck1b4420e2011-02-28 02:01:38 +00001579 setSize(std::max(getSize(), Offset + Layout.getSize()));
Anders Carlsson09ffa322010-03-10 22:21:28 +00001580
1581 // Remember max struct/class alignment.
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001582 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001583
Ken Dyck1b4420e2011-02-28 02:01:38 +00001584 return Offset;
Anders Carlsson09ffa322010-03-10 22:21:28 +00001585}
1586
Daniel Dunbar6da10982010-05-27 05:45:51 +00001587void RecordLayoutBuilder::InitializeLayout(const Decl *D) {
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001588 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Daniel Dunbar6da10982010-05-27 05:45:51 +00001589 IsUnion = RD->isUnion();
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001590 IsMsStruct = RD->isMsStruct(Context);
1591 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001592
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001593 Packed = D->hasAttr<PackedAttr>();
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001594
Daniel Dunbar096ed292011-10-05 21:04:55 +00001595 // Honor the default struct packing maximum alignment flag.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001596 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) {
Daniel Dunbar096ed292011-10-05 21:04:55 +00001597 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
1598 }
1599
Daniel Dunbar6da10982010-05-27 05:45:51 +00001600 // mac68k alignment supersedes maximum field alignment and attribute aligned,
1601 // and forces all structures to have 2-byte alignment. The IBM docs on it
1602 // allude to additional (more complicated) semantics, especially with regard
1603 // to bit-fields, but gcc appears not to follow that.
1604 if (D->hasAttr<AlignMac68kAttr>()) {
1605 IsMac68kAlign = true;
Ken Dyck02ced6f2011-02-17 01:49:42 +00001606 MaxFieldAlignment = CharUnits::fromQuantity(2);
Ken Dyck4731d5b2011-02-16 02:05:21 +00001607 Alignment = CharUnits::fromQuantity(2);
Daniel Dunbar6da10982010-05-27 05:45:51 +00001608 } else {
1609 if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>())
Ken Dyck02ced6f2011-02-17 01:49:42 +00001610 MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001611
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001612 if (unsigned MaxAlign = D->getMaxAlignment())
Ken Dyck85ef0432011-02-19 18:58:07 +00001613 UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign));
Daniel Dunbar6da10982010-05-27 05:45:51 +00001614 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001615
1616 // If there is an external AST source, ask it for the various offsets.
1617 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
1618 if (ExternalASTSource *External = Context.getExternalSource()) {
1619 ExternalLayout = External->layoutRecordType(RD,
1620 ExternalSize,
1621 ExternalAlign,
1622 ExternalFieldOffsets,
1623 ExternalBaseOffsets,
1624 ExternalVirtualBaseOffsets);
1625
1626 // Update based on external alignment.
1627 if (ExternalLayout) {
Douglas Gregor44ba7892012-01-28 00:53:29 +00001628 if (ExternalAlign > 0) {
1629 Alignment = Context.toCharUnitsFromBits(ExternalAlign);
Douglas Gregor44ba7892012-01-28 00:53:29 +00001630 } else {
1631 // The external source didn't have alignment information; infer it.
1632 InferAlignment = true;
1633 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001634 }
1635 }
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001636}
Anders Carlsson6d9f6f32009-07-19 00:18:47 +00001637
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001638void RecordLayoutBuilder::Layout(const RecordDecl *D) {
1639 InitializeLayout(D);
Anders Carlsson118ce162009-07-18 21:48:39 +00001640 LayoutFields(D);
Mike Stump11289f42009-09-09 15:08:12 +00001641
Anders Carlsson79474332009-07-18 20:20:21 +00001642 // Finally, round the size of the total struct up to the alignment of the
1643 // struct itself.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001644 FinishLayout(D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001645}
1646
1647void RecordLayoutBuilder::Layout(const CXXRecordDecl *RD) {
1648 InitializeLayout(RD);
1649
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001650 // Lay out the vtable and the non-virtual bases.
1651 LayoutNonVirtualBases(RD);
1652
1653 LayoutFields(RD);
1654
Ken Dycke7380752011-03-10 01:53:59 +00001655 NonVirtualSize = Context.toCharUnitsFromBits(
1656 llvm::RoundUpToAlignment(getSizeInBits(),
Douglas Gregore8bbc122011-09-02 00:18:52 +00001657 Context.getTargetInfo().getCharAlign()));
Ken Dyck4731d5b2011-02-16 02:05:21 +00001658 NonVirtualAlignment = Alignment;
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001659
John McCalle42a3362012-05-01 08:55:32 +00001660 if (isMicrosoftCXXABI()) {
1661 if (NonVirtualSize != NonVirtualSize.RoundUpToAlignment(Alignment)) {
John McCall0153cd32011-11-08 04:01:03 +00001662 CharUnits AlignMember =
1663 NonVirtualSize.RoundUpToAlignment(Alignment) - NonVirtualSize;
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001664
John McCall0153cd32011-11-08 04:01:03 +00001665 setSize(getSize() + AlignMember);
1666 setDataSize(getSize());
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001667
John McCall0153cd32011-11-08 04:01:03 +00001668 NonVirtualSize = Context.toCharUnitsFromBits(
1669 llvm::RoundUpToAlignment(getSizeInBits(),
1670 Context.getTargetInfo().getCharAlign()));
John McCalle42a3362012-05-01 08:55:32 +00001671 }
John McCall0153cd32011-11-08 04:01:03 +00001672
1673 MSLayoutVirtualBases(RD);
John McCall0153cd32011-11-08 04:01:03 +00001674 } else {
1675 // Lay out the virtual bases and add the primary virtual base offsets.
1676 LayoutVirtualBases(RD, RD);
1677 }
1678
1679 // Finally, round the size of the total struct up to the alignment
Eli Friedman83a12582011-12-01 00:37:01 +00001680 // of the struct itself.
1681 FinishLayout(RD);
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001682
Anders Carlsson5b441d72010-04-10 21:24:48 +00001683#ifndef NDEBUG
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001684 // Check that we have base offsets for all bases.
1685 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1686 E = RD->bases_end(); I != E; ++I) {
1687 if (I->isVirtual())
1688 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001689
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001690 const CXXRecordDecl *BaseDecl =
1691 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1692
1693 assert(Bases.count(BaseDecl) && "Did not find base offset!");
1694 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001695
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001696 // And all virtual bases.
1697 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
1698 E = RD->vbases_end(); I != E; ++I) {
1699 const CXXRecordDecl *BaseDecl =
1700 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001701
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001702 assert(VBases.count(BaseDecl) && "Did not find base offset!");
Anders Carlsson5b441d72010-04-10 21:24:48 +00001703 }
1704#endif
Anders Carlsson79474332009-07-18 20:20:21 +00001705}
1706
Anders Carlssonc2226202010-05-26 05:58:59 +00001707void RecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) {
Anders Carlsson4f516282009-07-18 20:50:59 +00001708 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001709 const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD);
Anders Carlsson4f516282009-07-18 20:50:59 +00001710
Ken Dyck85ef0432011-02-19 18:58:07 +00001711 UpdateAlignment(SL.getAlignment());
Mike Stump11289f42009-09-09 15:08:12 +00001712
Anders Carlsson4f516282009-07-18 20:50:59 +00001713 // We start laying out ivars not at the end of the superclass
1714 // structure, but at the next byte following the last field.
Ken Dyckecfc7552011-02-24 01:13:28 +00001715 setSize(SL.getDataSize());
Ken Dyck1b4420e2011-02-28 02:01:38 +00001716 setDataSize(getSize());
Anders Carlsson4f516282009-07-18 20:50:59 +00001717 }
Mike Stump11289f42009-09-09 15:08:12 +00001718
Daniel Dunbar6da10982010-05-27 05:45:51 +00001719 InitializeLayout(D);
Anders Carlsson4f516282009-07-18 20:50:59 +00001720 // Layout each ivar sequentially.
Jordy Rosea91768e2011-07-22 02:08:32 +00001721 for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD;
1722 IVD = IVD->getNextIvar())
Fariborz Jahanianb26d5782011-06-28 18:05:25 +00001723 LayoutField(IVD);
Mike Stump11289f42009-09-09 15:08:12 +00001724
Anders Carlsson4f516282009-07-18 20:50:59 +00001725 // Finally, round the size of the total struct up to the alignment of the
1726 // struct itself.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001727 FinishLayout(D);
Anders Carlsson4f516282009-07-18 20:50:59 +00001728}
1729
Anders Carlssonc2226202010-05-26 05:58:59 +00001730void RecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
Anders Carlsson118ce162009-07-18 21:48:39 +00001731 // Layout each field, for now, just sequentially, respecting alignment. In
1732 // the future, this will need to be tweakable by targets.
Fariborz Jahanianbcb23a12011-04-26 23:52:16 +00001733 const FieldDecl *LastFD = 0;
Fariborz Jahanianfc0fe6e2011-05-03 20:21:04 +00001734 ZeroLengthBitfield = 0;
Fariborz Jahanian783243b2011-05-11 16:58:31 +00001735 unsigned RemainingInAlignment = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001736 for (RecordDecl::field_iterator Field = D->field_begin(),
Fariborz Jahanianbcb23a12011-04-26 23:52:16 +00001737 FieldEnd = D->field_end(); Field != FieldEnd; ++Field) {
1738 if (IsMsStruct) {
David Blaikie40ed2972012-06-06 20:45:41 +00001739 FieldDecl *FD = *Field;
Fariborz Jahanianfc0fe6e2011-05-03 20:21:04 +00001740 if (Context.ZeroBitfieldFollowsBitfield(FD, LastFD))
1741 ZeroLengthBitfield = FD;
Fariborz Jahanianbcb23a12011-04-26 23:52:16 +00001742 // Zero-length bitfields following non-bitfield members are
1743 // ignored:
Fariborz Jahanianfc0fe6e2011-05-03 20:21:04 +00001744 else if (Context.ZeroBitfieldFollowsNonBitfield(FD, LastFD))
Fariborz Jahanianbcb23a12011-04-26 23:52:16 +00001745 continue;
Fariborz Jahanian307eace2011-05-06 22:42:22 +00001746 // FIXME. streamline these conditions into a simple one.
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001747 else if (Context.BitfieldFollowsBitfield(FD, LastFD) ||
Chad Rosierf01a7dd2011-08-04 23:34:15 +00001748 Context.BitfieldFollowsNonBitfield(FD, LastFD) ||
1749 Context.NonBitfieldFollowsBitfield(FD, LastFD)) {
Fariborz Jahanian307eace2011-05-06 22:42:22 +00001750 // 1) Adjacent bit fields are packed into the same 1-, 2-, or
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001751 // 4-byte allocation unit if the integral types are the same
1752 // size and if the next bit field fits into the current
1753 // allocation unit without crossing the boundary imposed by the
1754 // common alignment requirements of the bit fields.
Fariborz Jahanian307eace2011-05-06 22:42:22 +00001755 // 2) Establish a new alignment for a bitfield following
Fariborz Jahanianb7a28792011-05-06 21:56:12 +00001756 // a non-bitfield if size of their types differ.
Fariborz Jahanian307eace2011-05-06 22:42:22 +00001757 // 3) Establish a new alignment for a non-bitfield following
1758 // a bitfield if size of their types differ.
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001759 std::pair<uint64_t, unsigned> FieldInfo =
1760 Context.getTypeInfo(FD->getType());
1761 uint64_t TypeSize = FieldInfo.first;
1762 unsigned FieldAlign = FieldInfo.second;
Fariborz Jahanian7adbed62011-05-09 22:03:17 +00001763 // This check is needed for 'long long' in -m32 mode.
Fariborz Jahanian0586df42011-12-12 21:16:36 +00001764 if (TypeSize > FieldAlign &&
1765 (Context.hasSameType(FD->getType(),
1766 Context.UnsignedLongLongTy)
1767 ||Context.hasSameType(FD->getType(),
1768 Context.LongLongTy)))
Fariborz Jahanian7adbed62011-05-09 22:03:17 +00001769 FieldAlign = TypeSize;
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001770 FieldInfo = Context.getTypeInfo(LastFD->getType());
1771 uint64_t TypeSizeLastFD = FieldInfo.first;
1772 unsigned FieldAlignLastFD = FieldInfo.second;
Fariborz Jahanian7adbed62011-05-09 22:03:17 +00001773 // This check is needed for 'long long' in -m32 mode.
Fariborz Jahanian0586df42011-12-12 21:16:36 +00001774 if (TypeSizeLastFD > FieldAlignLastFD &&
1775 (Context.hasSameType(LastFD->getType(),
1776 Context.UnsignedLongLongTy)
1777 || Context.hasSameType(LastFD->getType(),
1778 Context.LongLongTy)))
Fariborz Jahanian7adbed62011-05-09 22:03:17 +00001779 FieldAlignLastFD = TypeSizeLastFD;
Fariborz Jahanian783243b2011-05-11 16:58:31 +00001780
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001781 if (TypeSizeLastFD != TypeSize) {
Fariborz Jahanian783243b2011-05-11 16:58:31 +00001782 if (RemainingInAlignment &&
1783 LastFD && LastFD->isBitField() &&
Richard Smithcaf33902011-10-10 18:28:20 +00001784 LastFD->getBitWidthValue(Context)) {
Fariborz Jahanian783243b2011-05-11 16:58:31 +00001785 // If previous field was a bitfield with some remaining unfilled
1786 // bits, pad the field so current field starts on its type boundary.
1787 uint64_t FieldOffset =
1788 getDataSizeInBits() - UnfilledBitsInLastByte;
1789 uint64_t NewSizeInBits = RemainingInAlignment + FieldOffset;
1790 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
Douglas Gregore8bbc122011-09-02 00:18:52 +00001791 Context.getTargetInfo().getCharAlign()));
Fariborz Jahanian783243b2011-05-11 16:58:31 +00001792 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1793 RemainingInAlignment = 0;
1794 }
1795
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001796 uint64_t UnpaddedFieldOffset =
1797 getDataSizeInBits() - UnfilledBitsInLastByte;
1798 FieldAlign = std::max(FieldAlign, FieldAlignLastFD);
Fariborz Jahanian783243b2011-05-11 16:58:31 +00001799
Fariborz Jahanian07ceb0a2011-05-10 19:00:50 +00001800 // The maximum field alignment overrides the aligned attribute.
1801 if (!MaxFieldAlignment.isZero()) {
1802 unsigned MaxFieldAlignmentInBits =
1803 Context.toBits(MaxFieldAlignment);
1804 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1805 }
Fariborz Jahanian783243b2011-05-11 16:58:31 +00001806
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001807 uint64_t NewSizeInBits =
1808 llvm::RoundUpToAlignment(UnpaddedFieldOffset, FieldAlign);
1809 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
Douglas Gregore8bbc122011-09-02 00:18:52 +00001810 Context.getTargetInfo().getCharAlign()));
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001811 UnfilledBitsInLastByte = getDataSizeInBits() - NewSizeInBits;
1812 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1813 }
Fariborz Jahanian783243b2011-05-11 16:58:31 +00001814 if (FD->isBitField()) {
Richard Smithcaf33902011-10-10 18:28:20 +00001815 uint64_t FieldSize = FD->getBitWidthValue(Context);
Fariborz Jahanian783243b2011-05-11 16:58:31 +00001816 assert (FieldSize > 0 && "LayoutFields - ms_struct layout");
1817 if (RemainingInAlignment < FieldSize)
1818 RemainingInAlignment = TypeSize - FieldSize;
1819 else
1820 RemainingInAlignment -= FieldSize;
1821 }
1822 }
1823 else if (FD->isBitField()) {
Richard Smithcaf33902011-10-10 18:28:20 +00001824 uint64_t FieldSize = FD->getBitWidthValue(Context);
Fariborz Jahanian783243b2011-05-11 16:58:31 +00001825 std::pair<uint64_t, unsigned> FieldInfo =
1826 Context.getTypeInfo(FD->getType());
1827 uint64_t TypeSize = FieldInfo.first;
1828 RemainingInAlignment = TypeSize - FieldSize;
Fariborz Jahanian84335f72011-05-04 18:51:37 +00001829 }
Fariborz Jahanianbcb23a12011-04-26 23:52:16 +00001830 LastFD = FD;
1831 }
Douglas Gregore8bbc122011-09-02 00:18:52 +00001832 else if (!Context.getTargetInfo().useBitFieldTypeAlignment() &&
1833 Context.getTargetInfo().useZeroLengthBitfieldAlignment()) {
David Blaikie40ed2972012-06-06 20:45:41 +00001834 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
1835 ZeroLengthBitfield = *Field;
Chad Rosier18903ee2011-08-04 01:21:14 +00001836 }
David Blaikie40ed2972012-06-06 20:45:41 +00001837 LayoutField(*Field);
Fariborz Jahanianbcb23a12011-04-26 23:52:16 +00001838 }
Fariborz Jahanian783243b2011-05-11 16:58:31 +00001839 if (IsMsStruct && RemainingInAlignment &&
Richard Smithcaf33902011-10-10 18:28:20 +00001840 LastFD && LastFD->isBitField() && LastFD->getBitWidthValue(Context)) {
Fariborz Jahanian783243b2011-05-11 16:58:31 +00001841 // If we ended a bitfield before the full length of the type then
1842 // pad the struct out to the full length of the last type.
1843 uint64_t FieldOffset =
1844 getDataSizeInBits() - UnfilledBitsInLastByte;
1845 uint64_t NewSizeInBits = RemainingInAlignment + FieldOffset;
1846 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
Douglas Gregore8bbc122011-09-02 00:18:52 +00001847 Context.getTargetInfo().getCharAlign()));
Fariborz Jahanian783243b2011-05-11 16:58:31 +00001848 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1849 }
Anders Carlsson118ce162009-07-18 21:48:39 +00001850}
1851
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001852void RecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize,
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001853 uint64_t TypeSize,
1854 bool FieldPacked,
1855 const FieldDecl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001856 assert(Context.getLangOpts().CPlusPlus &&
Anders Carlsson57235162010-04-16 15:57:11 +00001857 "Can only have wide bit-fields in C++!");
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001858
Anders Carlsson57235162010-04-16 15:57:11 +00001859 // Itanium C++ ABI 2.4:
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001860 // If sizeof(T)*8 < n, let T' be the largest integral POD type with
Anders Carlsson57235162010-04-16 15:57:11 +00001861 // sizeof(T')*8 <= n.
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001862
Anders Carlsson57235162010-04-16 15:57:11 +00001863 QualType IntegralPODTypes[] = {
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001864 Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy,
Anders Carlsson57235162010-04-16 15:57:11 +00001865 Context.UnsignedLongTy, Context.UnsignedLongLongTy
1866 };
1867
Anders Carlsson57235162010-04-16 15:57:11 +00001868 QualType Type;
1869 for (unsigned I = 0, E = llvm::array_lengthof(IntegralPODTypes);
1870 I != E; ++I) {
1871 uint64_t Size = Context.getTypeSize(IntegralPODTypes[I]);
Anders Carlsson57235162010-04-16 15:57:11 +00001872
1873 if (Size > FieldSize)
1874 break;
1875
1876 Type = IntegralPODTypes[I];
1877 }
1878 assert(!Type.isNull() && "Did not find a type!");
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001879
Ken Dyckdbe37f32011-03-01 01:36:00 +00001880 CharUnits TypeAlign = Context.getTypeAlignInChars(Type);
Anders Carlsson57235162010-04-16 15:57:11 +00001881
1882 // We're not going to use any of the unfilled bits in the last byte.
1883 UnfilledBitsInLastByte = 0;
1884
Anders Carlssonaad5fa82010-04-17 20:21:41 +00001885 uint64_t FieldOffset;
Ken Dyckecfc7552011-02-24 01:13:28 +00001886 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastByte;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001887
Anders Carlsson57235162010-04-16 15:57:11 +00001888 if (IsUnion) {
Ken Dyckecfc7552011-02-24 01:13:28 +00001889 setDataSize(std::max(getDataSizeInBits(), FieldSize));
Anders Carlssonaad5fa82010-04-17 20:21:41 +00001890 FieldOffset = 0;
Anders Carlsson57235162010-04-16 15:57:11 +00001891 } else {
Chad Rosiere1a6a0e2011-08-05 22:38:04 +00001892 // The bitfield is allocated starting at the next offset aligned
1893 // appropriately for T', with length n bits.
Ken Dyckdbe37f32011-03-01 01:36:00 +00001894 FieldOffset = llvm::RoundUpToAlignment(getDataSizeInBits(),
1895 Context.toBits(TypeAlign));
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001896
Anders Carlsson57235162010-04-16 15:57:11 +00001897 uint64_t NewSizeInBits = FieldOffset + FieldSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001898
Ken Dycka1a2e8d2011-03-10 02:00:35 +00001899 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
Douglas Gregore8bbc122011-09-02 00:18:52 +00001900 Context.getTargetInfo().getCharAlign()));
Ken Dyckecfc7552011-02-24 01:13:28 +00001901 UnfilledBitsInLastByte = getDataSizeInBits() - NewSizeInBits;
Anders Carlsson57235162010-04-16 15:57:11 +00001902 }
1903
1904 // Place this field at the current location.
1905 FieldOffsets.push_back(FieldOffset);
1906
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001907 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset,
Ken Dyckdbe37f32011-03-01 01:36:00 +00001908 Context.toBits(TypeAlign), FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001909
Anders Carlsson57235162010-04-16 15:57:11 +00001910 // Update the size.
Ken Dyckecfc7552011-02-24 01:13:28 +00001911 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001912
Anders Carlsson57235162010-04-16 15:57:11 +00001913 // Remember max struct/class alignment.
Ken Dyckdbe37f32011-03-01 01:36:00 +00001914 UpdateAlignment(TypeAlign);
Anders Carlsson57235162010-04-16 15:57:11 +00001915}
1916
Anders Carlssonc2226202010-05-26 05:58:59 +00001917void RecordLayoutBuilder::LayoutBitField(const FieldDecl *D) {
Anders Carlsson07209442009-11-22 17:37:31 +00001918 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
Ken Dyckecfc7552011-02-24 01:13:28 +00001919 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastByte;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001920 uint64_t FieldOffset = IsUnion ? 0 : UnpaddedFieldOffset;
Richard Smithcaf33902011-10-10 18:28:20 +00001921 uint64_t FieldSize = D->getBitWidthValue(Context);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001922
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001923 std::pair<uint64_t, unsigned> FieldInfo = Context.getTypeInfo(D->getType());
Anders Carlsson07209442009-11-22 17:37:31 +00001924 uint64_t TypeSize = FieldInfo.first;
1925 unsigned FieldAlign = FieldInfo.second;
Fariborz Jahanianfc0fe6e2011-05-03 20:21:04 +00001926
Fariborz Jahanian7adbed62011-05-09 22:03:17 +00001927 // This check is needed for 'long long' in -m32 mode.
Fariborz Jahanian0586df42011-12-12 21:16:36 +00001928 if (IsMsStruct && (TypeSize > FieldAlign) &&
1929 (Context.hasSameType(D->getType(),
1930 Context.UnsignedLongLongTy)
1931 || Context.hasSameType(D->getType(), Context.LongLongTy)))
Fariborz Jahanian7adbed62011-05-09 22:03:17 +00001932 FieldAlign = TypeSize;
Chad Rosier18903ee2011-08-04 01:21:14 +00001933
Fariborz Jahanianfc0fe6e2011-05-03 20:21:04 +00001934 if (ZeroLengthBitfield) {
Chad Rosiere1a6a0e2011-08-05 22:38:04 +00001935 std::pair<uint64_t, unsigned> FieldInfo;
1936 unsigned ZeroLengthBitfieldAlignment;
1937 if (IsMsStruct) {
1938 // If a zero-length bitfield is inserted after a bitfield,
1939 // and the alignment of the zero-length bitfield is
1940 // greater than the member that follows it, `bar', `bar'
1941 // will be aligned as the type of the zero-length bitfield.
1942 if (ZeroLengthBitfield != D) {
1943 FieldInfo = Context.getTypeInfo(ZeroLengthBitfield->getType());
1944 ZeroLengthBitfieldAlignment = FieldInfo.second;
1945 // Ignore alignment of subsequent zero-length bitfields.
1946 if ((ZeroLengthBitfieldAlignment > FieldAlign) || (FieldSize == 0))
1947 FieldAlign = ZeroLengthBitfieldAlignment;
1948 if (FieldSize)
1949 ZeroLengthBitfield = 0;
1950 }
1951 } else {
1952 // The alignment of a zero-length bitfield affects the alignment
1953 // of the next member. The alignment is the max of the zero
1954 // length bitfield's alignment and a target specific fixed value.
1955 unsigned ZeroLengthBitfieldBoundary =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001956 Context.getTargetInfo().getZeroLengthBitfieldBoundary();
Chad Rosiere1a6a0e2011-08-05 22:38:04 +00001957 if (ZeroLengthBitfieldBoundary > FieldAlign)
1958 FieldAlign = ZeroLengthBitfieldBoundary;
Fariborz Jahanianfc0fe6e2011-05-03 20:21:04 +00001959 }
1960 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001961
Anders Carlsson57235162010-04-16 15:57:11 +00001962 if (FieldSize > TypeSize) {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001963 LayoutWideBitField(FieldSize, TypeSize, FieldPacked, D);
Anders Carlsson57235162010-04-16 15:57:11 +00001964 return;
1965 }
1966
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001967 // The align if the field is not packed. This is to check if the attribute
1968 // was unnecessary (-Wpacked).
1969 unsigned UnpackedFieldAlign = FieldAlign;
1970 uint64_t UnpackedFieldOffset = FieldOffset;
Douglas Gregore8bbc122011-09-02 00:18:52 +00001971 if (!Context.getTargetInfo().useBitFieldTypeAlignment() && !ZeroLengthBitfield)
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001972 UnpackedFieldAlign = 1;
1973
Chad Rosiere1a6a0e2011-08-05 22:38:04 +00001974 if (FieldPacked ||
Douglas Gregore8bbc122011-09-02 00:18:52 +00001975 (!Context.getTargetInfo().useBitFieldTypeAlignment() && !ZeroLengthBitfield))
Anders Carlsson07209442009-11-22 17:37:31 +00001976 FieldAlign = 1;
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001977 FieldAlign = std::max(FieldAlign, D->getMaxAlignment());
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001978 UnpackedFieldAlign = std::max(UnpackedFieldAlign, D->getMaxAlignment());
Anders Carlsson07209442009-11-22 17:37:31 +00001979
1980 // The maximum field alignment overrides the aligned attribute.
Eli Friedmana91d38a2011-12-02 02:38:48 +00001981 if (!MaxFieldAlignment.isZero() && FieldSize != 0) {
Ken Dyck02ced6f2011-02-17 01:49:42 +00001982 unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment);
1983 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1984 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001985 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001986
Douglas Gregor44ba7892012-01-28 00:53:29 +00001987 // Check if we need to add padding to give the field the correct alignment.
1988 if (FieldSize == 0 ||
1989 (MaxFieldAlignment.isZero() &&
1990 (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize))
1991 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001992
Douglas Gregor44ba7892012-01-28 00:53:29 +00001993 if (FieldSize == 0 ||
1994 (MaxFieldAlignment.isZero() &&
1995 (UnpackedFieldOffset & (UnpackedFieldAlign-1)) + FieldSize > TypeSize))
1996 UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1997 UnpackedFieldAlign);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001998
Chad Rosiere1a6a0e2011-08-05 22:38:04 +00001999 // Padding members don't affect overall alignment, unless zero length bitfield
2000 // alignment is enabled.
Douglas Gregore8bbc122011-09-02 00:18:52 +00002001 if (!D->getIdentifier() && !Context.getTargetInfo().useZeroLengthBitfieldAlignment())
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002002 FieldAlign = UnpackedFieldAlign = 1;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002003
Chad Rosiere1a6a0e2011-08-05 22:38:04 +00002004 if (!IsMsStruct)
2005 ZeroLengthBitfield = 0;
2006
Douglas Gregor44ba7892012-01-28 00:53:29 +00002007 if (ExternalLayout)
2008 FieldOffset = updateExternalFieldOffset(D, FieldOffset);
2009
Anders Carlsson07209442009-11-22 17:37:31 +00002010 // Place this field at the current location.
2011 FieldOffsets.push_back(FieldOffset);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002012
Douglas Gregore9fc3772012-01-26 07:55:45 +00002013 if (!ExternalLayout)
2014 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset,
2015 UnpackedFieldAlign, FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002016
Anders Carlssonba958402009-11-22 19:13:51 +00002017 // Update DataSize to include the last byte containing (part of) the bitfield.
2018 if (IsUnion) {
2019 // FIXME: I think FieldSize should be TypeSize here.
Ken Dyckecfc7552011-02-24 01:13:28 +00002020 setDataSize(std::max(getDataSizeInBits(), FieldSize));
Anders Carlssonba958402009-11-22 19:13:51 +00002021 } else {
2022 uint64_t NewSizeInBits = FieldOffset + FieldSize;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002023
Ken Dycka1a2e8d2011-03-10 02:00:35 +00002024 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
Douglas Gregore8bbc122011-09-02 00:18:52 +00002025 Context.getTargetInfo().getCharAlign()));
Ken Dyckecfc7552011-02-24 01:13:28 +00002026 UnfilledBitsInLastByte = getDataSizeInBits() - NewSizeInBits;
Anders Carlssonba958402009-11-22 19:13:51 +00002027 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002028
Anders Carlssonba958402009-11-22 19:13:51 +00002029 // Update the size.
Ken Dyckecfc7552011-02-24 01:13:28 +00002030 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002031
Anders Carlsson07209442009-11-22 17:37:31 +00002032 // Remember max struct/class alignment.
Ken Dyck85ef0432011-02-19 18:58:07 +00002033 UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign),
2034 Context.toCharUnitsFromBits(UnpackedFieldAlign));
Anders Carlsson07209442009-11-22 17:37:31 +00002035}
2036
Douglas Gregore9fc3772012-01-26 07:55:45 +00002037void RecordLayoutBuilder::LayoutField(const FieldDecl *D) {
Anders Carlsson07209442009-11-22 17:37:31 +00002038 if (D->isBitField()) {
2039 LayoutBitField(D);
2040 return;
2041 }
2042
Ken Dyckecfc7552011-02-24 01:13:28 +00002043 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastByte;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002044
Anders Carlssonba958402009-11-22 19:13:51 +00002045 // Reset the unfilled bits.
2046 UnfilledBitsInLastByte = 0;
2047
Anders Carlsson07209442009-11-22 17:37:31 +00002048 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
Ken Dyck6d90e892011-02-20 02:06:09 +00002049 CharUnits FieldOffset =
Ken Dyckecfc7552011-02-24 01:13:28 +00002050 IsUnion ? CharUnits::Zero() : getDataSize();
Ken Dyck6d90e892011-02-20 02:06:09 +00002051 CharUnits FieldSize;
2052 CharUnits FieldAlign;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002053
Anders Carlsson07209442009-11-22 17:37:31 +00002054 if (D->getType()->isIncompleteArrayType()) {
2055 // This is a flexible array member; we can't directly
2056 // query getTypeInfo about these, so we figure it out here.
2057 // Flexible array members don't have any size, but they
2058 // have to be aligned appropriately for their element type.
Ken Dyck6d90e892011-02-20 02:06:09 +00002059 FieldSize = CharUnits::Zero();
Anders Carlsson5efc56e2010-04-16 15:07:51 +00002060 const ArrayType* ATy = Context.getAsArrayType(D->getType());
Ken Dyck6d90e892011-02-20 02:06:09 +00002061 FieldAlign = Context.getTypeAlignInChars(ATy->getElementType());
Anders Carlsson07209442009-11-22 17:37:31 +00002062 } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) {
2063 unsigned AS = RT->getPointeeType().getAddressSpace();
Ken Dyck6d90e892011-02-20 02:06:09 +00002064 FieldSize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002065 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(AS));
Ken Dyck6d90e892011-02-20 02:06:09 +00002066 FieldAlign =
Douglas Gregore8bbc122011-09-02 00:18:52 +00002067 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(AS));
Anders Carlsson79474332009-07-18 20:20:21 +00002068 } else {
Ken Dyck6d90e892011-02-20 02:06:09 +00002069 std::pair<CharUnits, CharUnits> FieldInfo =
2070 Context.getTypeInfoInChars(D->getType());
Anders Carlsson07209442009-11-22 17:37:31 +00002071 FieldSize = FieldInfo.first;
2072 FieldAlign = FieldInfo.second;
Chad Rosier18903ee2011-08-04 01:21:14 +00002073
Fariborz Jahanianfc0fe6e2011-05-03 20:21:04 +00002074 if (ZeroLengthBitfield) {
Chad Rosier18903ee2011-08-04 01:21:14 +00002075 CharUnits ZeroLengthBitfieldBoundary =
2076 Context.toCharUnitsFromBits(
Douglas Gregore8bbc122011-09-02 00:18:52 +00002077 Context.getTargetInfo().getZeroLengthBitfieldBoundary());
Chad Rosier18903ee2011-08-04 01:21:14 +00002078 if (ZeroLengthBitfieldBoundary == CharUnits::Zero()) {
2079 // If a zero-length bitfield is inserted after a bitfield,
2080 // and the alignment of the zero-length bitfield is
2081 // greater than the member that follows it, `bar', `bar'
2082 // will be aligned as the type of the zero-length bitfield.
2083 std::pair<CharUnits, CharUnits> FieldInfo =
2084 Context.getTypeInfoInChars(ZeroLengthBitfield->getType());
2085 CharUnits ZeroLengthBitfieldAlignment = FieldInfo.second;
2086 if (ZeroLengthBitfieldAlignment > FieldAlign)
2087 FieldAlign = ZeroLengthBitfieldAlignment;
Chad Rosier64b18ee2011-08-04 19:25:14 +00002088 } else if (ZeroLengthBitfieldBoundary > FieldAlign) {
Chad Rosier18903ee2011-08-04 01:21:14 +00002089 // Align 'bar' based on a fixed alignment specified by the target.
Douglas Gregore8bbc122011-09-02 00:18:52 +00002090 assert(Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
Chad Rosiera336c6f2011-08-04 17:52:43 +00002091 "ZeroLengthBitfieldBoundary should only be used in conjunction"
2092 " with useZeroLengthBitfieldAlignment.");
Chad Rosier18903ee2011-08-04 01:21:14 +00002093 FieldAlign = ZeroLengthBitfieldBoundary;
2094 }
Fariborz Jahanianfc0fe6e2011-05-03 20:21:04 +00002095 ZeroLengthBitfield = 0;
2096 }
Douglas Gregordbe39272011-02-01 15:15:22 +00002097
Eli Friedman9ee2d0472012-10-12 23:29:20 +00002098 if (IsMsStruct) {
Douglas Gregordbe39272011-02-01 15:15:22 +00002099 // If MS bitfield layout is required, figure out what type is being
2100 // laid out and align the field to the width of that type.
2101
2102 // Resolve all typedefs down to their base type and round up the field
2103 // alignment if necessary.
2104 QualType T = Context.getBaseElementType(D->getType());
2105 if (const BuiltinType *BTy = T->getAs<BuiltinType>()) {
Ken Dyck6d90e892011-02-20 02:06:09 +00002106 CharUnits TypeSize = Context.getTypeSizeInChars(BTy);
Douglas Gregordbe39272011-02-01 15:15:22 +00002107 if (TypeSize > FieldAlign)
2108 FieldAlign = TypeSize;
2109 }
2110 }
Anders Carlsson79474332009-07-18 20:20:21 +00002111 }
Mike Stump11289f42009-09-09 15:08:12 +00002112
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002113 // The align if the field is not packed. This is to check if the attribute
2114 // was unnecessary (-Wpacked).
Ken Dyck6d90e892011-02-20 02:06:09 +00002115 CharUnits UnpackedFieldAlign = FieldAlign;
2116 CharUnits UnpackedFieldOffset = FieldOffset;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002117
Anders Carlsson07209442009-11-22 17:37:31 +00002118 if (FieldPacked)
Ken Dyck6d90e892011-02-20 02:06:09 +00002119 FieldAlign = CharUnits::One();
2120 CharUnits MaxAlignmentInChars =
2121 Context.toCharUnitsFromBits(D->getMaxAlignment());
2122 FieldAlign = std::max(FieldAlign, MaxAlignmentInChars);
2123 UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars);
Anders Carlsson07209442009-11-22 17:37:31 +00002124
2125 // The maximum field alignment overrides the aligned attribute.
Ken Dyck02ced6f2011-02-17 01:49:42 +00002126 if (!MaxFieldAlignment.isZero()) {
Ken Dyck6d90e892011-02-20 02:06:09 +00002127 FieldAlign = std::min(FieldAlign, MaxFieldAlignment);
2128 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002129 }
Anders Carlsson07209442009-11-22 17:37:31 +00002130
Douglas Gregor44ba7892012-01-28 00:53:29 +00002131 // Round up the current record size to the field's alignment boundary.
2132 FieldOffset = FieldOffset.RoundUpToAlignment(FieldAlign);
2133 UnpackedFieldOffset =
2134 UnpackedFieldOffset.RoundUpToAlignment(UnpackedFieldAlign);
2135
2136 if (ExternalLayout) {
2137 FieldOffset = Context.toCharUnitsFromBits(
2138 updateExternalFieldOffset(D, Context.toBits(FieldOffset)));
2139
2140 if (!IsUnion && EmptySubobjects) {
2141 // Record the fact that we're placing a field at this offset.
2142 bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset);
2143 (void)Allowed;
2144 assert(Allowed && "Externally-placed field cannot be placed here");
2145 }
2146 } else {
Douglas Gregore9fc3772012-01-26 07:55:45 +00002147 if (!IsUnion && EmptySubobjects) {
2148 // Check if we can place the field at this offset.
2149 while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) {
2150 // We couldn't place the field at the offset. Try again at a new offset.
2151 FieldOffset += FieldAlign;
2152 }
Anders Carlsson07209442009-11-22 17:37:31 +00002153 }
Anders Carlsson07209442009-11-22 17:37:31 +00002154 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00002155
Anders Carlsson79474332009-07-18 20:20:21 +00002156 // Place this field at the current location.
Ken Dyck6d90e892011-02-20 02:06:09 +00002157 FieldOffsets.push_back(Context.toBits(FieldOffset));
Mike Stump11289f42009-09-09 15:08:12 +00002158
Douglas Gregore9fc3772012-01-26 07:55:45 +00002159 if (!ExternalLayout)
2160 CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset,
2161 Context.toBits(UnpackedFieldOffset),
2162 Context.toBits(UnpackedFieldAlign), FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002163
Anders Carlsson79474332009-07-18 20:20:21 +00002164 // Reserve space for this field.
Eli Friedman43f18342012-01-12 23:27:03 +00002165 uint64_t FieldSizeInBits = Context.toBits(FieldSize);
Anders Carlsson79474332009-07-18 20:20:21 +00002166 if (IsUnion)
Eli Friedman2e108372012-01-12 23:48:56 +00002167 setDataSize(std::max(getDataSizeInBits(), FieldSizeInBits));
Anders Carlsson79474332009-07-18 20:20:21 +00002168 else
Eli Friedman2e108372012-01-12 23:48:56 +00002169 setDataSize(FieldOffset + FieldSize);
Mike Stump11289f42009-09-09 15:08:12 +00002170
Eli Friedman2e108372012-01-12 23:48:56 +00002171 // Update the size.
2172 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Mike Stump11289f42009-09-09 15:08:12 +00002173
Anders Carlsson79474332009-07-18 20:20:21 +00002174 // Remember max struct/class alignment.
Ken Dyck6d90e892011-02-20 02:06:09 +00002175 UpdateAlignment(FieldAlign, UnpackedFieldAlign);
Anders Carlsson79474332009-07-18 20:20:21 +00002176}
2177
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002178void RecordLayoutBuilder::FinishLayout(const NamedDecl *D) {
Anders Carlsson79474332009-07-18 20:20:21 +00002179 // In C++, records cannot be of size 0.
David Blaikiebbafb8a2012-03-11 07:00:24 +00002180 if (Context.getLangOpts().CPlusPlus && getSizeInBits() == 0) {
Fariborz Jahanian09b23312011-02-02 19:36:18 +00002181 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2182 // Compatibility with gcc requires a class (pod or non-pod)
2183 // which is not empty but of size 0; such as having fields of
2184 // array of zero-length, remains of Size 0
2185 if (RD->isEmpty())
Ken Dyck1b4420e2011-02-28 02:01:38 +00002186 setSize(CharUnits::One());
Fariborz Jahanian09b23312011-02-02 19:36:18 +00002187 }
2188 else
Ken Dyck1b4420e2011-02-28 02:01:38 +00002189 setSize(CharUnits::One());
Fariborz Jahanian09b23312011-02-02 19:36:18 +00002190 }
Eli Friedman83a12582011-12-01 00:37:01 +00002191
Douglas Gregor1423a5c2012-10-26 22:31:14 +00002192 // Finally, round the size of the record up to the alignment of the
2193 // record itself.
2194 uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastByte;
2195 uint64_t UnpackedSizeInBits =
2196 llvm::RoundUpToAlignment(getSizeInBits(),
2197 Context.toBits(UnpackedAlignment));
2198 CharUnits UnpackedSize = Context.toCharUnitsFromBits(UnpackedSizeInBits);
2199 uint64_t RoundedSize
2200 = llvm::RoundUpToAlignment(getSizeInBits(), Context.toBits(Alignment));
2201
2202 if (ExternalLayout) {
2203 // If we're inferring alignment, and the external size is smaller than
2204 // our size after we've rounded up to alignment, conservatively set the
2205 // alignment to 1.
2206 if (InferAlignment && ExternalSize < RoundedSize) {
2207 Alignment = CharUnits::One();
2208 InferAlignment = false;
2209 }
2210 setSize(ExternalSize);
2211 return;
2212 }
2213
2214
Eli Friedman83a12582011-12-01 00:37:01 +00002215 // MSVC doesn't round up to the alignment of the record with virtual bases.
2216 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2217 if (isMicrosoftCXXABI() && RD->getNumVBases())
2218 return;
2219 }
2220
Douglas Gregor1423a5c2012-10-26 22:31:14 +00002221 // Set the size to the final size.
2222 setSize(RoundedSize);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002223
Douglas Gregore8bbc122011-09-02 00:18:52 +00002224 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002225 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
2226 // Warn if padding was introduced to the struct/class/union.
Ken Dyckecfc7552011-02-24 01:13:28 +00002227 if (getSizeInBits() > UnpaddedSize) {
2228 unsigned PadSize = getSizeInBits() - UnpaddedSize;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002229 bool InBits = true;
2230 if (PadSize % CharBitNum == 0) {
2231 PadSize = PadSize / CharBitNum;
2232 InBits = false;
2233 }
2234 Diag(RD->getLocation(), diag::warn_padded_struct_size)
2235 << Context.getTypeDeclType(RD)
2236 << PadSize
2237 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
2238 }
2239
2240 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
2241 // bother since there won't be alignment issues.
Ken Dyckecfc7552011-02-24 01:13:28 +00002242 if (Packed && UnpackedAlignment > CharUnits::One() &&
Ken Dyck1b4420e2011-02-28 02:01:38 +00002243 getSize() == UnpackedSize)
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002244 Diag(D->getLocation(), diag::warn_unnecessary_packed)
2245 << Context.getTypeDeclType(RD);
2246 }
Anders Carlsson79474332009-07-18 20:20:21 +00002247}
2248
Ken Dyck85ef0432011-02-19 18:58:07 +00002249void RecordLayoutBuilder::UpdateAlignment(CharUnits NewAlignment,
2250 CharUnits UnpackedNewAlignment) {
Douglas Gregore9fc3772012-01-26 07:55:45 +00002251 // The alignment is not modified when using 'mac68k' alignment or when
Douglas Gregor44ba7892012-01-28 00:53:29 +00002252 // we have an externally-supplied layout that also provides overall alignment.
2253 if (IsMac68kAlign || (ExternalLayout && !InferAlignment))
Daniel Dunbar6da10982010-05-27 05:45:51 +00002254 return;
2255
Ken Dyck85ef0432011-02-19 18:58:07 +00002256 if (NewAlignment > Alignment) {
2257 assert(llvm::isPowerOf2_32(NewAlignment.getQuantity() &&
2258 "Alignment not a power of 2"));
2259 Alignment = NewAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002260 }
2261
Ken Dyck85ef0432011-02-19 18:58:07 +00002262 if (UnpackedNewAlignment > UnpackedAlignment) {
2263 assert(llvm::isPowerOf2_32(UnpackedNewAlignment.getQuantity() &&
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002264 "Alignment not a power of 2"));
Ken Dyck85ef0432011-02-19 18:58:07 +00002265 UnpackedAlignment = UnpackedNewAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002266 }
2267}
2268
Douglas Gregor44ba7892012-01-28 00:53:29 +00002269uint64_t
2270RecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field,
2271 uint64_t ComputedOffset) {
2272 assert(ExternalFieldOffsets.find(Field) != ExternalFieldOffsets.end() &&
2273 "Field does not have an external offset");
2274
2275 uint64_t ExternalFieldOffset = ExternalFieldOffsets[Field];
2276
2277 if (InferAlignment && ExternalFieldOffset < ComputedOffset) {
2278 // The externally-supplied field offset is before the field offset we
2279 // computed. Assume that the structure is packed.
Douglas Gregor1423a5c2012-10-26 22:31:14 +00002280 Alignment = CharUnits::One();
Douglas Gregor44ba7892012-01-28 00:53:29 +00002281 InferAlignment = false;
2282 }
2283
2284 // Use the externally-supplied field offset.
Benjamin Kramer648e68b2012-08-31 22:14:25 +00002285 return ExternalFieldOffset;
2286}
2287
2288/// \brief Get diagnostic %select index for tag kind for
2289/// field padding diagnostic message.
2290/// WARNING: Indexes apply to particular diagnostics only!
2291///
2292/// \returns diagnostic %select index.
2293static unsigned getPaddingDiagFromTagKind(TagTypeKind Tag) {
2294 switch (Tag) {
2295 case TTK_Struct: return 0;
2296 case TTK_Interface: return 1;
2297 case TTK_Class: return 2;
2298 default: llvm_unreachable("Invalid tag kind for field padding diagnostic!");
2299 }
2300}
2301
2302void RecordLayoutBuilder::CheckFieldPadding(uint64_t Offset,
2303 uint64_t UnpaddedOffset,
2304 uint64_t UnpackedOffset,
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002305 unsigned UnpackedAlign,
2306 bool isPacked,
2307 const FieldDecl *D) {
2308 // We let objc ivars without warning, objc interfaces generally are not used
2309 // for padding tricks.
2310 if (isa<ObjCIvarDecl>(D))
Anders Carlsson79474332009-07-18 20:20:21 +00002311 return;
Mike Stump11289f42009-09-09 15:08:12 +00002312
Ted Kremenekfed48af2011-09-06 19:40:45 +00002313 // Don't warn about structs created without a SourceLocation. This can
2314 // be done by clients of the AST, such as codegen.
2315 if (D->getLocation().isInvalid())
2316 return;
2317
Douglas Gregore8bbc122011-09-02 00:18:52 +00002318 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
Mike Stump11289f42009-09-09 15:08:12 +00002319
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002320 // Warn if padding was introduced to the struct/class.
2321 if (!IsUnion && Offset > UnpaddedOffset) {
2322 unsigned PadSize = Offset - UnpaddedOffset;
2323 bool InBits = true;
2324 if (PadSize % CharBitNum == 0) {
2325 PadSize = PadSize / CharBitNum;
2326 InBits = false;
Benjamin Kramer648e68b2012-08-31 22:14:25 +00002327 }
2328 if (D->getIdentifier())
2329 Diag(D->getLocation(), diag::warn_padded_struct_field)
2330 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
2331 << Context.getTypeDeclType(D->getParent())
2332 << PadSize
2333 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1) // plural or not
2334 << D->getIdentifier();
2335 else
2336 Diag(D->getLocation(), diag::warn_padded_struct_anon_field)
2337 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
2338 << Context.getTypeDeclType(D->getParent())
2339 << PadSize
2340 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002341 }
2342
2343 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
2344 // bother since there won't be alignment issues.
2345 if (isPacked && UnpackedAlign > CharBitNum && Offset == UnpackedOffset)
2346 Diag(D->getLocation(), diag::warn_unnecessary_packed)
2347 << D->getIdentifier();
Anders Carlsson79474332009-07-18 20:20:21 +00002348}
Mike Stump11289f42009-09-09 15:08:12 +00002349
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00002350const CXXMethodDecl *
Anders Carlssonc2226202010-05-26 05:58:59 +00002351RecordLayoutBuilder::ComputeKeyFunction(const CXXRecordDecl *RD) {
Daniel Dunbarccabe482010-04-19 20:44:53 +00002352 // If a class isn't polymorphic it doesn't have a key function.
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00002353 if (!RD->isPolymorphic())
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002354 return 0;
Eli Friedmanf2c79b62009-12-08 03:56:49 +00002355
Eli Friedman300f55d2011-06-10 21:53:06 +00002356 // A class that is not externally visible doesn't have a key function. (Or
Eli Friedmanf2c79b62009-12-08 03:56:49 +00002357 // at least, there's no point to assigning a key function to such a class;
2358 // this doesn't affect the ABI.)
Eli Friedman300f55d2011-06-10 21:53:06 +00002359 if (RD->getLinkage() != ExternalLinkage)
Eli Friedmanf2c79b62009-12-08 03:56:49 +00002360 return 0;
2361
Argyrios Kyrtzidis8c64bbe2010-10-13 02:39:41 +00002362 // Template instantiations don't have key functions,see Itanium C++ ABI 5.2.6.
2363 // Same behavior as GCC.
2364 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
2365 if (TSK == TSK_ImplicitInstantiation ||
2366 TSK == TSK_ExplicitInstantiationDefinition)
2367 return 0;
2368
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002369 for (CXXRecordDecl::method_iterator I = RD->method_begin(),
2370 E = RD->method_end(); I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00002371 const CXXMethodDecl *MD = *I;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002372
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002373 if (!MD->isVirtual())
2374 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002375
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002376 if (MD->isPure())
2377 continue;
Eli Friedmanf2c79b62009-12-08 03:56:49 +00002378
Anders Carlssonf98849e2009-12-02 17:15:43 +00002379 // Ignore implicit member functions, they are always marked as inline, but
2380 // they don't have a body until they're defined.
2381 if (MD->isImplicit())
2382 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002383
Douglas Gregora318efd2010-01-05 19:06:31 +00002384 if (MD->isInlineSpecified())
2385 continue;
Eli Friedman71a26d82009-12-06 20:50:05 +00002386
2387 if (MD->hasInlineBody())
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002388 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002389
Benjamin Kramer4a902082012-08-03 15:43:22 +00002390 // Ignore inline deleted or defaulted functions.
Benjamin Kramer73d1be72012-08-03 08:39:58 +00002391 if (!MD->isUserProvided())
2392 continue;
2393
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002394 // We found it.
2395 return MD;
2396 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002397
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002398 return 0;
2399}
2400
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002401DiagnosticBuilder
2402RecordLayoutBuilder::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +00002403 return Context.getDiagnostics().Report(Loc, DiagID);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002404}
2405
Anders Carlssondf291d82010-05-26 04:56:53 +00002406/// getASTRecordLayout - Get or compute information about the layout of the
2407/// specified record (struct/union/class), which indicates its size and field
2408/// position information.
Jay Foad39c79802011-01-12 09:06:06 +00002409const ASTRecordLayout &
2410ASTContext::getASTRecordLayout(const RecordDecl *D) const {
John McCall0710e552011-10-07 02:39:22 +00002411 // These asserts test different things. A record has a definition
2412 // as soon as we begin to parse the definition. That definition is
2413 // not a complete definition (which is what isDefinition() tests)
2414 // until we *finish* parsing the definition.
Sean Callanan56c19892012-02-08 00:04:52 +00002415
2416 if (D->hasExternalLexicalStorage() && !D->getDefinition())
2417 getExternalSource()->CompleteType(const_cast<RecordDecl*>(D));
2418
Anders Carlssondf291d82010-05-26 04:56:53 +00002419 D = D->getDefinition();
2420 assert(D && "Cannot get layout of forward declarations!");
John McCallf937c022011-10-07 06:10:15 +00002421 assert(D->isCompleteDefinition() && "Cannot layout type before complete!");
Anders Carlssondf291d82010-05-26 04:56:53 +00002422
2423 // Look up this layout, if already laid out, return what we have.
2424 // Note that we can't save a reference to the entry because this function
2425 // is recursive.
2426 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
2427 if (Entry) return *Entry;
2428
Anders Carlssond2954862010-05-26 05:10:47 +00002429 const ASTRecordLayout *NewEntry;
2430
2431 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
Anders Carlssonc121b4e2010-05-27 00:07:01 +00002432 EmptySubobjectMap EmptySubobjects(*this, RD);
John McCall0153cd32011-11-08 04:01:03 +00002433 RecordLayoutBuilder Builder(*this, &EmptySubobjects);
2434 Builder.Layout(RD);
Anders Carlsson439edd12010-05-27 05:41:06 +00002435
John McCall0153cd32011-11-08 04:01:03 +00002436 // MSVC gives the vb-table pointer an alignment equal to that of
2437 // the non-virtual part of the structure. That's an inherently
2438 // multi-pass operation. If our first pass doesn't give us
2439 // adequate alignment, try again with the specified minimum
2440 // alignment. This is *much* more maintainable than computing the
2441 // alignment in advance in a separately-coded pass; it's also
2442 // significantly more efficient in the common case where the
2443 // vb-table doesn't need extra padding.
2444 if (Builder.VBPtrOffset != CharUnits::fromQuantity(-1) &&
2445 (Builder.VBPtrOffset % Builder.NonVirtualAlignment) != 0) {
2446 Builder.resetWithTargetAlignment(Builder.NonVirtualAlignment);
2447 Builder.Layout(RD);
Eli Friedman84d2d3a2011-09-27 19:12:27 +00002448 }
2449
Anders Carlssond2954862010-05-26 05:10:47 +00002450 // FIXME: This is not always correct. See the part about bitfields at
2451 // http://www.codesourcery.com/public/cxx-abi/abi.html#POD for more info.
2452 // FIXME: IsPODForThePurposeOfLayout should be stored in the record layout.
Eli Friedman84d2d3a2011-09-27 19:12:27 +00002453 // This does not affect the calculations of MSVC layouts
2454 bool IsPODForThePurposeOfLayout =
John McCall0153cd32011-11-08 04:01:03 +00002455 (!Builder.isMicrosoftCXXABI() && cast<CXXRecordDecl>(D)->isPOD());
Anders Carlssond2954862010-05-26 05:10:47 +00002456
2457 // FIXME: This should be done in FinalizeLayout.
Ken Dyck1b4420e2011-02-28 02:01:38 +00002458 CharUnits DataSize =
John McCall0153cd32011-11-08 04:01:03 +00002459 IsPODForThePurposeOfLayout ? Builder.getSize() : Builder.getDataSize();
Ken Dyck1b4420e2011-02-28 02:01:38 +00002460 CharUnits NonVirtualSize =
John McCall0153cd32011-11-08 04:01:03 +00002461 IsPODForThePurposeOfLayout ? DataSize : Builder.NonVirtualSize;
Anders Carlssond2954862010-05-26 05:10:47 +00002462
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002463 NewEntry =
John McCall0153cd32011-11-08 04:01:03 +00002464 new (*this) ASTRecordLayout(*this, Builder.getSize(),
2465 Builder.Alignment,
John McCalle42a3362012-05-01 08:55:32 +00002466 Builder.HasOwnVFPtr,
John McCall0153cd32011-11-08 04:01:03 +00002467 Builder.VBPtrOffset,
Ken Dyck1b4420e2011-02-28 02:01:38 +00002468 DataSize,
John McCall0153cd32011-11-08 04:01:03 +00002469 Builder.FieldOffsets.data(),
2470 Builder.FieldOffsets.size(),
Ken Dyckaf1c83f2011-02-16 01:52:01 +00002471 NonVirtualSize,
John McCall0153cd32011-11-08 04:01:03 +00002472 Builder.NonVirtualAlignment,
Anders Carlssonc121b4e2010-05-27 00:07:01 +00002473 EmptySubobjects.SizeOfLargestEmptySubobject,
John McCall0153cd32011-11-08 04:01:03 +00002474 Builder.PrimaryBase,
2475 Builder.PrimaryBaseIsVirtual,
2476 Builder.Bases, Builder.VBases);
Anders Carlssond2954862010-05-26 05:10:47 +00002477 } else {
John McCall0153cd32011-11-08 04:01:03 +00002478 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
Anders Carlssond2954862010-05-26 05:10:47 +00002479 Builder.Layout(D);
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002480
Anders Carlssond2954862010-05-26 05:10:47 +00002481 NewEntry =
Ken Dyck1b4420e2011-02-28 02:01:38 +00002482 new (*this) ASTRecordLayout(*this, Builder.getSize(),
Ken Dyck4731d5b2011-02-16 02:05:21 +00002483 Builder.Alignment,
Ken Dyck1b4420e2011-02-28 02:01:38 +00002484 Builder.getSize(),
Anders Carlssond2954862010-05-26 05:10:47 +00002485 Builder.FieldOffsets.data(),
2486 Builder.FieldOffsets.size());
2487 }
2488
Anders Carlssondf291d82010-05-26 04:56:53 +00002489 ASTRecordLayouts[D] = NewEntry;
2490
David Blaikiebbafb8a2012-03-11 07:00:24 +00002491 if (getLangOpts().DumpRecordLayouts) {
Anders Carlssondf291d82010-05-26 04:56:53 +00002492 llvm::errs() << "\n*** Dumping AST Record Layout\n";
David Blaikiebbafb8a2012-03-11 07:00:24 +00002493 DumpRecordLayout(D, llvm::errs(), getLangOpts().DumpRecordLayoutsSimple);
Anders Carlssondf291d82010-05-26 04:56:53 +00002494 }
2495
2496 return *NewEntry;
2497}
2498
2499const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) {
2500 RD = cast<CXXRecordDecl>(RD->getDefinition());
2501 assert(RD && "Cannot get key function for forward declarations!");
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002502
Anders Carlssondf291d82010-05-26 04:56:53 +00002503 const CXXMethodDecl *&Entry = KeyFunctions[RD];
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002504 if (!Entry)
Anders Carlssonc2226202010-05-26 05:58:59 +00002505 Entry = RecordLayoutBuilder::ComputeKeyFunction(RD);
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002506
Anders Carlssondf291d82010-05-26 04:56:53 +00002507 return Entry;
2508}
2509
Richard Smithdafff942012-01-14 04:30:29 +00002510static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) {
2511 const ASTRecordLayout &Layout = C.getASTRecordLayout(FD->getParent());
2512 return Layout.getFieldOffset(FD->getFieldIndex());
2513}
2514
2515uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const {
2516 uint64_t OffsetInBits;
2517 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
2518 OffsetInBits = ::getFieldOffset(*this, FD);
2519 } else {
2520 const IndirectFieldDecl *IFD = cast<IndirectFieldDecl>(VD);
2521
2522 OffsetInBits = 0;
2523 for (IndirectFieldDecl::chain_iterator CI = IFD->chain_begin(),
2524 CE = IFD->chain_end();
2525 CI != CE; ++CI)
2526 OffsetInBits += ::getFieldOffset(*this, cast<FieldDecl>(*CI));
2527 }
2528
2529 return OffsetInBits;
2530}
2531
Eric Christopher8a39a012011-10-05 06:00:51 +00002532/// getObjCLayout - Get or compute information about the layout of the
2533/// given interface.
Anders Carlssondf291d82010-05-26 04:56:53 +00002534///
2535/// \param Impl - If given, also include the layout of the interface's
2536/// implementation. This may differ by including synthesized ivars.
2537const ASTRecordLayout &
2538ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
Jay Foad39c79802011-01-12 09:06:06 +00002539 const ObjCImplementationDecl *Impl) const {
Douglas Gregor64d92572011-12-20 15:50:13 +00002540 // Retrieve the definition
Sean Callanand9a909c2012-03-15 16:33:08 +00002541 if (D->hasExternalLexicalStorage() && !D->getDefinition())
2542 getExternalSource()->CompleteType(const_cast<ObjCInterfaceDecl*>(D));
Douglas Gregor64d92572011-12-20 15:50:13 +00002543 D = D->getDefinition();
2544 assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!");
Anders Carlssondf291d82010-05-26 04:56:53 +00002545
2546 // Look up this layout, if already laid out, return what we have.
Roman Divackye6377112012-09-06 15:59:27 +00002547 const ObjCContainerDecl *Key =
2548 Impl ? (const ObjCContainerDecl*) Impl : (const ObjCContainerDecl*) D;
Anders Carlssondf291d82010-05-26 04:56:53 +00002549 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
2550 return *Entry;
2551
2552 // Add in synthesized ivar count if laying out an implementation.
2553 if (Impl) {
2554 unsigned SynthCount = CountNonClassIvars(D);
2555 // If there aren't any sythesized ivars then reuse the interface
2556 // entry. Note we can't cache this because we simply free all
2557 // entries later; however we shouldn't look up implementations
2558 // frequently.
2559 if (SynthCount == 0)
2560 return getObjCLayout(D, 0);
2561 }
2562
John McCall0153cd32011-11-08 04:01:03 +00002563 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
Anders Carlsson6ed3a9a2010-05-26 05:04:25 +00002564 Builder.Layout(D);
2565
Anders Carlssondf291d82010-05-26 04:56:53 +00002566 const ASTRecordLayout *NewEntry =
Ken Dyck1b4420e2011-02-28 02:01:38 +00002567 new (*this) ASTRecordLayout(*this, Builder.getSize(),
Ken Dyck4731d5b2011-02-16 02:05:21 +00002568 Builder.Alignment,
Ken Dyck1b4420e2011-02-28 02:01:38 +00002569 Builder.getDataSize(),
Anders Carlsson6ed3a9a2010-05-26 05:04:25 +00002570 Builder.FieldOffsets.data(),
2571 Builder.FieldOffsets.size());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002572
Anders Carlssondf291d82010-05-26 04:56:53 +00002573 ObjCLayouts[Key] = NewEntry;
2574
2575 return *NewEntry;
2576}
2577
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002578static void PrintOffset(raw_ostream &OS,
Anders Carlsson3f018712010-10-31 23:45:59 +00002579 CharUnits Offset, unsigned IndentLevel) {
Benjamin Kramer96ad7172011-11-05 09:02:52 +00002580 OS << llvm::format("%4" PRId64 " | ", (int64_t)Offset.getQuantity());
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002581 OS.indent(IndentLevel * 2);
2582}
2583
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00002584static void PrintIndentNoOffset(raw_ostream &OS, unsigned IndentLevel) {
2585 OS << " | ";
2586 OS.indent(IndentLevel * 2);
2587}
2588
Chris Lattner0e62c1c2011-07-23 10:55:15 +00002589static void DumpCXXRecordLayout(raw_ostream &OS,
Jay Foad39c79802011-01-12 09:06:06 +00002590 const CXXRecordDecl *RD, const ASTContext &C,
Anders Carlsson3f018712010-10-31 23:45:59 +00002591 CharUnits Offset,
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002592 unsigned IndentLevel,
2593 const char* Description,
2594 bool IncludeVirtualBases) {
Anders Carlsson3f018712010-10-31 23:45:59 +00002595 const ASTRecordLayout &Layout = C.getASTRecordLayout(RD);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002596
2597 PrintOffset(OS, Offset, IndentLevel);
Dan Gohman145f3f12010-04-19 16:39:44 +00002598 OS << C.getTypeDeclType(const_cast<CXXRecordDecl *>(RD)).getAsString();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002599 if (Description)
2600 OS << ' ' << Description;
2601 if (RD->isEmpty())
2602 OS << " (empty)";
2603 OS << '\n';
2604
2605 IndentLevel++;
2606
Anders Carlsson3f018712010-10-31 23:45:59 +00002607 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
John McCalle42a3362012-05-01 08:55:32 +00002608 bool HasVfptr = Layout.hasOwnVFPtr();
Eli Friedman84d2d3a2011-09-27 19:12:27 +00002609 bool HasVbptr = Layout.getVBPtrOffset() != CharUnits::fromQuantity(-1);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002610
2611 // Vtable pointer.
Eli Friedman43114f92011-10-21 22:49:56 +00002612 if (RD->isDynamicClass() && !PrimaryBase &&
John McCall359b8852013-01-25 22:30:49 +00002613 !C.getTargetInfo().getCXXABI().isMicrosoft()) {
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002614 PrintOffset(OS, Offset, IndentLevel);
Benjamin Kramerb89514a2011-10-14 18:45:37 +00002615 OS << '(' << *RD << " vtable pointer)\n";
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002616 }
Eli Friedman84d2d3a2011-09-27 19:12:27 +00002617
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002618 // Dump (non-virtual) bases
2619 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
2620 E = RD->bases_end(); I != E; ++I) {
2621 assert(!I->getType()->isDependentType() &&
2622 "Cannot layout class with dependent bases.");
2623 if (I->isVirtual())
2624 continue;
2625
2626 const CXXRecordDecl *Base =
2627 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
2628
Anders Carlsson3f018712010-10-31 23:45:59 +00002629 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002630
2631 DumpCXXRecordLayout(OS, Base, C, BaseOffset, IndentLevel,
2632 Base == PrimaryBase ? "(primary base)" : "(base)",
2633 /*IncludeVirtualBases=*/false);
2634 }
Eli Friedman43114f92011-10-21 22:49:56 +00002635
2636 // vfptr and vbptr (for Microsoft C++ ABI)
2637 if (HasVfptr) {
John McCalle42a3362012-05-01 08:55:32 +00002638 PrintOffset(OS, Offset, IndentLevel);
Eli Friedman43114f92011-10-21 22:49:56 +00002639 OS << '(' << *RD << " vftable pointer)\n";
2640 }
Eli Friedman84d2d3a2011-09-27 19:12:27 +00002641 if (HasVbptr) {
2642 PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel);
Benjamin Kramerb89514a2011-10-14 18:45:37 +00002643 OS << '(' << *RD << " vbtable pointer)\n";
Eli Friedman84d2d3a2011-09-27 19:12:27 +00002644 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002645
2646 // Dump fields.
2647 uint64_t FieldNo = 0;
2648 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2649 E = RD->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +00002650 const FieldDecl &Field = **I;
Anders Carlsson3f018712010-10-31 23:45:59 +00002651 CharUnits FieldOffset = Offset +
Ken Dyck86a7fcc2011-01-18 01:56:16 +00002652 C.toCharUnitsFromBits(Layout.getFieldOffset(FieldNo));
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002653
David Blaikie2d7c57e2012-04-30 02:36:29 +00002654 if (const RecordType *RT = Field.getType()->getAs<RecordType>()) {
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002655 if (const CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2656 DumpCXXRecordLayout(OS, D, C, FieldOffset, IndentLevel,
David Blaikie2d7c57e2012-04-30 02:36:29 +00002657 Field.getName().data(),
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002658 /*IncludeVirtualBases=*/true);
2659 continue;
2660 }
2661 }
2662
2663 PrintOffset(OS, FieldOffset, IndentLevel);
David Blaikie2d7c57e2012-04-30 02:36:29 +00002664 OS << Field.getType().getAsString() << ' ' << Field << '\n';
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002665 }
2666
2667 if (!IncludeVirtualBases)
2668 return;
2669
2670 // Dump virtual bases.
John McCalle42a3362012-05-01 08:55:32 +00002671 const ASTRecordLayout::VBaseOffsetsMapTy &vtordisps =
2672 Layout.getVBaseOffsetsMap();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002673 for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
2674 E = RD->vbases_end(); I != E; ++I) {
2675 assert(I->isVirtual() && "Found non-virtual class!");
2676 const CXXRecordDecl *VBase =
2677 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
2678
Anders Carlsson3f018712010-10-31 23:45:59 +00002679 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
John McCalle42a3362012-05-01 08:55:32 +00002680
2681 if (vtordisps.find(VBase)->second.hasVtorDisp()) {
2682 PrintOffset(OS, VBaseOffset - CharUnits::fromQuantity(4), IndentLevel);
2683 OS << "(vtordisp for vbase " << *VBase << ")\n";
2684 }
2685
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002686 DumpCXXRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel,
2687 VBase == PrimaryBase ?
2688 "(primary virtual base)" : "(virtual base)",
2689 /*IncludeVirtualBases=*/false);
2690 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002691
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00002692 PrintIndentNoOffset(OS, IndentLevel - 1);
2693 OS << "[sizeof=" << Layout.getSize().getQuantity();
Ken Dyckd5090c12011-02-11 02:20:09 +00002694 OS << ", dsize=" << Layout.getDataSize().getQuantity();
Ken Dyck7ad11e72011-02-15 02:32:40 +00002695 OS << ", align=" << Layout.getAlignment().getQuantity() << '\n';
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00002696
2697 PrintIndentNoOffset(OS, IndentLevel - 1);
2698 OS << " nvsize=" << Layout.getNonVirtualSize().getQuantity();
2699 OS << ", nvalign=" << Layout.getNonVirtualAlign().getQuantity() << "]\n";
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002700 OS << '\n';
2701}
Daniel Dunbarccabe482010-04-19 20:44:53 +00002702
2703void ASTContext::DumpRecordLayout(const RecordDecl *RD,
Douglas Gregore9fc3772012-01-26 07:55:45 +00002704 raw_ostream &OS,
2705 bool Simple) const {
Daniel Dunbarccabe482010-04-19 20:44:53 +00002706 const ASTRecordLayout &Info = getASTRecordLayout(RD);
2707
2708 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Douglas Gregore9fc3772012-01-26 07:55:45 +00002709 if (!Simple)
2710 return DumpCXXRecordLayout(OS, CXXRD, *this, CharUnits(), 0, 0,
2711 /*IncludeVirtualBases=*/true);
Daniel Dunbarccabe482010-04-19 20:44:53 +00002712
2713 OS << "Type: " << getTypeDeclType(RD).getAsString() << "\n";
Douglas Gregore9fc3772012-01-26 07:55:45 +00002714 if (!Simple) {
2715 OS << "Record: ";
2716 RD->dump();
2717 }
Daniel Dunbarccabe482010-04-19 20:44:53 +00002718 OS << "\nLayout: ";
2719 OS << "<ASTRecordLayout\n";
Ken Dyckb0fcc592011-02-11 01:54:29 +00002720 OS << " Size:" << toBits(Info.getSize()) << "\n";
Ken Dyckd5090c12011-02-11 02:20:09 +00002721 OS << " DataSize:" << toBits(Info.getDataSize()) << "\n";
Ken Dyck7ad11e72011-02-15 02:32:40 +00002722 OS << " Alignment:" << toBits(Info.getAlignment()) << "\n";
Daniel Dunbarccabe482010-04-19 20:44:53 +00002723 OS << " FieldOffsets: [";
2724 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) {
2725 if (i) OS << ", ";
2726 OS << Info.getFieldOffset(i);
2727 }
2728 OS << "]>\n";
2729}