blob: 2101a5534a6bef977b2b8f5a02e586f7a608ab93 [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
Reid Kleckner8b6d0342015-02-25 19:17:45 +000058/// \brief Externally provided layout. Typically used when the AST source, such
59/// as DWARF, lacks all the information that was available at compile time, such
60/// as alignment attributes on fields and pragmas in effect.
61struct ExternalLayout {
62 ExternalLayout() : Size(0), Align(0) {}
63
64 /// \brief Overall record size in bits.
65 uint64_t Size;
66
67 /// \brief Overall record alignment in bits.
68 uint64_t Align;
69
70 /// \brief Record field offsets in bits.
71 llvm::DenseMap<const FieldDecl *, uint64_t> FieldOffsets;
72
73 /// \brief Direct, non-virtual base offsets.
74 llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsets;
75
76 /// \brief Virtual base offsets.
77 llvm::DenseMap<const CXXRecordDecl *, CharUnits> VirtualBaseOffsets;
78
79 /// Get the offset of the given field. The external source must provide
80 /// entries for all fields in the record.
81 uint64_t getExternalFieldOffset(const FieldDecl *FD) {
82 assert(FieldOffsets.count(FD) &&
83 "Field does not have an external offset");
84 return FieldOffsets[FD];
85 }
86
87 bool getExternalNVBaseOffset(const CXXRecordDecl *RD, CharUnits &BaseOffset) {
88 auto Known = BaseOffsets.find(RD);
89 if (Known == BaseOffsets.end())
90 return false;
91 BaseOffset = Known->second;
92 return true;
93 }
94
95 bool getExternalVBaseOffset(const CXXRecordDecl *RD, CharUnits &BaseOffset) {
96 auto Known = VirtualBaseOffsets.find(RD);
97 if (Known == VirtualBaseOffsets.end())
98 return false;
99 BaseOffset = Known->second;
100 return true;
101 }
102};
103
Anders Carlssonf58de112010-05-26 15:32:58 +0000104/// EmptySubobjectMap - Keeps track of which empty subobjects exist at different
105/// offsets while laying out a C++ class.
106class EmptySubobjectMap {
Jay Foad39c79802011-01-12 09:06:06 +0000107 const ASTContext &Context;
Anders Carlsson233e2722010-10-31 21:54:55 +0000108 uint64_t CharWidth;
109
Anders Carlssonf58de112010-05-26 15:32:58 +0000110 /// Class - The class whose empty entries we're keeping track of.
111 const CXXRecordDecl *Class;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000112
Anders Carlsson439edd12010-05-27 05:41:06 +0000113 /// EmptyClassOffsets - A map from offsets to empty record decls.
Benjamin Kramer834652a2014-05-03 18:44:26 +0000114 typedef llvm::TinyPtrVector<const CXXRecordDecl *> ClassVectorTy;
Anders Carlssonf8f756d2010-10-31 21:22:43 +0000115 typedef llvm::DenseMap<CharUnits, ClassVectorTy> EmptyClassOffsetsMapTy;
Anders Carlsson439edd12010-05-27 05:41:06 +0000116 EmptyClassOffsetsMapTy EmptyClassOffsets;
117
Anders Carlssoncc5de092010-06-08 15:56:03 +0000118 /// MaxEmptyClassOffset - The highest offset known to contain an empty
119 /// base subobject.
Anders Carlsson725190f2010-10-31 21:39:24 +0000120 CharUnits MaxEmptyClassOffset;
Anders Carlssoncc5de092010-06-08 15:56:03 +0000121
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000122 /// ComputeEmptySubobjectSizes - Compute the size of the largest base or
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000123 /// member subobject that is empty.
124 void ComputeEmptySubobjectSizes();
Anders Carlsson439edd12010-05-27 05:41:06 +0000125
Anders Carlsson725190f2010-10-31 21:39:24 +0000126 void AddSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000127
Anders Carlssona7f3cdb2010-05-28 21:24:37 +0000128 void UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000129 CharUnits Offset, bool PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +0000130
Anders Carlssondb319762010-05-27 18:20:57 +0000131 void UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
132 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000133 CharUnits Offset);
134 void UpdateEmptyFieldSubobjects(const FieldDecl *FD, CharUnits Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000135
Anders Carlssoncc5de092010-06-08 15:56:03 +0000136 /// AnyEmptySubobjectsBeyondOffset - Returns whether there are any empty
137 /// subobjects beyond the given offset.
Anders Carlsson725190f2010-10-31 21:39:24 +0000138 bool AnyEmptySubobjectsBeyondOffset(CharUnits Offset) const {
Anders Carlssoncc5de092010-06-08 15:56:03 +0000139 return Offset <= MaxEmptyClassOffset;
140 }
141
Anders Carlsson233e2722010-10-31 21:54:55 +0000142 CharUnits
143 getFieldOffset(const ASTRecordLayout &Layout, unsigned FieldNo) const {
144 uint64_t FieldOffset = Layout.getFieldOffset(FieldNo);
145 assert(FieldOffset % CharWidth == 0 &&
146 "Field offset not at char boundary!");
147
Ken Dyck7c4026b2011-01-24 01:28:50 +0000148 return Context.toCharUnitsFromBits(FieldOffset);
Anders Carlssonf8f756d2010-10-31 21:22:43 +0000149 }
Anders Carlssonf8f756d2010-10-31 21:22:43 +0000150
Charles Davisc2c576a2010-08-19 00:55:19 +0000151protected:
Anders Carlsson725190f2010-10-31 21:39:24 +0000152 bool CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
153 CharUnits Offset) const;
Charles Davisc2c576a2010-08-19 00:55:19 +0000154
155 bool CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000156 CharUnits Offset);
Charles Davisc2c576a2010-08-19 00:55:19 +0000157
158 bool CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
159 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000160 CharUnits Offset) const;
Charles Davisc2c576a2010-08-19 00:55:19 +0000161 bool CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
Anders Carlsson233e2722010-10-31 21:54:55 +0000162 CharUnits Offset) const;
Charles Davisc2c576a2010-08-19 00:55:19 +0000163
Anders Carlssonf58de112010-05-26 15:32:58 +0000164public:
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000165 /// This holds the size of the largest empty subobject (either a base
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000166 /// or a member). Will be zero if the record being built doesn't contain
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000167 /// any empty classes.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000168 CharUnits SizeOfLargestEmptySubobject;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000169
Jay Foad39c79802011-01-12 09:06:06 +0000170 EmptySubobjectMap(const ASTContext &Context, const CXXRecordDecl *Class)
Anders Carlsson28466ab2010-10-31 22:13:23 +0000171 : Context(Context), CharWidth(Context.getCharWidth()), Class(Class) {
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000172 ComputeEmptySubobjectSizes();
173 }
174
175 /// CanPlaceBaseAtOffset - Return whether the given base class can be placed
176 /// at the given offset.
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000177 /// Returns false if placing the record will result in two components
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000178 /// (direct or indirect) of the same type having the same offset.
Anders Carlssoncc5de092010-06-08 15:56:03 +0000179 bool CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000180 CharUnits Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000181
182 /// CanPlaceFieldAtOffset - Return whether a field can be placed at the given
183 /// offset.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000184 bool CanPlaceFieldAtOffset(const FieldDecl *FD, CharUnits Offset);
Anders Carlssonf58de112010-05-26 15:32:58 +0000185};
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000186
187void EmptySubobjectMap::ComputeEmptySubobjectSizes() {
188 // Check the bases.
David Majnemerc964b4b2014-07-16 06:04:00 +0000189 for (const CXXBaseSpecifier &Base : Class->bases()) {
190 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000191
Anders Carlsson28466ab2010-10-31 22:13:23 +0000192 CharUnits EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000193 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
194 if (BaseDecl->isEmpty()) {
195 // If the class decl is empty, get its size.
Ken Dyckc8ae5502011-02-09 01:59:34 +0000196 EmptySize = Layout.getSize();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000197 } else {
198 // Otherwise, we get the largest empty subobject for the decl.
199 EmptySize = Layout.getSizeOfLargestEmptySubobject();
200 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000201
Anders Carlsson28466ab2010-10-31 22:13:23 +0000202 if (EmptySize > SizeOfLargestEmptySubobject)
203 SizeOfLargestEmptySubobject = EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000204 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000205
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000206 // Check the fields.
David Majnemerc964b4b2014-07-16 06:04:00 +0000207 for (const FieldDecl *FD : Class->fields()) {
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000208 const RecordType *RT =
David Majnemerc964b4b2014-07-16 06:04:00 +0000209 Context.getBaseElementType(FD->getType())->getAs<RecordType>();
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000210
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000211 // We only care about record types.
212 if (!RT)
213 continue;
214
Anders Carlsson28466ab2010-10-31 22:13:23 +0000215 CharUnits EmptySize;
Reid Klecknercd612ab2014-04-11 16:57:42 +0000216 const CXXRecordDecl *MemberDecl = RT->getAsCXXRecordDecl();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000217 const ASTRecordLayout &Layout = Context.getASTRecordLayout(MemberDecl);
218 if (MemberDecl->isEmpty()) {
219 // If the class decl is empty, get its size.
Ken Dyckc8ae5502011-02-09 01:59:34 +0000220 EmptySize = Layout.getSize();
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000221 } else {
222 // Otherwise, we get the largest empty subobject for the decl.
223 EmptySize = Layout.getSizeOfLargestEmptySubobject();
224 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000225
Anders Carlsson28466ab2010-10-31 22:13:23 +0000226 if (EmptySize > SizeOfLargestEmptySubobject)
227 SizeOfLargestEmptySubobject = EmptySize;
Anders Carlssonc5ca1f72010-05-26 15:54:25 +0000228 }
229}
230
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000231bool
Anders Carlssondb319762010-05-27 18:20:57 +0000232EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
Anders Carlsson725190f2010-10-31 21:39:24 +0000233 CharUnits Offset) const {
Anders Carlssondb319762010-05-27 18:20:57 +0000234 // We only need to check empty bases.
235 if (!RD->isEmpty())
236 return true;
237
Anders Carlsson725190f2010-10-31 21:39:24 +0000238 EmptyClassOffsetsMapTy::const_iterator I = EmptyClassOffsets.find(Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000239 if (I == EmptyClassOffsets.end())
240 return true;
David Majnemerc964b4b2014-07-16 06:04:00 +0000241
242 const ClassVectorTy &Classes = I->second;
Anders Carlssondb319762010-05-27 18:20:57 +0000243 if (std::find(Classes.begin(), Classes.end(), RD) == Classes.end())
244 return true;
245
246 // There is already an empty class of the same type at this offset.
247 return false;
248}
249
250void EmptySubobjectMap::AddSubobjectAtOffset(const CXXRecordDecl *RD,
Anders Carlsson725190f2010-10-31 21:39:24 +0000251 CharUnits Offset) {
Anders Carlssondb319762010-05-27 18:20:57 +0000252 // We only care about empty bases.
253 if (!RD->isEmpty())
254 return;
255
Reid Kleckner369f3162013-05-14 20:30:42 +0000256 // If we have empty structures inside a union, we can assign both
Rafael Espindola7bcde192010-12-29 23:02:58 +0000257 // the same offset. Just avoid pushing them twice in the list.
David Majnemerc964b4b2014-07-16 06:04:00 +0000258 ClassVectorTy &Classes = EmptyClassOffsets[Offset];
Rafael Espindola7bcde192010-12-29 23:02:58 +0000259 if (std::find(Classes.begin(), Classes.end(), RD) != Classes.end())
260 return;
261
Anders Carlssondb319762010-05-27 18:20:57 +0000262 Classes.push_back(RD);
Anders Carlssoncc5de092010-06-08 15:56:03 +0000263
264 // Update the empty class offset.
Anders Carlsson725190f2010-10-31 21:39:24 +0000265 if (Offset > MaxEmptyClassOffset)
266 MaxEmptyClassOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000267}
268
269bool
Anders Carlsson28466ab2010-10-31 22:13:23 +0000270EmptySubobjectMap::CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
271 CharUnits Offset) {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000272 // We don't have to keep looking past the maximum offset that's known to
273 // contain an empty class.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000274 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000275 return true;
276
Anders Carlsson28466ab2010-10-31 22:13:23 +0000277 if (!CanPlaceSubobjectAtOffset(Info->Class, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000278 return false;
279
Anders Carlsson439edd12010-05-27 05:41:06 +0000280 // Traverse all non-virtual bases.
Anders Carlssona7774a62010-05-29 21:10:24 +0000281 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
David Majnemerc964b4b2014-07-16 06:04:00 +0000282 for (const BaseSubobjectInfo *Base : Info->Bases) {
Anders Carlsson439edd12010-05-27 05:41:06 +0000283 if (Base->IsVirtual)
284 continue;
285
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000286 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlsson439edd12010-05-27 05:41:06 +0000287
288 if (!CanPlaceBaseSubobjectAtOffset(Base, BaseOffset))
289 return false;
290 }
291
Anders Carlssone3c24c72010-05-29 17:35:14 +0000292 if (Info->PrimaryVirtualBaseInfo) {
293 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
Anders Carlsson439edd12010-05-27 05:41:06 +0000294
295 if (Info == PrimaryVirtualBaseInfo->Derived) {
296 if (!CanPlaceBaseSubobjectAtOffset(PrimaryVirtualBaseInfo, Offset))
297 return false;
298 }
299 }
300
Anders Carlssondb319762010-05-27 18:20:57 +0000301 // Traverse all member variables.
302 unsigned FieldNo = 0;
303 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
304 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000305 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000306 continue;
David Majnemerc964b4b2014-07-16 06:04:00 +0000307
Anders Carlsson28466ab2010-10-31 22:13:23 +0000308 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
David Blaikie40ed2972012-06-06 20:45:41 +0000309 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000310 return false;
311 }
David Majnemerc964b4b2014-07-16 06:04:00 +0000312
Anders Carlsson439edd12010-05-27 05:41:06 +0000313 return true;
314}
315
Anders Carlssona7f3cdb2010-05-28 21:24:37 +0000316void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000317 CharUnits Offset,
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000318 bool PlacingEmptyBase) {
319 if (!PlacingEmptyBase && Offset >= SizeOfLargestEmptySubobject) {
320 // We know that the only empty subobjects that can conflict with empty
321 // subobject of non-empty bases, are empty bases that can be placed at
322 // offset zero. Because of this, we only need to keep track of empty base
323 // subobjects with offsets less than the size of the largest empty
324 // subobject for our class.
325 return;
326 }
327
Anders Carlsson28466ab2010-10-31 22:13:23 +0000328 AddSubobjectAtOffset(Info->Class, Offset);
Anders Carlssona7774a62010-05-29 21:10:24 +0000329
Anders Carlsson439edd12010-05-27 05:41:06 +0000330 // Traverse all non-virtual bases.
Anders Carlssona7774a62010-05-29 21:10:24 +0000331 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
David Majnemerc964b4b2014-07-16 06:04:00 +0000332 for (const BaseSubobjectInfo *Base : Info->Bases) {
Anders Carlsson439edd12010-05-27 05:41:06 +0000333 if (Base->IsVirtual)
334 continue;
Anders Carlssona7774a62010-05-29 21:10:24 +0000335
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000336 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000337 UpdateEmptyBaseSubobjects(Base, BaseOffset, PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +0000338 }
339
Anders Carlssone3c24c72010-05-29 17:35:14 +0000340 if (Info->PrimaryVirtualBaseInfo) {
341 BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
Anders Carlsson439edd12010-05-27 05:41:06 +0000342
343 if (Info == PrimaryVirtualBaseInfo->Derived)
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000344 UpdateEmptyBaseSubobjects(PrimaryVirtualBaseInfo, Offset,
345 PlacingEmptyBase);
Anders Carlsson439edd12010-05-27 05:41:06 +0000346 }
Anders Carlssondb319762010-05-27 18:20:57 +0000347
Anders Carlssondb319762010-05-27 18:20:57 +0000348 // Traverse all member variables.
349 unsigned FieldNo = 0;
350 for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
351 E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000352 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000353 continue;
Anders Carlssona7774a62010-05-29 21:10:24 +0000354
Anders Carlsson28466ab2010-10-31 22:13:23 +0000355 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
David Blaikie40ed2972012-06-06 20:45:41 +0000356 UpdateEmptyFieldSubobjects(*I, FieldOffset);
Anders Carlssondb319762010-05-27 18:20:57 +0000357 }
Anders Carlsson439edd12010-05-27 05:41:06 +0000358}
359
Anders Carlssona60b86a2010-05-29 20:49:49 +0000360bool EmptySubobjectMap::CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000361 CharUnits Offset) {
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000362 // If we know this class doesn't have any empty subobjects we don't need to
363 // bother checking.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000364 if (SizeOfLargestEmptySubobject.isZero())
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000365 return true;
366
Anders Carlsson439edd12010-05-27 05:41:06 +0000367 if (!CanPlaceBaseSubobjectAtOffset(Info, Offset))
368 return false;
Anders Carlssondb319762010-05-27 18:20:57 +0000369
370 // We are able to place the base at this offset. Make sure to update the
371 // empty base subobject map.
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000372 UpdateEmptyBaseSubobjects(Info, Offset, Info->Class->isEmpty());
Anders Carlssonc121b4e2010-05-27 00:07:01 +0000373 return true;
374}
375
Anders Carlssondb319762010-05-27 18:20:57 +0000376bool
377EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
378 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000379 CharUnits Offset) const {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000380 // We don't have to keep looking past the maximum offset that's known to
381 // contain an empty class.
Anders Carlsson28466ab2010-10-31 22:13:23 +0000382 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000383 return true;
384
Anders Carlsson28466ab2010-10-31 22:13:23 +0000385 if (!CanPlaceSubobjectAtOffset(RD, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000386 return false;
387
388 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
389
390 // Traverse all non-virtual bases.
David Majnemerc964b4b2014-07-16 06:04:00 +0000391 for (const CXXBaseSpecifier &Base : RD->bases()) {
392 if (Base.isVirtual())
Anders Carlssondb319762010-05-27 18:20:57 +0000393 continue;
394
David Majnemerc964b4b2014-07-16 06:04:00 +0000395 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Anders Carlssondb319762010-05-27 18:20:57 +0000396
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000397 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
Anders Carlssondb319762010-05-27 18:20:57 +0000398 if (!CanPlaceFieldSubobjectAtOffset(BaseDecl, Class, BaseOffset))
399 return false;
400 }
401
Anders Carlsson44687202010-06-08 19:09:24 +0000402 if (RD == Class) {
403 // This is the most derived class, traverse virtual bases as well.
David Majnemerc964b4b2014-07-16 06:04:00 +0000404 for (const CXXBaseSpecifier &Base : RD->vbases()) {
405 const CXXRecordDecl *VBaseDecl = Base.getType()->getAsCXXRecordDecl();
Reid Klecknercd612ab2014-04-11 16:57:42 +0000406
Anders Carlsson3f018712010-10-31 23:45:59 +0000407 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
Anders Carlsson44687202010-06-08 19:09:24 +0000408 if (!CanPlaceFieldSubobjectAtOffset(VBaseDecl, Class, VBaseOffset))
409 return false;
410 }
411 }
412
Anders Carlssondb319762010-05-27 18:20:57 +0000413 // Traverse all member variables.
414 unsigned FieldNo = 0;
415 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
416 I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000417 if (I->isBitField())
Anders Carlsson233e2722010-10-31 21:54:55 +0000418 continue;
419
Anders Carlsson28466ab2010-10-31 22:13:23 +0000420 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
Anders Carlssondb319762010-05-27 18:20:57 +0000421
David Blaikie40ed2972012-06-06 20:45:41 +0000422 if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000423 return false;
424 }
425
426 return true;
427}
428
Anders Carlsson233e2722010-10-31 21:54:55 +0000429bool
430EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
431 CharUnits Offset) const {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000432 // We don't have to keep looking past the maximum offset that's known to
433 // contain an empty class.
Anders Carlsson233e2722010-10-31 21:54:55 +0000434 if (!AnyEmptySubobjectsBeyondOffset(Offset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000435 return true;
436
Anders Carlssondb319762010-05-27 18:20:57 +0000437 QualType T = FD->getType();
Reid Klecknercd612ab2014-04-11 16:57:42 +0000438 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
Anders Carlsson28466ab2010-10-31 22:13:23 +0000439 return CanPlaceFieldSubobjectAtOffset(RD, RD, Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000440
441 // If we have an array type we need to look at every element.
442 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
443 QualType ElemTy = Context.getBaseElementType(AT);
444 const RecordType *RT = ElemTy->getAs<RecordType>();
445 if (!RT)
446 return true;
Reid Klecknercd612ab2014-04-11 16:57:42 +0000447
448 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
Anders Carlssondb319762010-05-27 18:20:57 +0000449 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
450
451 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
Anders Carlsson233e2722010-10-31 21:54:55 +0000452 CharUnits ElementOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000453 for (uint64_t I = 0; I != NumElements; ++I) {
Anders Carlsson45c1d282010-06-08 16:20:35 +0000454 // We don't have to keep looking past the maximum offset that's known to
455 // contain an empty class.
Anders Carlsson233e2722010-10-31 21:54:55 +0000456 if (!AnyEmptySubobjectsBeyondOffset(ElementOffset))
Anders Carlsson45c1d282010-06-08 16:20:35 +0000457 return true;
458
Anders Carlsson28466ab2010-10-31 22:13:23 +0000459 if (!CanPlaceFieldSubobjectAtOffset(RD, RD, ElementOffset))
Anders Carlssondb319762010-05-27 18:20:57 +0000460 return false;
461
Ken Dyckc8ae5502011-02-09 01:59:34 +0000462 ElementOffset += Layout.getSize();
Anders Carlssondb319762010-05-27 18:20:57 +0000463 }
464 }
465
466 return true;
467}
468
469bool
Anders Carlsson28466ab2010-10-31 22:13:23 +0000470EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl *FD,
471 CharUnits Offset) {
472 if (!CanPlaceFieldSubobjectAtOffset(FD, Offset))
Anders Carlssondb319762010-05-27 18:20:57 +0000473 return false;
474
475 // We are able to place the member variable at this offset.
476 // Make sure to update the empty base subobject map.
477 UpdateEmptyFieldSubobjects(FD, Offset);
478 return true;
479}
480
481void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
482 const CXXRecordDecl *Class,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000483 CharUnits Offset) {
Anders Carlssonae111dc2010-06-13 17:49:16 +0000484 // We know that the only empty subobjects that can conflict with empty
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000485 // field subobjects are subobjects of empty bases that can be placed at offset
Anders Carlssonae111dc2010-06-13 17:49:16 +0000486 // zero. Because of this, we only need to keep track of empty field
487 // subobjects with offsets less than the size of the largest empty
488 // subobject for our class.
489 if (Offset >= SizeOfLargestEmptySubobject)
490 return;
491
Anders Carlsson28466ab2010-10-31 22:13:23 +0000492 AddSubobjectAtOffset(RD, Offset);
Anders Carlssondb319762010-05-27 18:20:57 +0000493
494 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
495
496 // Traverse all non-virtual bases.
David Majnemerc964b4b2014-07-16 06:04:00 +0000497 for (const CXXBaseSpecifier &Base : RD->bases()) {
498 if (Base.isVirtual())
Anders Carlssondb319762010-05-27 18:20:57 +0000499 continue;
500
David Majnemerc964b4b2014-07-16 06:04:00 +0000501 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Anders Carlssondb319762010-05-27 18:20:57 +0000502
Anders Carlsson0a14ee92010-11-01 00:21:58 +0000503 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
Anders Carlssondb319762010-05-27 18:20:57 +0000504 UpdateEmptyFieldSubobjects(BaseDecl, Class, BaseOffset);
505 }
506
Anders Carlsson44687202010-06-08 19:09:24 +0000507 if (RD == Class) {
508 // This is the most derived class, traverse virtual bases as well.
David Majnemerc964b4b2014-07-16 06:04:00 +0000509 for (const CXXBaseSpecifier &Base : RD->vbases()) {
510 const CXXRecordDecl *VBaseDecl = Base.getType()->getAsCXXRecordDecl();
Reid Klecknercd612ab2014-04-11 16:57:42 +0000511
Anders Carlsson3f018712010-10-31 23:45:59 +0000512 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
Anders Carlsson44687202010-06-08 19:09:24 +0000513 UpdateEmptyFieldSubobjects(VBaseDecl, Class, VBaseOffset);
514 }
515 }
516
Anders Carlssondb319762010-05-27 18:20:57 +0000517 // Traverse all member variables.
518 unsigned FieldNo = 0;
519 for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
520 I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +0000521 if (I->isBitField())
Anders Carlsson09814d32010-11-01 15:14:51 +0000522 continue;
523
Anders Carlsson28466ab2010-10-31 22:13:23 +0000524 CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
Anders Carlssondb319762010-05-27 18:20:57 +0000525
David Blaikie40ed2972012-06-06 20:45:41 +0000526 UpdateEmptyFieldSubobjects(*I, FieldOffset);
Anders Carlssondb319762010-05-27 18:20:57 +0000527 }
528}
529
530void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const FieldDecl *FD,
Anders Carlsson28466ab2010-10-31 22:13:23 +0000531 CharUnits Offset) {
Anders Carlssondb319762010-05-27 18:20:57 +0000532 QualType T = FD->getType();
Reid Klecknercd612ab2014-04-11 16:57:42 +0000533 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
Anders Carlssondb319762010-05-27 18:20:57 +0000534 UpdateEmptyFieldSubobjects(RD, RD, Offset);
535 return;
536 }
537
538 // If we have an array type we need to update every element.
539 if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
540 QualType ElemTy = Context.getBaseElementType(AT);
541 const RecordType *RT = ElemTy->getAs<RecordType>();
542 if (!RT)
543 return;
Reid Klecknercd612ab2014-04-11 16:57:42 +0000544
545 const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
Anders Carlssondb319762010-05-27 18:20:57 +0000546 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
547
548 uint64_t NumElements = Context.getConstantArrayElementCount(AT);
Anders Carlsson28466ab2010-10-31 22:13:23 +0000549 CharUnits ElementOffset = Offset;
Anders Carlssondb319762010-05-27 18:20:57 +0000550
551 for (uint64_t I = 0; I != NumElements; ++I) {
Anders Carlssonae111dc2010-06-13 17:49:16 +0000552 // We know that the only empty subobjects that can conflict with empty
Anders Carlssoncc59cc52010-06-13 18:00:18 +0000553 // field subobjects are subobjects of empty bases that can be placed at
Anders Carlssonae111dc2010-06-13 17:49:16 +0000554 // offset zero. Because of this, we only need to keep track of empty field
555 // subobjects with offsets less than the size of the largest empty
556 // subobject for our class.
557 if (ElementOffset >= SizeOfLargestEmptySubobject)
558 return;
559
Anders Carlssondb319762010-05-27 18:20:57 +0000560 UpdateEmptyFieldSubobjects(RD, RD, ElementOffset);
Ken Dyckc8ae5502011-02-09 01:59:34 +0000561 ElementOffset += Layout.getSize();
Anders Carlssondb319762010-05-27 18:20:57 +0000562 }
563 }
564}
565
John McCalle42a3362012-05-01 08:55:32 +0000566typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> ClassSetTy;
567
Anders Carlssonc2226202010-05-26 05:58:59 +0000568class RecordLayoutBuilder {
Charles Davisc2c576a2010-08-19 00:55:19 +0000569protected:
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000570 // FIXME: Remove this and make the appropriate fields public.
571 friend class clang::ASTContext;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000572
Jay Foad39c79802011-01-12 09:06:06 +0000573 const ASTContext &Context;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000574
Anders Carlssonf58de112010-05-26 15:32:58 +0000575 EmptySubobjectMap *EmptySubobjects;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000576
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000577 /// Size - The current size of the record layout.
578 uint64_t Size;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000579
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000580 /// Alignment - The current alignment of the record layout.
Ken Dyck4731d5b2011-02-16 02:05:21 +0000581 CharUnits Alignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000582
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000583 /// \brief The alignment if attribute packed is not used.
Ken Dyck1300b3b2011-02-16 02:11:31 +0000584 CharUnits UnpackedAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000585
Chris Lattner0e62c1c2011-07-23 10:55:15 +0000586 SmallVector<uint64_t, 16> FieldOffsets;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000587
Douglas Gregore9fc3772012-01-26 07:55:45 +0000588 /// \brief Whether the external AST source has provided a layout for this
589 /// record.
Reid Kleckner8b6d0342015-02-25 19:17:45 +0000590 unsigned UseExternalLayout : 1;
Douglas Gregor44ba7892012-01-28 00:53:29 +0000591
592 /// \brief Whether we need to infer alignment, even when we have an
593 /// externally-provided layout.
594 unsigned InferAlignment : 1;
Douglas Gregore9fc3772012-01-26 07:55:45 +0000595
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000596 /// Packed - Whether the record is packed or not.
Daniel Dunbar6da10982010-05-27 05:45:51 +0000597 unsigned Packed : 1;
598
599 unsigned IsUnion : 1;
600
601 unsigned IsMac68kAlign : 1;
Fariborz Jahanianbcb23a12011-04-26 23:52:16 +0000602
603 unsigned IsMsStruct : 1;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000604
Eli Friedman2782dac2013-06-26 20:50:34 +0000605 /// UnfilledBitsInLastUnit - If the last field laid out was a bitfield,
606 /// this contains the number of bits in the last unit that can be used for
607 /// an adjacent bitfield if necessary. The unit in question is usually
608 /// a byte, but larger units are used if IsMsStruct.
609 unsigned char UnfilledBitsInLastUnit;
610 /// LastBitfieldTypeSize - If IsMsStruct, represents the size of the type
611 /// of the previous field if it was a bitfield.
612 unsigned char LastBitfieldTypeSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000613
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000614 /// MaxFieldAlignment - The maximum allowed field alignment. This is set by
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000615 /// #pragma pack.
Ken Dyck02ced6f2011-02-17 01:49:42 +0000616 CharUnits MaxFieldAlignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000617
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000618 /// DataSize - The data size of the record being laid out.
619 uint64_t DataSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000620
Ken Dyckaf1c83f2011-02-16 01:52:01 +0000621 CharUnits NonVirtualSize;
Ken Dycka2d3dda2011-02-16 01:43:15 +0000622 CharUnits NonVirtualAlignment;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000623
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000624 /// PrimaryBase - the primary base class (if one exists) of the class
625 /// we're laying out.
626 const CXXRecordDecl *PrimaryBase;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000627
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000628 /// PrimaryBaseIsVirtual - Whether the primary base of the class we're laying
629 /// out is virtual.
630 bool PrimaryBaseIsVirtual;
631
John McCalle42a3362012-05-01 08:55:32 +0000632 /// HasOwnVFPtr - Whether the class provides its own vtable/vftbl
633 /// pointer, as opposed to inheriting one from a primary base class.
634 bool HasOwnVFPtr;
Eli Friedman43114f92011-10-21 22:49:56 +0000635
Anders Carlsson22f57202010-10-31 21:01:46 +0000636 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000637
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000638 /// Bases - base classes and their offsets in the record.
639 BaseOffsetsMapTy Bases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000640
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000641 // VBases - virtual base classes and their offsets in the record.
John McCalle42a3362012-05-01 08:55:32 +0000642 ASTRecordLayout::VBaseOffsetsMapTy VBases;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000643
644 /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are
645 /// primary base classes for some other direct or indirect base class.
Anders Carlsson5adde292010-11-24 22:55:48 +0000646 CXXIndirectPrimaryBaseSet IndirectPrimaryBases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000647
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000648 /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in
649 /// inheritance graph order. Used for determining the primary base class.
650 const CXXRecordDecl *FirstNearlyEmptyVBase;
651
652 /// VisitedVirtualBases - A set of all the visited virtual bases, used to
653 /// avoid visiting virtual bases more than once.
654 llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000655
Reid Kleckner8b6d0342015-02-25 19:17:45 +0000656 /// Valid if UseExternalLayout is true.
657 ExternalLayout External;
Douglas Gregore9fc3772012-01-26 07:55:45 +0000658
John McCall0153cd32011-11-08 04:01:03 +0000659 RecordLayoutBuilder(const ASTContext &Context,
660 EmptySubobjectMap *EmptySubobjects)
Ken Dyck4731d5b2011-02-16 02:05:21 +0000661 : Context(Context), EmptySubobjects(EmptySubobjects), Size(0),
John McCall0153cd32011-11-08 04:01:03 +0000662 Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()),
Reid Kleckner8b6d0342015-02-25 19:17:45 +0000663 UseExternalLayout(false), InferAlignment(false),
Douglas Gregor44ba7892012-01-28 00:53:29 +0000664 Packed(false), IsUnion(false), IsMac68kAlign(false), IsMsStruct(false),
Eli Friedman2782dac2013-06-26 20:50:34 +0000665 UnfilledBitsInLastUnit(0), LastBitfieldTypeSize(0),
666 MaxFieldAlignment(CharUnits::Zero()),
Ken Dyck02ced6f2011-02-17 01:49:42 +0000667 DataSize(0), NonVirtualSize(CharUnits::Zero()),
Fariborz Jahanianeb397412011-05-02 17:20:56 +0000668 NonVirtualAlignment(CharUnits::One()),
Craig Topper36250ad2014-05-12 05:36:57 +0000669 PrimaryBase(nullptr), PrimaryBaseIsVirtual(false),
John McCalle42a3362012-05-01 08:55:32 +0000670 HasOwnVFPtr(false),
Craig Topper36250ad2014-05-12 05:36:57 +0000671 FirstNearlyEmptyVBase(nullptr) {}
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000672
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000673 void Layout(const RecordDecl *D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000674 void Layout(const CXXRecordDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000675 void Layout(const ObjCInterfaceDecl *D);
676
677 void LayoutFields(const RecordDecl *D);
Kostya Serebryany293dc9b2014-10-16 20:54:52 +0000678 void LayoutField(const FieldDecl *D, bool InsertExtraPadding);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000679 void LayoutWideBitField(uint64_t FieldSize, uint64_t TypeSize,
680 bool FieldPacked, const FieldDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000681 void LayoutBitField(const FieldDecl *D);
John McCall0153cd32011-11-08 04:01:03 +0000682
John McCall359b8852013-01-25 22:30:49 +0000683 TargetCXXABI getCXXABI() const {
684 return Context.getTargetInfo().getCXXABI();
685 }
686
Anders Carlssone3c24c72010-05-29 17:35:14 +0000687 /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects.
688 llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator;
689
690 typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *>
691 BaseSubobjectInfoMapTy;
692
693 /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases
694 /// of the class we're laying out to their base subobject info.
695 BaseSubobjectInfoMapTy VirtualBaseInfo;
696
697 /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the
698 /// class we're laying out to their base subobject info.
699 BaseSubobjectInfoMapTy NonVirtualBaseInfo;
700
701 /// ComputeBaseSubobjectInfo - Compute the base subobject information for the
702 /// bases of the given class.
703 void ComputeBaseSubobjectInfo(const CXXRecordDecl *RD);
704
705 /// ComputeBaseSubobjectInfo - Compute the base subobject information for a
706 /// single class and all of its base classes.
707 BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
708 bool IsVirtual,
709 BaseSubobjectInfo *Derived);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000710
711 /// DeterminePrimaryBase - Determine the primary base of the given class.
712 void DeterminePrimaryBase(const CXXRecordDecl *RD);
713
714 void SelectPrimaryVBase(const CXXRecordDecl *RD);
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000715
Eli Friedman43114f92011-10-21 22:49:56 +0000716 void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign);
Charles Davisc2c576a2010-08-19 00:55:19 +0000717
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000718 /// LayoutNonVirtualBases - Determines the primary base class (if any) and
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000719 /// lays it out. Will then proceed to lay out all non-virtual base clasess.
720 void LayoutNonVirtualBases(const CXXRecordDecl *RD);
721
722 /// LayoutNonVirtualBase - Lays out a single non-virtual base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +0000723 void LayoutNonVirtualBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000724
Anders Carlssona2f8e412010-10-31 22:20:42 +0000725 void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
726 CharUnits Offset);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000727
728 /// LayoutVirtualBases - Lays out all the virtual bases.
729 void LayoutVirtualBases(const CXXRecordDecl *RD,
730 const CXXRecordDecl *MostDerivedClass);
731
732 /// LayoutVirtualBase - Lays out a single virtual base.
Warren Hunt55d8e822013-10-23 23:53:07 +0000733 void LayoutVirtualBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000734
Daniel Dunbar592a85c2010-05-27 02:25:46 +0000735 /// LayoutBase - Will lay out a base and return the offset where it was
Anders Carlssona2f8e412010-10-31 22:20:42 +0000736 /// placed, in chars.
737 CharUnits LayoutBase(const BaseSubobjectInfo *Base);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000738
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000739 /// InitializeLayout - Initialize record layout for the given record decl.
Daniel Dunbar6da10982010-05-27 05:45:51 +0000740 void InitializeLayout(const Decl *D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +0000741
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000742 /// FinishLayout - Finalize record layout. Adjust record size based on the
743 /// alignment.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000744 void FinishLayout(const NamedDecl *D);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000745
Ken Dyck85ef0432011-02-19 18:58:07 +0000746 void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment);
747 void UpdateAlignment(CharUnits NewAlignment) {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000748 UpdateAlignment(NewAlignment, NewAlignment);
749 }
750
Douglas Gregor44ba7892012-01-28 00:53:29 +0000751 /// \brief Retrieve the externally-supplied field offset for the given
752 /// field.
753 ///
754 /// \param Field The field whose offset is being queried.
755 /// \param ComputedOffset The offset that we've computed for this field.
756 uint64_t updateExternalFieldOffset(const FieldDecl *Field,
757 uint64_t ComputedOffset);
758
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +0000759 void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset,
760 uint64_t UnpackedOffset, unsigned UnpackedAlign,
761 bool isPacked, const FieldDecl *D);
762
763 DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000764
Ken Dyckecfc7552011-02-24 01:13:28 +0000765 CharUnits getSize() const {
Ken Dyck3c215f22011-02-24 01:33:05 +0000766 assert(Size % Context.getCharWidth() == 0);
Ken Dyckecfc7552011-02-24 01:13:28 +0000767 return Context.toCharUnitsFromBits(Size);
768 }
769 uint64_t getSizeInBits() const { return Size; }
770
771 void setSize(CharUnits NewSize) { Size = Context.toBits(NewSize); }
772 void setSize(uint64_t NewSize) { Size = NewSize; }
773
Eli Friedman84d2d3a2011-09-27 19:12:27 +0000774 CharUnits getAligment() const { return Alignment; }
775
Ken Dyckecfc7552011-02-24 01:13:28 +0000776 CharUnits getDataSize() const {
Ken Dyck3c215f22011-02-24 01:33:05 +0000777 assert(DataSize % Context.getCharWidth() == 0);
Ken Dyckecfc7552011-02-24 01:13:28 +0000778 return Context.toCharUnitsFromBits(DataSize);
779 }
780 uint64_t getDataSizeInBits() const { return DataSize; }
781
782 void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); }
783 void setDataSize(uint64_t NewSize) { DataSize = NewSize; }
784
Aaron Ballmanabc18922015-02-15 22:54:08 +0000785 RecordLayoutBuilder(const RecordLayoutBuilder &) = delete;
786 void operator=(const RecordLayoutBuilder &) = delete;
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000787};
Benjamin Kramerc7656cd2010-05-26 09:58:31 +0000788} // end anonymous namespace
Anders Carlsson35a36eb2010-05-26 05:41:04 +0000789
Anders Carlsson81430692009-09-22 03:02:06 +0000790void
Anders Carlssonc2226202010-05-26 05:58:59 +0000791RecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000792 for (const auto &I : RD->bases()) {
793 assert(!I.getType()->isDependentType() &&
Sebastian Redl1054fae2009-10-25 17:03:50 +0000794 "Cannot layout class with dependent bases.");
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000795
Reid Klecknercd612ab2014-04-11 16:57:42 +0000796 const CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000797
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000798 // Check if this is a nearly empty virtual base.
Aaron Ballman574705e2014-03-13 15:41:46 +0000799 if (I.isVirtual() && Context.isNearlyEmpty(Base)) {
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000800 // If it's not an indirect primary base, then we've found our primary
801 // base.
Anders Carlsson81430692009-09-22 03:02:06 +0000802 if (!IndirectPrimaryBases.count(Base)) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000803 PrimaryBase = Base;
804 PrimaryBaseIsVirtual = true;
Mike Stump6f3793b2009-08-12 21:50:08 +0000805 return;
806 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000807
Anders Carlssonf2fa75b2010-03-11 03:39:12 +0000808 // Is this the first nearly empty virtual base?
809 if (!FirstNearlyEmptyVBase)
810 FirstNearlyEmptyVBase = Base;
Mike Stump6f3793b2009-08-12 21:50:08 +0000811 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000812
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000813 SelectPrimaryVBase(Base);
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000814 if (PrimaryBase)
Zhongxing Xuec345b72010-02-15 04:28:35 +0000815 return;
Mike Stump6f3793b2009-08-12 21:50:08 +0000816 }
817}
818
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000819/// DeterminePrimaryBase - Determine the primary base of the given class.
Anders Carlssonc2226202010-05-26 05:58:59 +0000820void RecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) {
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000821 // If the class isn't dynamic, it won't have a primary base.
822 if (!RD->isDynamicClass())
823 return;
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000824
Anders Carlsson81430692009-09-22 03:02:06 +0000825 // Compute all the primary virtual bases for all of our direct and
Mike Stump590a7c72009-08-13 23:26:06 +0000826 // indirect bases, and record all their primary virtual base classes.
Anders Carlsson5adde292010-11-24 22:55:48 +0000827 RD->getIndirectPrimaryBases(IndirectPrimaryBases);
Mike Stump590a7c72009-08-13 23:26:06 +0000828
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000829 // If the record has a dynamic base class, attempt to choose a primary base
830 // class. It is the first (in direct base class order) non-virtual dynamic
Anders Carlsson81430692009-09-22 03:02:06 +0000831 // base class, if one exists.
Aaron Ballman574705e2014-03-13 15:41:46 +0000832 for (const auto &I : RD->bases()) {
Anders Carlsson03ff3792009-11-27 22:05:05 +0000833 // Ignore virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000834 if (I.isVirtual())
Anders Carlsson03ff3792009-11-27 22:05:05 +0000835 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000836
Reid Klecknercd612ab2014-04-11 16:57:42 +0000837 const CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
Anders Carlsson03ff3792009-11-27 22:05:05 +0000838
Warren Hunt55d8e822013-10-23 23:53:07 +0000839 if (Base->isDynamicClass()) {
Anders Carlsson03ff3792009-11-27 22:05:05 +0000840 // We found it.
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000841 PrimaryBase = Base;
842 PrimaryBaseIsVirtual = false;
Anders Carlsson03ff3792009-11-27 22:05:05 +0000843 return;
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000844 }
845 }
846
Eli Friedman5e9534b2011-10-18 00:55:28 +0000847 // Under the Itanium ABI, if there is no non-virtual primary base class,
848 // try to compute the primary virtual base. The primary virtual base is
849 // the first nearly empty virtual base that is not an indirect primary
850 // virtual base class, if one exists.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000851 if (RD->getNumVBases() != 0) {
852 SelectPrimaryVBase(RD);
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000853 if (PrimaryBase)
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000854 return;
855 }
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000856
Eli Friedman5e9534b2011-10-18 00:55:28 +0000857 // Otherwise, it is the first indirect primary base class, if one exists.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000858 if (FirstNearlyEmptyVBase) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000859 PrimaryBase = FirstNearlyEmptyVBase;
860 PrimaryBaseIsVirtual = true;
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000861 return;
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000862 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000863
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000864 assert(!PrimaryBase && "Should not get here with a primary base!");
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000865}
866
Anders Carlssone3c24c72010-05-29 17:35:14 +0000867BaseSubobjectInfo *
868RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
869 bool IsVirtual,
870 BaseSubobjectInfo *Derived) {
871 BaseSubobjectInfo *Info;
872
873 if (IsVirtual) {
874 // Check if we already have info about this virtual base.
875 BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD];
876 if (InfoSlot) {
877 assert(InfoSlot->Class == RD && "Wrong class for virtual base info!");
878 return InfoSlot;
879 }
880
881 // We don't, create it.
882 InfoSlot = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
883 Info = InfoSlot;
884 } else {
885 Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
886 }
887
888 Info->Class = RD;
889 Info->IsVirtual = IsVirtual;
Craig Topper36250ad2014-05-12 05:36:57 +0000890 Info->Derived = nullptr;
891 Info->PrimaryVirtualBaseInfo = nullptr;
892
893 const CXXRecordDecl *PrimaryVirtualBase = nullptr;
894 BaseSubobjectInfo *PrimaryVirtualBaseInfo = nullptr;
Anders Carlssone3c24c72010-05-29 17:35:14 +0000895
896 // Check if this base has a primary virtual base.
897 if (RD->getNumVBases()) {
898 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlsson7f95cd12010-11-24 23:12:57 +0000899 if (Layout.isPrimaryBaseVirtual()) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000900 // This base does have a primary virtual base.
901 PrimaryVirtualBase = Layout.getPrimaryBase();
902 assert(PrimaryVirtualBase && "Didn't have a primary virtual base!");
903
904 // Now check if we have base subobject info about this primary base.
905 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
906
907 if (PrimaryVirtualBaseInfo) {
908 if (PrimaryVirtualBaseInfo->Derived) {
909 // We did have info about this primary base, and it turns out that it
910 // has already been claimed as a primary virtual base for another
Craig Topper36250ad2014-05-12 05:36:57 +0000911 // base.
912 PrimaryVirtualBase = nullptr;
Anders Carlssone3c24c72010-05-29 17:35:14 +0000913 } else {
914 // We can claim this base as our primary base.
915 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
916 PrimaryVirtualBaseInfo->Derived = Info;
917 }
918 }
919 }
920 }
921
922 // Now go through all direct bases.
Aaron Ballman574705e2014-03-13 15:41:46 +0000923 for (const auto &I : RD->bases()) {
924 bool IsVirtual = I.isVirtual();
Reid Klecknercd612ab2014-04-11 16:57:42 +0000925
926 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
927
Anders Carlssone3c24c72010-05-29 17:35:14 +0000928 Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info));
929 }
930
931 if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) {
932 // Traversing the bases must have created the base info for our primary
933 // virtual base.
934 PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
935 assert(PrimaryVirtualBaseInfo &&
936 "Did not create a primary virtual base!");
937
938 // Claim the primary virtual base as our primary virtual base.
939 Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
940 PrimaryVirtualBaseInfo->Derived = Info;
941 }
942
943 return Info;
944}
945
946void RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD) {
Aaron Ballman574705e2014-03-13 15:41:46 +0000947 for (const auto &I : RD->bases()) {
948 bool IsVirtual = I.isVirtual();
Anders Carlssone3c24c72010-05-29 17:35:14 +0000949
Reid Klecknercd612ab2014-04-11 16:57:42 +0000950 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
951
Anders Carlssone3c24c72010-05-29 17:35:14 +0000952 // Compute the base subobject info for this base.
Craig Topper36250ad2014-05-12 05:36:57 +0000953 BaseSubobjectInfo *Info = ComputeBaseSubobjectInfo(BaseDecl, IsVirtual,
954 nullptr);
Anders Carlssone3c24c72010-05-29 17:35:14 +0000955
956 if (IsVirtual) {
957 // ComputeBaseInfo has already added this base for us.
958 assert(VirtualBaseInfo.count(BaseDecl) &&
959 "Did not add virtual base!");
960 } else {
961 // Add the base info to the map of non-virtual bases.
962 assert(!NonVirtualBaseInfo.count(BaseDecl) &&
963 "Non-virtual base already exists!");
964 NonVirtualBaseInfo.insert(std::make_pair(BaseDecl, Info));
965 }
966 }
967}
968
Anders Carlsson09ffa322010-03-10 22:21:28 +0000969void
Eli Friedman43114f92011-10-21 22:49:56 +0000970RecordLayoutBuilder::EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign) {
Eli Friedman5e9534b2011-10-18 00:55:28 +0000971 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
972
973 // The maximum field alignment overrides base align.
974 if (!MaxFieldAlignment.isZero()) {
975 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
976 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
977 }
978
979 // Round up the current record size to pointer alignment.
Eli Friedman43114f92011-10-21 22:49:56 +0000980 setSize(getSize().RoundUpToAlignment(BaseAlign));
981 setDataSize(getSize());
Eli Friedman5e9534b2011-10-18 00:55:28 +0000982
983 // Update the alignment.
984 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
985}
986
987void
Anders Carlssonc2226202010-05-26 05:58:59 +0000988RecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl *RD) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000989 // Then, determine the primary base class.
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000990 DeterminePrimaryBase(RD);
Daniel Dunbaraa423af2010-04-08 02:59:49 +0000991
Anders Carlssone3c24c72010-05-29 17:35:14 +0000992 // Compute base subobject info.
993 ComputeBaseSubobjectInfo(RD);
994
Anders Carlsson8630b5b2010-03-11 00:15:35 +0000995 // If we have a primary base class, lay it out.
Anders Carlssond20e7cd2010-05-26 05:20:58 +0000996 if (PrimaryBase) {
997 if (PrimaryBaseIsVirtual) {
Anders Carlssone3c24c72010-05-29 17:35:14 +0000998 // If the primary virtual base was a primary virtual base of some other
999 // base class we'll have to steal it.
1000 BaseSubobjectInfo *PrimaryBaseInfo = VirtualBaseInfo.lookup(PrimaryBase);
Craig Topper36250ad2014-05-12 05:36:57 +00001001 PrimaryBaseInfo->Derived = nullptr;
1002
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001003 // We have a virtual primary base, insert it as an indirect primary base.
Anders Carlssond20e7cd2010-05-26 05:20:58 +00001004 IndirectPrimaryBases.insert(PrimaryBase);
Anders Carlssonfe900962010-03-11 05:42:17 +00001005
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001006 assert(!VisitedVirtualBases.count(PrimaryBase) &&
Anders Carlssond20e7cd2010-05-26 05:20:58 +00001007 "vbase already visited!");
1008 VisitedVirtualBases.insert(PrimaryBase);
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001009
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001010 LayoutVirtualBase(PrimaryBaseInfo);
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001011 } else {
1012 BaseSubobjectInfo *PrimaryBaseInfo =
1013 NonVirtualBaseInfo.lookup(PrimaryBase);
1014 assert(PrimaryBaseInfo &&
1015 "Did not find base info for non-virtual primary base!");
1016
1017 LayoutNonVirtualBase(PrimaryBaseInfo);
1018 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001019
John McCall0153cd32011-11-08 04:01:03 +00001020 // If this class needs a vtable/vf-table and didn't get one from a
1021 // primary base, add it in now.
Warren Hunt55d8e822013-10-23 23:53:07 +00001022 } else if (RD->isDynamicClass()) {
Eli Friedman5e9534b2011-10-18 00:55:28 +00001023 assert(DataSize == 0 && "Vtable pointer must be at offset zero!");
Eli Friedman5e9534b2011-10-18 00:55:28 +00001024 CharUnits PtrWidth =
1025 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
Eli Friedman43114f92011-10-21 22:49:56 +00001026 CharUnits PtrAlign =
1027 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
1028 EnsureVTablePointerAlignment(PtrAlign);
John McCalle42a3362012-05-01 08:55:32 +00001029 HasOwnVFPtr = true;
Eli Friedman5e9534b2011-10-18 00:55:28 +00001030 setSize(getSize() + PtrWidth);
1031 setDataSize(getSize());
1032 }
1033
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001034 // Now lay out the non-virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001035 for (const auto &I : RD->bases()) {
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001036
Benjamin Kramer273670a2013-10-25 07:40:50 +00001037 // Ignore virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +00001038 if (I.isVirtual())
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001039 continue;
1040
Aaron Ballman574705e2014-03-13 15:41:46 +00001041 const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001042
John McCall0153cd32011-11-08 04:01:03 +00001043 // Skip the primary base, because we've already laid it out. The
1044 // !PrimaryBaseIsVirtual check is required because we might have a
1045 // non-virtual base of the same type as a primary virtual base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001046 if (BaseDecl == PrimaryBase && !PrimaryBaseIsVirtual)
Anders Carlsson8630b5b2010-03-11 00:15:35 +00001047 continue;
1048
1049 // Lay out the base.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001050 BaseSubobjectInfo *BaseInfo = NonVirtualBaseInfo.lookup(BaseDecl);
1051 assert(BaseInfo && "Did not find base info for non-virtual base!");
1052
1053 LayoutNonVirtualBase(BaseInfo);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001054 }
1055}
1056
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001057void RecordLayoutBuilder::LayoutNonVirtualBase(const BaseSubobjectInfo *Base) {
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001058 // Layout the base.
Anders Carlssona2f8e412010-10-31 22:20:42 +00001059 CharUnits Offset = LayoutBase(Base);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001060
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001061 // Add its base class offset.
Anders Carlssonbb0e6782010-05-29 17:42:25 +00001062 assert(!Bases.count(Base->Class) && "base offset already exists!");
Anders Carlssona2f8e412010-10-31 22:20:42 +00001063 Bases.insert(std::make_pair(Base->Class, Offset));
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001064
1065 AddPrimaryVirtualBaseOffsets(Base, Offset);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001066}
Mike Stump2b84dd32009-11-05 04:02:15 +00001067
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001068void
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001069RecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
Anders Carlssona2f8e412010-10-31 22:20:42 +00001070 CharUnits Offset) {
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001071 // This base isn't interesting, it has no virtual bases.
1072 if (!Info->Class->getNumVBases())
1073 return;
1074
1075 // First, check if we have a virtual primary base to add offsets for.
1076 if (Info->PrimaryVirtualBaseInfo) {
1077 assert(Info->PrimaryVirtualBaseInfo->IsVirtual &&
1078 "Primary virtual base is not virtual!");
1079 if (Info->PrimaryVirtualBaseInfo->Derived == Info) {
1080 // Add the offset.
1081 assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) &&
1082 "primary vbase offset already exists!");
1083 VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class,
John McCalle42a3362012-05-01 08:55:32 +00001084 ASTRecordLayout::VBaseInfo(Offset, false)));
Anders Carlssonea7b1822010-04-15 16:12:58 +00001085
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001086 // Traverse the primary virtual base.
1087 AddPrimaryVirtualBaseOffsets(Info->PrimaryVirtualBaseInfo, Offset);
1088 }
Anders Carlssonea7b1822010-04-15 16:12:58 +00001089 }
1090
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001091 // Now go through all direct non-virtual bases.
1092 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
David Majnemerc964b4b2014-07-16 06:04:00 +00001093 for (const BaseSubobjectInfo *Base : Info->Bases) {
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001094 if (Base->IsVirtual)
Anders Carlssonea7b1822010-04-15 16:12:58 +00001095 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001096
Anders Carlsson0a14ee92010-11-01 00:21:58 +00001097 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001098 AddPrimaryVirtualBaseOffsets(Base, BaseOffset);
Anders Carlssonea7b1822010-04-15 16:12:58 +00001099 }
1100}
1101
1102void
Anders Carlssonc2226202010-05-26 05:58:59 +00001103RecordLayoutBuilder::LayoutVirtualBases(const CXXRecordDecl *RD,
Anders Carlssonea7b1822010-04-15 16:12:58 +00001104 const CXXRecordDecl *MostDerivedClass) {
Anders Carlssonde710c92010-03-11 04:33:54 +00001105 const CXXRecordDecl *PrimaryBase;
Anders Carlsson291279e2010-04-10 18:42:27 +00001106 bool PrimaryBaseIsVirtual;
Anders Carlssonfe900962010-03-11 05:42:17 +00001107
Anders Carlsson291279e2010-04-10 18:42:27 +00001108 if (MostDerivedClass == RD) {
Anders Carlssond20e7cd2010-05-26 05:20:58 +00001109 PrimaryBase = this->PrimaryBase;
1110 PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual;
Anders Carlsson291279e2010-04-10 18:42:27 +00001111 } else {
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001112 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
Anders Carlssonde710c92010-03-11 04:33:54 +00001113 PrimaryBase = Layout.getPrimaryBase();
Anders Carlsson7f95cd12010-11-24 23:12:57 +00001114 PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
Anders Carlsson291279e2010-04-10 18:42:27 +00001115 }
1116
David Majnemerc964b4b2014-07-16 06:04:00 +00001117 for (const CXXBaseSpecifier &Base : RD->bases()) {
1118 assert(!Base.getType()->isDependentType() &&
Sebastian Redl1054fae2009-10-25 17:03:50 +00001119 "Cannot layout class with dependent bases.");
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001120
David Majnemerc964b4b2014-07-16 06:04:00 +00001121 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001122
David Majnemerc964b4b2014-07-16 06:04:00 +00001123 if (Base.isVirtual()) {
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001124 if (PrimaryBase != BaseDecl || !PrimaryBaseIsVirtual) {
1125 bool IndirectPrimaryBase = IndirectPrimaryBases.count(BaseDecl);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001126
Anders Carlsson291279e2010-04-10 18:42:27 +00001127 // Only lay out the virtual base if it's not an indirect primary base.
1128 if (!IndirectPrimaryBase) {
1129 // Only visit virtual bases once.
David Blaikie82e95a32014-11-19 07:49:47 +00001130 if (!VisitedVirtualBases.insert(BaseDecl).second)
Anders Carlsson291279e2010-04-10 18:42:27 +00001131 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001132
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001133 const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1134 assert(BaseInfo && "Did not find virtual base info!");
1135 LayoutVirtualBase(BaseInfo);
Anders Carlsson6a848892010-03-11 04:10:39 +00001136 }
Mike Stump2b84dd32009-11-05 04:02:15 +00001137 }
Mike Stumpc2f591b2009-08-13 22:53:07 +00001138 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001139
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001140 if (!BaseDecl->getNumVBases()) {
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001141 // This base isn't interesting since it doesn't have any virtual bases.
1142 continue;
Mike Stump996576f32009-08-16 19:04:13 +00001143 }
Anders Carlssonf7b7a1e2010-03-11 04:24:02 +00001144
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001145 LayoutVirtualBases(BaseDecl, MostDerivedClass);
Mike Stump6b2556f2009-08-06 13:41:24 +00001146 }
1147}
1148
Warren Hunt55d8e822013-10-23 23:53:07 +00001149void RecordLayoutBuilder::LayoutVirtualBase(const BaseSubobjectInfo *Base) {
Anders Carlsson6b0d9142010-05-29 19:44:50 +00001150 assert(!Base->Derived && "Trying to lay out a primary virtual base!");
1151
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001152 // Layout the base.
Anders Carlssona2f8e412010-10-31 22:20:42 +00001153 CharUnits Offset = LayoutBase(Base);
Anders Carlsson0d0b5882010-03-10 22:26:24 +00001154
1155 // Add its base class offset.
Anders Carlssond6ff5d72010-05-29 17:48:36 +00001156 assert(!VBases.count(Base->Class) && "vbase offset already exists!");
John McCalle42a3362012-05-01 08:55:32 +00001157 VBases.insert(std::make_pair(Base->Class,
Warren Hunt55d8e822013-10-23 23:53:07 +00001158 ASTRecordLayout::VBaseInfo(Offset, false)));
John McCalle42a3362012-05-01 08:55:32 +00001159
Warren Hunt55d8e822013-10-23 23:53:07 +00001160 AddPrimaryVirtualBaseOffsets(Base, Offset);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001161}
1162
Anders Carlssona2f8e412010-10-31 22:20:42 +00001163CharUnits RecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) {
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001164 const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001165
Douglas Gregore9fc3772012-01-26 07:55:45 +00001166
1167 CharUnits Offset;
1168
1169 // Query the external layout to see if it provides an offset.
1170 bool HasExternalLayout = false;
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001171 if (UseExternalLayout) {
Douglas Gregore9fc3772012-01-26 07:55:45 +00001172 llvm::DenseMap<const CXXRecordDecl *, CharUnits>::iterator Known;
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001173 if (Base->IsVirtual)
1174 HasExternalLayout = External.getExternalNVBaseOffset(Base->Class, Offset);
1175 else
1176 HasExternalLayout = External.getExternalVBaseOffset(Base->Class, Offset);
Douglas Gregore9fc3772012-01-26 07:55:45 +00001177 }
1178
Warren Huntd640d7d2014-01-09 00:30:56 +00001179 CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlignment();
Eli Friedman69d27d22013-07-16 00:21:28 +00001180 CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
1181
Anders Carlsson09ffa322010-03-10 22:21:28 +00001182 // If we have an empty base class, try to place it at offset 0.
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001183 if (Base->Class->isEmpty() &&
Douglas Gregore9fc3772012-01-26 07:55:45 +00001184 (!HasExternalLayout || Offset == CharUnits::Zero()) &&
Anders Carlsson28466ab2010-10-31 22:13:23 +00001185 EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) {
Ken Dyck1b4420e2011-02-28 02:01:38 +00001186 setSize(std::max(getSize(), Layout.getSize()));
Eli Friedman69d27d22013-07-16 00:21:28 +00001187 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001188
Anders Carlssona2f8e412010-10-31 22:20:42 +00001189 return CharUnits::Zero();
Anders Carlsson09ffa322010-03-10 22:21:28 +00001190 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001191
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001192 // The maximum field alignment overrides base align.
Ken Dyck02ced6f2011-02-17 01:49:42 +00001193 if (!MaxFieldAlignment.isZero()) {
Ken Dyck85ef0432011-02-19 18:58:07 +00001194 BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1195 UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001196 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001197
Douglas Gregore9fc3772012-01-26 07:55:45 +00001198 if (!HasExternalLayout) {
1199 // Round up the current record size to the base's alignment boundary.
1200 Offset = getDataSize().RoundUpToAlignment(BaseAlign);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001201
Douglas Gregore9fc3772012-01-26 07:55:45 +00001202 // Try to place the base.
1203 while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset))
1204 Offset += BaseAlign;
1205 } else {
1206 bool Allowed = EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset);
1207 (void)Allowed;
1208 assert(Allowed && "Base subobject externally placed at overlapping offset");
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001209
1210 if (InferAlignment && Offset < getDataSize().RoundUpToAlignment(BaseAlign)){
1211 // The externally-supplied base offset is before the base offset we
1212 // computed. Assume that the structure is packed.
1213 Alignment = CharUnits::One();
1214 InferAlignment = false;
1215 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001216 }
1217
Anders Carlssond7f3fcf2010-05-29 20:47:33 +00001218 if (!Base->Class->isEmpty()) {
Anders Carlsson09ffa322010-03-10 22:21:28 +00001219 // Update the data size.
Ken Dyck1b4420e2011-02-28 02:01:38 +00001220 setDataSize(Offset + Layout.getNonVirtualSize());
Anders Carlsson09ffa322010-03-10 22:21:28 +00001221
Ken Dyck1b4420e2011-02-28 02:01:38 +00001222 setSize(std::max(getSize(), getDataSize()));
Anders Carlsson09ffa322010-03-10 22:21:28 +00001223 } else
Ken Dyck1b4420e2011-02-28 02:01:38 +00001224 setSize(std::max(getSize(), Offset + Layout.getSize()));
Anders Carlsson09ffa322010-03-10 22:21:28 +00001225
1226 // Remember max struct/class alignment.
Argyrios Kyrtzidis8b542742010-12-09 00:35:20 +00001227 UpdateAlignment(BaseAlign, UnpackedBaseAlign);
Anders Carlsson09ffa322010-03-10 22:21:28 +00001228
Ken Dyck1b4420e2011-02-28 02:01:38 +00001229 return Offset;
Anders Carlsson09ffa322010-03-10 22:21:28 +00001230}
1231
Daniel Dunbar6da10982010-05-27 05:45:51 +00001232void RecordLayoutBuilder::InitializeLayout(const Decl *D) {
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001233 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Daniel Dunbar6da10982010-05-27 05:45:51 +00001234 IsUnion = RD->isUnion();
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001235 IsMsStruct = RD->isMsStruct(Context);
1236 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001237
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001238 Packed = D->hasAttr<PackedAttr>();
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001239
Daniel Dunbar096ed292011-10-05 21:04:55 +00001240 // Honor the default struct packing maximum alignment flag.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001241 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) {
Daniel Dunbar096ed292011-10-05 21:04:55 +00001242 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
1243 }
1244
Daniel Dunbar6da10982010-05-27 05:45:51 +00001245 // mac68k alignment supersedes maximum field alignment and attribute aligned,
1246 // and forces all structures to have 2-byte alignment. The IBM docs on it
1247 // allude to additional (more complicated) semantics, especially with regard
1248 // to bit-fields, but gcc appears not to follow that.
1249 if (D->hasAttr<AlignMac68kAttr>()) {
1250 IsMac68kAlign = true;
Ken Dyck02ced6f2011-02-17 01:49:42 +00001251 MaxFieldAlignment = CharUnits::fromQuantity(2);
Ken Dyck4731d5b2011-02-16 02:05:21 +00001252 Alignment = CharUnits::fromQuantity(2);
Daniel Dunbar6da10982010-05-27 05:45:51 +00001253 } else {
1254 if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>())
Ken Dyck02ced6f2011-02-17 01:49:42 +00001255 MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001256
Alexis Huntdcfba7b2010-08-18 23:23:40 +00001257 if (unsigned MaxAlign = D->getMaxAlignment())
Ken Dyck85ef0432011-02-19 18:58:07 +00001258 UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign));
Daniel Dunbar6da10982010-05-27 05:45:51 +00001259 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001260
1261 // If there is an external AST source, ask it for the various offsets.
1262 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001263 if (ExternalASTSource *Source = Context.getExternalSource()) {
1264 UseExternalLayout = Source->layoutRecordType(
1265 RD, External.Size, External.Align, External.FieldOffsets,
1266 External.BaseOffsets, External.VirtualBaseOffsets);
NAKAMURA Takumi472041f2015-02-25 10:32:20 +00001267
Douglas Gregore9fc3772012-01-26 07:55:45 +00001268 // Update based on external alignment.
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001269 if (UseExternalLayout) {
1270 if (External.Align > 0) {
1271 Alignment = Context.toCharUnitsFromBits(External.Align);
Douglas Gregor44ba7892012-01-28 00:53:29 +00001272 } else {
1273 // The external source didn't have alignment information; infer it.
1274 InferAlignment = true;
1275 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001276 }
1277 }
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001278}
Anders Carlsson6d9f6f32009-07-19 00:18:47 +00001279
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001280void RecordLayoutBuilder::Layout(const RecordDecl *D) {
1281 InitializeLayout(D);
Anders Carlsson118ce162009-07-18 21:48:39 +00001282 LayoutFields(D);
Mike Stump11289f42009-09-09 15:08:12 +00001283
Anders Carlsson79474332009-07-18 20:20:21 +00001284 // Finally, round the size of the total struct up to the alignment of the
1285 // struct itself.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001286 FinishLayout(D);
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001287}
1288
1289void RecordLayoutBuilder::Layout(const CXXRecordDecl *RD) {
1290 InitializeLayout(RD);
1291
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001292 // Lay out the vtable and the non-virtual bases.
1293 LayoutNonVirtualBases(RD);
1294
1295 LayoutFields(RD);
1296
Ken Dycke7380752011-03-10 01:53:59 +00001297 NonVirtualSize = Context.toCharUnitsFromBits(
1298 llvm::RoundUpToAlignment(getSizeInBits(),
Douglas Gregore8bbc122011-09-02 00:18:52 +00001299 Context.getTargetInfo().getCharAlign()));
Ken Dyck4731d5b2011-02-16 02:05:21 +00001300 NonVirtualAlignment = Alignment;
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001301
Warren Hunt55d8e822013-10-23 23:53:07 +00001302 // Lay out the virtual bases and add the primary virtual base offsets.
1303 LayoutVirtualBases(RD, RD);
John McCall0153cd32011-11-08 04:01:03 +00001304
1305 // Finally, round the size of the total struct up to the alignment
Eli Friedman83a12582011-12-01 00:37:01 +00001306 // of the struct itself.
1307 FinishLayout(RD);
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001308
Anders Carlsson5b441d72010-04-10 21:24:48 +00001309#ifndef NDEBUG
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001310 // Check that we have base offsets for all bases.
David Majnemerc964b4b2014-07-16 06:04:00 +00001311 for (const CXXBaseSpecifier &Base : RD->bases()) {
1312 if (Base.isVirtual())
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001313 continue;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001314
David Majnemerc964b4b2014-07-16 06:04:00 +00001315 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001316
1317 assert(Bases.count(BaseDecl) && "Did not find base offset!");
1318 }
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001319
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001320 // And all virtual bases.
David Majnemerc964b4b2014-07-16 06:04:00 +00001321 for (const CXXBaseSpecifier &Base : RD->vbases()) {
1322 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001323
Anders Carlssonc28a6c92010-05-26 15:10:00 +00001324 assert(VBases.count(BaseDecl) && "Did not find base offset!");
Anders Carlsson5b441d72010-04-10 21:24:48 +00001325 }
1326#endif
Anders Carlsson79474332009-07-18 20:20:21 +00001327}
1328
Anders Carlssonc2226202010-05-26 05:58:59 +00001329void RecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) {
Anders Carlsson4f516282009-07-18 20:50:59 +00001330 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001331 const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD);
Anders Carlsson4f516282009-07-18 20:50:59 +00001332
Ken Dyck85ef0432011-02-19 18:58:07 +00001333 UpdateAlignment(SL.getAlignment());
Mike Stump11289f42009-09-09 15:08:12 +00001334
Anders Carlsson4f516282009-07-18 20:50:59 +00001335 // We start laying out ivars not at the end of the superclass
1336 // structure, but at the next byte following the last field.
Ken Dyckecfc7552011-02-24 01:13:28 +00001337 setSize(SL.getDataSize());
Ken Dyck1b4420e2011-02-28 02:01:38 +00001338 setDataSize(getSize());
Anders Carlsson4f516282009-07-18 20:50:59 +00001339 }
Mike Stump11289f42009-09-09 15:08:12 +00001340
Daniel Dunbar6da10982010-05-27 05:45:51 +00001341 InitializeLayout(D);
Anders Carlsson4f516282009-07-18 20:50:59 +00001342 // Layout each ivar sequentially.
Jordy Rosea91768e2011-07-22 02:08:32 +00001343 for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD;
1344 IVD = IVD->getNextIvar())
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001345 LayoutField(IVD, false);
Mike Stump11289f42009-09-09 15:08:12 +00001346
Anders Carlsson4f516282009-07-18 20:50:59 +00001347 // Finally, round the size of the total struct up to the alignment of the
1348 // struct itself.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001349 FinishLayout(D);
Anders Carlsson4f516282009-07-18 20:50:59 +00001350}
1351
Anders Carlssonc2226202010-05-26 05:58:59 +00001352void RecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
Anders Carlsson118ce162009-07-18 21:48:39 +00001353 // Layout each field, for now, just sequentially, respecting alignment. In
1354 // the future, this will need to be tweakable by targets.
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001355 bool InsertExtraPadding = D->mayInsertExtraPadding(/*EmitRemark=*/true);
Kostya Serebryany68c29da2014-10-27 19:34:10 +00001356 bool HasFlexibleArrayMember = D->hasFlexibleArrayMember();
1357 for (auto I = D->field_begin(), End = D->field_end(); I != End; ++I) {
1358 auto Next(I);
1359 ++Next;
1360 LayoutField(*I,
1361 InsertExtraPadding && (Next != End || !HasFlexibleArrayMember));
1362 }
Anders Carlsson118ce162009-07-18 21:48:39 +00001363}
1364
Artyom Skrobov5e63acc2014-10-17 10:22:03 +00001365// Rounds the specified size to have it a multiple of the char size.
1366static uint64_t
1367roundUpSizeToCharAlignment(uint64_t Size,
1368 const ASTContext &Context) {
1369 uint64_t CharAlignment = Context.getTargetInfo().getCharAlign();
1370 return llvm::RoundUpToAlignment(Size, CharAlignment);
1371}
1372
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001373void RecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize,
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001374 uint64_t TypeSize,
1375 bool FieldPacked,
1376 const FieldDecl *D) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00001377 assert(Context.getLangOpts().CPlusPlus &&
Anders Carlsson57235162010-04-16 15:57:11 +00001378 "Can only have wide bit-fields in C++!");
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001379
Anders Carlsson57235162010-04-16 15:57:11 +00001380 // Itanium C++ ABI 2.4:
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001381 // If sizeof(T)*8 < n, let T' be the largest integral POD type with
Anders Carlsson57235162010-04-16 15:57:11 +00001382 // sizeof(T')*8 <= n.
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001383
Anders Carlsson57235162010-04-16 15:57:11 +00001384 QualType IntegralPODTypes[] = {
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001385 Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy,
Anders Carlsson57235162010-04-16 15:57:11 +00001386 Context.UnsignedLongTy, Context.UnsignedLongLongTy
1387 };
1388
Anders Carlsson57235162010-04-16 15:57:11 +00001389 QualType Type;
David Majnemerc964b4b2014-07-16 06:04:00 +00001390 for (const QualType &QT : IntegralPODTypes) {
1391 uint64_t Size = Context.getTypeSize(QT);
Anders Carlsson57235162010-04-16 15:57:11 +00001392
1393 if (Size > FieldSize)
1394 break;
1395
David Majnemerc964b4b2014-07-16 06:04:00 +00001396 Type = QT;
Anders Carlsson57235162010-04-16 15:57:11 +00001397 }
1398 assert(!Type.isNull() && "Did not find a type!");
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001399
Ken Dyckdbe37f32011-03-01 01:36:00 +00001400 CharUnits TypeAlign = Context.getTypeAlignInChars(Type);
Anders Carlsson57235162010-04-16 15:57:11 +00001401
1402 // We're not going to use any of the unfilled bits in the last byte.
Eli Friedman2782dac2013-06-26 20:50:34 +00001403 UnfilledBitsInLastUnit = 0;
1404 LastBitfieldTypeSize = 0;
Anders Carlsson57235162010-04-16 15:57:11 +00001405
Anders Carlssonaad5fa82010-04-17 20:21:41 +00001406 uint64_t FieldOffset;
Eli Friedman2782dac2013-06-26 20:50:34 +00001407 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001408
Anders Carlsson57235162010-04-16 15:57:11 +00001409 if (IsUnion) {
Artyom Skrobov5e63acc2014-10-17 10:22:03 +00001410 uint64_t RoundedFieldSize = roundUpSizeToCharAlignment(FieldSize,
1411 Context);
1412 setDataSize(std::max(getDataSizeInBits(), RoundedFieldSize));
Anders Carlssonaad5fa82010-04-17 20:21:41 +00001413 FieldOffset = 0;
Anders Carlsson57235162010-04-16 15:57:11 +00001414 } else {
Chad Rosiere1a6a0e2011-08-05 22:38:04 +00001415 // The bitfield is allocated starting at the next offset aligned
1416 // appropriately for T', with length n bits.
Ken Dyckdbe37f32011-03-01 01:36:00 +00001417 FieldOffset = llvm::RoundUpToAlignment(getDataSizeInBits(),
1418 Context.toBits(TypeAlign));
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001419
Anders Carlsson57235162010-04-16 15:57:11 +00001420 uint64_t NewSizeInBits = FieldOffset + FieldSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001421
Ken Dycka1a2e8d2011-03-10 02:00:35 +00001422 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
Douglas Gregore8bbc122011-09-02 00:18:52 +00001423 Context.getTargetInfo().getCharAlign()));
Eli Friedman2782dac2013-06-26 20:50:34 +00001424 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
Anders Carlsson57235162010-04-16 15:57:11 +00001425 }
1426
1427 // Place this field at the current location.
1428 FieldOffsets.push_back(FieldOffset);
1429
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001430 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset,
Ken Dyckdbe37f32011-03-01 01:36:00 +00001431 Context.toBits(TypeAlign), FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001432
Anders Carlsson57235162010-04-16 15:57:11 +00001433 // Update the size.
Ken Dyckecfc7552011-02-24 01:13:28 +00001434 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Daniel Dunbar592a85c2010-05-27 02:25:46 +00001435
Anders Carlsson57235162010-04-16 15:57:11 +00001436 // Remember max struct/class alignment.
Ken Dyckdbe37f32011-03-01 01:36:00 +00001437 UpdateAlignment(TypeAlign);
Anders Carlsson57235162010-04-16 15:57:11 +00001438}
1439
Anders Carlssonc2226202010-05-26 05:58:59 +00001440void RecordLayoutBuilder::LayoutBitField(const FieldDecl *D) {
Anders Carlsson07209442009-11-22 17:37:31 +00001441 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
Richard Smithcaf33902011-10-10 18:28:20 +00001442 uint64_t FieldSize = D->getBitWidthValue(Context);
David Majnemer34b57492014-07-30 01:30:47 +00001443 TypeInfo FieldInfo = Context.getTypeInfo(D->getType());
1444 uint64_t TypeSize = FieldInfo.Width;
1445 unsigned FieldAlign = FieldInfo.Align;
Eli Friedman2782dac2013-06-26 20:50:34 +00001446
John McCall30268ca2014-01-29 07:53:44 +00001447 // UnfilledBitsInLastUnit is the difference between the end of the
1448 // last allocated bitfield (i.e. the first bit offset available for
1449 // bitfields) and the end of the current data size in bits (i.e. the
1450 // first bit offset available for non-bitfields). The current data
1451 // size in bits is always a multiple of the char size; additionally,
1452 // for ms_struct records it's also a multiple of the
1453 // LastBitfieldTypeSize (if set).
1454
John McCall76e1818a2014-02-13 00:50:08 +00001455 // The struct-layout algorithm is dictated by the platform ABI,
1456 // which in principle could use almost any rules it likes. In
1457 // practice, UNIXy targets tend to inherit the algorithm described
1458 // in the System V generic ABI. The basic bitfield layout rule in
1459 // System V is to place bitfields at the next available bit offset
1460 // where the entire bitfield would fit in an aligned storage unit of
1461 // the declared type; it's okay if an earlier or later non-bitfield
1462 // is allocated in the same storage unit. However, some targets
1463 // (those that !useBitFieldTypeAlignment(), e.g. ARM APCS) don't
1464 // require this storage unit to be aligned, and therefore always put
1465 // the bitfield at the next available bit offset.
John McCall30268ca2014-01-29 07:53:44 +00001466
John McCall76e1818a2014-02-13 00:50:08 +00001467 // ms_struct basically requests a complete replacement of the
1468 // platform ABI's struct-layout algorithm, with the high-level goal
1469 // of duplicating MSVC's layout. For non-bitfields, this follows
1470 // the the standard algorithm. The basic bitfield layout rule is to
1471 // allocate an entire unit of the bitfield's declared type
1472 // (e.g. 'unsigned long'), then parcel it up among successive
1473 // bitfields whose declared types have the same size, making a new
1474 // unit as soon as the last can no longer store the whole value.
1475 // Since it completely replaces the platform ABI's algorithm,
1476 // settings like !useBitFieldTypeAlignment() do not apply.
1477
1478 // A zero-width bitfield forces the use of a new storage unit for
1479 // later bitfields. In general, this occurs by rounding up the
1480 // current size of the struct as if the algorithm were about to
1481 // place a non-bitfield of the field's formal type. Usually this
1482 // does not change the alignment of the struct itself, but it does
1483 // on some targets (those that useZeroLengthBitfieldAlignment(),
1484 // e.g. ARM). In ms_struct layout, zero-width bitfields are
1485 // ignored unless they follow a non-zero-width bitfield.
1486
1487 // A field alignment restriction (e.g. from #pragma pack) or
1488 // specification (e.g. from __attribute__((aligned))) changes the
1489 // formal alignment of the field. For System V, this alters the
1490 // required alignment of the notional storage unit that must contain
1491 // the bitfield. For ms_struct, this only affects the placement of
1492 // new storage units. In both cases, the effect of #pragma pack is
1493 // ignored on zero-width bitfields.
1494
1495 // On System V, a packed field (e.g. from #pragma pack or
1496 // __attribute__((packed))) always uses the next available bit
1497 // offset.
1498
John McCall95833f32014-02-27 20:30:49 +00001499 // In an ms_struct struct, the alignment of a fundamental type is
1500 // always equal to its size. This is necessary in order to mimic
1501 // the i386 alignment rules on targets which might not fully align
1502 // all types (e.g. Darwin PPC32, where alignof(long long) == 4).
John McCall30268ca2014-01-29 07:53:44 +00001503
1504 // First, some simple bookkeeping to perform for ms_struct structs.
Eli Friedman2782dac2013-06-26 20:50:34 +00001505 if (IsMsStruct) {
John McCall30268ca2014-01-29 07:53:44 +00001506 // The field alignment for integer types is always the size.
Fariborz Jahanian7adbed62011-05-09 22:03:17 +00001507 FieldAlign = TypeSize;
John McCall30268ca2014-01-29 07:53:44 +00001508
1509 // If the previous field was not a bitfield, or was a bitfield
1510 // with a different storage unit size, we're done with that
1511 // storage unit.
Eli Friedman2782dac2013-06-26 20:50:34 +00001512 if (LastBitfieldTypeSize != TypeSize) {
John McCall30268ca2014-01-29 07:53:44 +00001513 // Also, ignore zero-length bitfields after non-bitfields.
1514 if (!LastBitfieldTypeSize && !FieldSize)
1515 FieldAlign = 1;
1516
Eli Friedman2782dac2013-06-26 20:50:34 +00001517 UnfilledBitsInLastUnit = 0;
1518 LastBitfieldTypeSize = 0;
1519 }
1520 }
1521
John McCall30268ca2014-01-29 07:53:44 +00001522 // If the field is wider than its declared type, it follows
1523 // different rules in all cases.
Anders Carlsson57235162010-04-16 15:57:11 +00001524 if (FieldSize > TypeSize) {
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001525 LayoutWideBitField(FieldSize, TypeSize, FieldPacked, D);
Anders Carlsson57235162010-04-16 15:57:11 +00001526 return;
1527 }
1528
John McCall30268ca2014-01-29 07:53:44 +00001529 // Compute the next available bit offset.
1530 uint64_t FieldOffset =
1531 IsUnion ? 0 : (getDataSizeInBits() - UnfilledBitsInLastUnit);
1532
1533 // Handle targets that don't honor bitfield type alignment.
John McCall76e1818a2014-02-13 00:50:08 +00001534 if (!IsMsStruct && !Context.getTargetInfo().useBitFieldTypeAlignment()) {
John McCall30268ca2014-01-29 07:53:44 +00001535 // Some such targets do honor it on zero-width bitfields.
1536 if (FieldSize == 0 &&
1537 Context.getTargetInfo().useZeroLengthBitfieldAlignment()) {
1538 // The alignment to round up to is the max of the field's natural
1539 // alignment and a target-specific fixed value (sometimes zero).
1540 unsigned ZeroLengthBitfieldBoundary =
1541 Context.getTargetInfo().getZeroLengthBitfieldBoundary();
1542 FieldAlign = std::max(FieldAlign, ZeroLengthBitfieldBoundary);
1543
1544 // If that doesn't apply, just ignore the field alignment.
1545 } else {
1546 FieldAlign = 1;
1547 }
1548 }
1549
1550 // Remember the alignment we would have used if the field were not packed.
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001551 unsigned UnpackedFieldAlign = FieldAlign;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001552
Yunzhong Gao5fd0c9d2014-02-13 02:45:10 +00001553 // Ignore the field alignment if the field is packed unless it has zero-size.
1554 if (!IsMsStruct && FieldPacked && FieldSize != 0)
Anders Carlsson07209442009-11-22 17:37:31 +00001555 FieldAlign = 1;
Anders Carlsson07209442009-11-22 17:37:31 +00001556
John McCall30268ca2014-01-29 07:53:44 +00001557 // But, if there's an 'aligned' attribute on the field, honor that.
1558 if (unsigned ExplicitFieldAlign = D->getMaxAlignment()) {
1559 FieldAlign = std::max(FieldAlign, ExplicitFieldAlign);
1560 UnpackedFieldAlign = std::max(UnpackedFieldAlign, ExplicitFieldAlign);
1561 }
1562
1563 // But, if there's a #pragma pack in play, that takes precedent over
1564 // even the 'aligned' attribute, for non-zero-width bitfields.
1565 if (!MaxFieldAlignment.isZero() && FieldSize) {
Ken Dyck02ced6f2011-02-17 01:49:42 +00001566 unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment);
1567 FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1568 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001569 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001570
John McCall30268ca2014-01-29 07:53:44 +00001571 // For purposes of diagnostics, we're going to simultaneously
1572 // compute the field offsets that we would have used if we weren't
1573 // adding any alignment padding or if the field weren't packed.
1574 uint64_t UnpaddedFieldOffset = FieldOffset;
1575 uint64_t UnpackedFieldOffset = FieldOffset;
1576
1577 // Check if we need to add padding to fit the bitfield within an
1578 // allocation unit with the right size and alignment. The rules are
1579 // somewhat different here for ms_struct structs.
1580 if (IsMsStruct) {
1581 // If it's not a zero-width bitfield, and we can fit the bitfield
1582 // into the active storage unit (and we haven't already decided to
1583 // start a new storage unit), just do so, regardless of any other
1584 // other consideration. Otherwise, round up to the right alignment.
1585 if (FieldSize == 0 || FieldSize > UnfilledBitsInLastUnit) {
1586 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
1587 UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1588 UnpackedFieldAlign);
1589 UnfilledBitsInLastUnit = 0;
1590 }
1591
1592 } else {
1593 // #pragma pack, with any value, suppresses the insertion of padding.
1594 bool AllowPadding = MaxFieldAlignment.isZero();
1595
1596 // Compute the real offset.
1597 if (FieldSize == 0 ||
1598 (AllowPadding &&
1599 (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)) {
1600 FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
1601 }
1602
1603 // Repeat the computation for diagnostic purposes.
1604 if (FieldSize == 0 ||
1605 (AllowPadding &&
1606 (UnpackedFieldOffset & (UnpackedFieldAlign-1)) + FieldSize > TypeSize))
1607 UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1608 UnpackedFieldAlign);
Eli Friedman2782dac2013-06-26 20:50:34 +00001609 }
1610
John McCall30268ca2014-01-29 07:53:44 +00001611 // If we're using external layout, give the external layout a chance
1612 // to override this information.
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001613 if (UseExternalLayout)
Douglas Gregor44ba7892012-01-28 00:53:29 +00001614 FieldOffset = updateExternalFieldOffset(D, FieldOffset);
1615
John McCall30268ca2014-01-29 07:53:44 +00001616 // Okay, place the bitfield at the calculated offset.
Anders Carlsson07209442009-11-22 17:37:31 +00001617 FieldOffsets.push_back(FieldOffset);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001618
John McCall30268ca2014-01-29 07:53:44 +00001619 // Bookkeeping:
1620
1621 // Anonymous members don't affect the overall record alignment,
1622 // except on targets where they do.
1623 if (!IsMsStruct &&
1624 !Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
1625 !D->getIdentifier())
1626 FieldAlign = UnpackedFieldAlign = 1;
1627
1628 // Diagnose differences in layout due to padding or packing.
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001629 if (!UseExternalLayout)
Douglas Gregore9fc3772012-01-26 07:55:45 +00001630 CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset,
1631 UnpackedFieldAlign, FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001632
Anders Carlssonba958402009-11-22 19:13:51 +00001633 // Update DataSize to include the last byte containing (part of) the bitfield.
John McCall30268ca2014-01-29 07:53:44 +00001634
1635 // For unions, this is just a max operation, as usual.
Anders Carlssonba958402009-11-22 19:13:51 +00001636 if (IsUnion) {
Artyom Skrobov5e63acc2014-10-17 10:22:03 +00001637 uint64_t RoundedFieldSize = roundUpSizeToCharAlignment(FieldSize,
1638 Context);
1639 setDataSize(std::max(getDataSizeInBits(), RoundedFieldSize));
John McCall30268ca2014-01-29 07:53:44 +00001640 // For non-zero-width bitfields in ms_struct structs, allocate a new
1641 // storage unit if necessary.
1642 } else if (IsMsStruct && FieldSize) {
1643 // We should have cleared UnfilledBitsInLastUnit in every case
1644 // where we changed storage units.
1645 if (!UnfilledBitsInLastUnit) {
1646 setDataSize(FieldOffset + TypeSize);
1647 UnfilledBitsInLastUnit = TypeSize;
Eli Friedman2782dac2013-06-26 20:50:34 +00001648 }
John McCall30268ca2014-01-29 07:53:44 +00001649 UnfilledBitsInLastUnit -= FieldSize;
1650 LastBitfieldTypeSize = TypeSize;
1651
1652 // Otherwise, bump the data size up to include the bitfield,
1653 // including padding up to char alignment, and then remember how
1654 // bits we didn't use.
1655 } else {
1656 uint64_t NewSizeInBits = FieldOffset + FieldSize;
1657 uint64_t CharAlignment = Context.getTargetInfo().getCharAlign();
1658 setDataSize(llvm::RoundUpToAlignment(NewSizeInBits, CharAlignment));
1659 UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
1660
1661 // The only time we can get here for an ms_struct is if this is a
1662 // zero-width bitfield, which doesn't count as anything for the
1663 // purposes of unfilled bits.
1664 LastBitfieldTypeSize = 0;
Anders Carlssonba958402009-11-22 19:13:51 +00001665 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001666
Anders Carlssonba958402009-11-22 19:13:51 +00001667 // Update the size.
Ken Dyckecfc7552011-02-24 01:13:28 +00001668 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001669
Anders Carlsson07209442009-11-22 17:37:31 +00001670 // Remember max struct/class alignment.
Ken Dyck85ef0432011-02-19 18:58:07 +00001671 UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign),
1672 Context.toCharUnitsFromBits(UnpackedFieldAlign));
Anders Carlsson07209442009-11-22 17:37:31 +00001673}
1674
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001675void RecordLayoutBuilder::LayoutField(const FieldDecl *D,
1676 bool InsertExtraPadding) {
Anders Carlsson07209442009-11-22 17:37:31 +00001677 if (D->isBitField()) {
1678 LayoutBitField(D);
1679 return;
1680 }
1681
Eli Friedman2782dac2013-06-26 20:50:34 +00001682 uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001683
Anders Carlssonba958402009-11-22 19:13:51 +00001684 // Reset the unfilled bits.
Eli Friedman2782dac2013-06-26 20:50:34 +00001685 UnfilledBitsInLastUnit = 0;
1686 LastBitfieldTypeSize = 0;
Anders Carlssonba958402009-11-22 19:13:51 +00001687
Anders Carlsson07209442009-11-22 17:37:31 +00001688 bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
Ken Dyck6d90e892011-02-20 02:06:09 +00001689 CharUnits FieldOffset =
Ken Dyckecfc7552011-02-24 01:13:28 +00001690 IsUnion ? CharUnits::Zero() : getDataSize();
Ken Dyck6d90e892011-02-20 02:06:09 +00001691 CharUnits FieldSize;
1692 CharUnits FieldAlign;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001693
Anders Carlsson07209442009-11-22 17:37:31 +00001694 if (D->getType()->isIncompleteArrayType()) {
1695 // This is a flexible array member; we can't directly
1696 // query getTypeInfo about these, so we figure it out here.
1697 // Flexible array members don't have any size, but they
1698 // have to be aligned appropriately for their element type.
Ken Dyck6d90e892011-02-20 02:06:09 +00001699 FieldSize = CharUnits::Zero();
Anders Carlsson5efc56e2010-04-16 15:07:51 +00001700 const ArrayType* ATy = Context.getAsArrayType(D->getType());
Ken Dyck6d90e892011-02-20 02:06:09 +00001701 FieldAlign = Context.getTypeAlignInChars(ATy->getElementType());
Anders Carlsson07209442009-11-22 17:37:31 +00001702 } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) {
1703 unsigned AS = RT->getPointeeType().getAddressSpace();
Ken Dyck6d90e892011-02-20 02:06:09 +00001704 FieldSize =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001705 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(AS));
Ken Dyck6d90e892011-02-20 02:06:09 +00001706 FieldAlign =
Douglas Gregore8bbc122011-09-02 00:18:52 +00001707 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(AS));
Anders Carlsson79474332009-07-18 20:20:21 +00001708 } else {
Ken Dyck6d90e892011-02-20 02:06:09 +00001709 std::pair<CharUnits, CharUnits> FieldInfo =
1710 Context.getTypeInfoInChars(D->getType());
Anders Carlsson07209442009-11-22 17:37:31 +00001711 FieldSize = FieldInfo.first;
1712 FieldAlign = FieldInfo.second;
Chad Rosier18903ee2011-08-04 01:21:14 +00001713
Eli Friedman9ee2d0472012-10-12 23:29:20 +00001714 if (IsMsStruct) {
Douglas Gregordbe39272011-02-01 15:15:22 +00001715 // If MS bitfield layout is required, figure out what type is being
1716 // laid out and align the field to the width of that type.
1717
1718 // Resolve all typedefs down to their base type and round up the field
1719 // alignment if necessary.
1720 QualType T = Context.getBaseElementType(D->getType());
1721 if (const BuiltinType *BTy = T->getAs<BuiltinType>()) {
Ken Dyck6d90e892011-02-20 02:06:09 +00001722 CharUnits TypeSize = Context.getTypeSizeInChars(BTy);
Douglas Gregordbe39272011-02-01 15:15:22 +00001723 if (TypeSize > FieldAlign)
1724 FieldAlign = TypeSize;
1725 }
1726 }
Anders Carlsson79474332009-07-18 20:20:21 +00001727 }
Mike Stump11289f42009-09-09 15:08:12 +00001728
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001729 // The align if the field is not packed. This is to check if the attribute
1730 // was unnecessary (-Wpacked).
Ken Dyck6d90e892011-02-20 02:06:09 +00001731 CharUnits UnpackedFieldAlign = FieldAlign;
1732 CharUnits UnpackedFieldOffset = FieldOffset;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001733
Anders Carlsson07209442009-11-22 17:37:31 +00001734 if (FieldPacked)
Ken Dyck6d90e892011-02-20 02:06:09 +00001735 FieldAlign = CharUnits::One();
1736 CharUnits MaxAlignmentInChars =
1737 Context.toCharUnitsFromBits(D->getMaxAlignment());
1738 FieldAlign = std::max(FieldAlign, MaxAlignmentInChars);
1739 UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars);
Anders Carlsson07209442009-11-22 17:37:31 +00001740
1741 // The maximum field alignment overrides the aligned attribute.
Ken Dyck02ced6f2011-02-17 01:49:42 +00001742 if (!MaxFieldAlignment.isZero()) {
Ken Dyck6d90e892011-02-20 02:06:09 +00001743 FieldAlign = std::min(FieldAlign, MaxFieldAlignment);
1744 UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001745 }
Anders Carlsson07209442009-11-22 17:37:31 +00001746
Douglas Gregor44ba7892012-01-28 00:53:29 +00001747 // Round up the current record size to the field's alignment boundary.
1748 FieldOffset = FieldOffset.RoundUpToAlignment(FieldAlign);
1749 UnpackedFieldOffset =
1750 UnpackedFieldOffset.RoundUpToAlignment(UnpackedFieldAlign);
1751
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001752 if (UseExternalLayout) {
Douglas Gregor44ba7892012-01-28 00:53:29 +00001753 FieldOffset = Context.toCharUnitsFromBits(
1754 updateExternalFieldOffset(D, Context.toBits(FieldOffset)));
1755
1756 if (!IsUnion && EmptySubobjects) {
1757 // Record the fact that we're placing a field at this offset.
1758 bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset);
1759 (void)Allowed;
1760 assert(Allowed && "Externally-placed field cannot be placed here");
1761 }
1762 } else {
Douglas Gregore9fc3772012-01-26 07:55:45 +00001763 if (!IsUnion && EmptySubobjects) {
1764 // Check if we can place the field at this offset.
1765 while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) {
1766 // We couldn't place the field at the offset. Try again at a new offset.
1767 FieldOffset += FieldAlign;
1768 }
Anders Carlsson07209442009-11-22 17:37:31 +00001769 }
Anders Carlsson07209442009-11-22 17:37:31 +00001770 }
Douglas Gregore9fc3772012-01-26 07:55:45 +00001771
Anders Carlsson79474332009-07-18 20:20:21 +00001772 // Place this field at the current location.
Ken Dyck6d90e892011-02-20 02:06:09 +00001773 FieldOffsets.push_back(Context.toBits(FieldOffset));
Mike Stump11289f42009-09-09 15:08:12 +00001774
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001775 if (!UseExternalLayout)
1776 CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset,
Douglas Gregore9fc3772012-01-26 07:55:45 +00001777 Context.toBits(UnpackedFieldOffset),
1778 Context.toBits(UnpackedFieldAlign), FieldPacked, D);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001779
Kostya Serebryany68c29da2014-10-27 19:34:10 +00001780 if (InsertExtraPadding) {
Kostya Serebryany293dc9b2014-10-16 20:54:52 +00001781 CharUnits ASanAlignment = CharUnits::fromQuantity(8);
1782 CharUnits ExtraSizeForAsan = ASanAlignment;
1783 if (FieldSize % ASanAlignment)
1784 ExtraSizeForAsan +=
1785 ASanAlignment - CharUnits::fromQuantity(FieldSize % ASanAlignment);
1786 FieldSize += ExtraSizeForAsan;
1787 }
1788
Anders Carlsson79474332009-07-18 20:20:21 +00001789 // Reserve space for this field.
Eli Friedman43f18342012-01-12 23:27:03 +00001790 uint64_t FieldSizeInBits = Context.toBits(FieldSize);
Anders Carlsson79474332009-07-18 20:20:21 +00001791 if (IsUnion)
Eli Friedman2e108372012-01-12 23:48:56 +00001792 setDataSize(std::max(getDataSizeInBits(), FieldSizeInBits));
Anders Carlsson79474332009-07-18 20:20:21 +00001793 else
Eli Friedman2e108372012-01-12 23:48:56 +00001794 setDataSize(FieldOffset + FieldSize);
Mike Stump11289f42009-09-09 15:08:12 +00001795
Eli Friedman2e108372012-01-12 23:48:56 +00001796 // Update the size.
1797 setSize(std::max(getSizeInBits(), getDataSizeInBits()));
Mike Stump11289f42009-09-09 15:08:12 +00001798
Anders Carlsson79474332009-07-18 20:20:21 +00001799 // Remember max struct/class alignment.
Ken Dyck6d90e892011-02-20 02:06:09 +00001800 UpdateAlignment(FieldAlign, UnpackedFieldAlign);
Anders Carlsson79474332009-07-18 20:20:21 +00001801}
1802
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001803void RecordLayoutBuilder::FinishLayout(const NamedDecl *D) {
Anders Carlsson79474332009-07-18 20:20:21 +00001804 // In C++, records cannot be of size 0.
David Blaikiebbafb8a2012-03-11 07:00:24 +00001805 if (Context.getLangOpts().CPlusPlus && getSizeInBits() == 0) {
Fariborz Jahanian09b23312011-02-02 19:36:18 +00001806 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
1807 // Compatibility with gcc requires a class (pod or non-pod)
1808 // which is not empty but of size 0; such as having fields of
1809 // array of zero-length, remains of Size 0
1810 if (RD->isEmpty())
Ken Dyck1b4420e2011-02-28 02:01:38 +00001811 setSize(CharUnits::One());
Fariborz Jahanian09b23312011-02-02 19:36:18 +00001812 }
1813 else
Ken Dyck1b4420e2011-02-28 02:01:38 +00001814 setSize(CharUnits::One());
Fariborz Jahanian09b23312011-02-02 19:36:18 +00001815 }
Eli Friedman83a12582011-12-01 00:37:01 +00001816
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001817 // Finally, round the size of the record up to the alignment of the
1818 // record itself.
Eli Friedman2782dac2013-06-26 20:50:34 +00001819 uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastUnit;
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001820 uint64_t UnpackedSizeInBits =
1821 llvm::RoundUpToAlignment(getSizeInBits(),
1822 Context.toBits(UnpackedAlignment));
1823 CharUnits UnpackedSize = Context.toCharUnitsFromBits(UnpackedSizeInBits);
1824 uint64_t RoundedSize
1825 = llvm::RoundUpToAlignment(getSizeInBits(), Context.toBits(Alignment));
1826
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001827 if (UseExternalLayout) {
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001828 // If we're inferring alignment, and the external size is smaller than
1829 // our size after we've rounded up to alignment, conservatively set the
1830 // alignment to 1.
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001831 if (InferAlignment && External.Size < RoundedSize) {
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001832 Alignment = CharUnits::One();
1833 InferAlignment = false;
1834 }
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001835 setSize(External.Size);
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001836 return;
1837 }
1838
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001839 // Set the size to the final size.
1840 setSize(RoundedSize);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001841
Douglas Gregore8bbc122011-09-02 00:18:52 +00001842 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001843 if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1844 // Warn if padding was introduced to the struct/class/union.
Ken Dyckecfc7552011-02-24 01:13:28 +00001845 if (getSizeInBits() > UnpaddedSize) {
1846 unsigned PadSize = getSizeInBits() - UnpaddedSize;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001847 bool InBits = true;
1848 if (PadSize % CharBitNum == 0) {
1849 PadSize = PadSize / CharBitNum;
1850 InBits = false;
1851 }
1852 Diag(RD->getLocation(), diag::warn_padded_struct_size)
1853 << Context.getTypeDeclType(RD)
1854 << PadSize
1855 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
1856 }
1857
1858 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
1859 // bother since there won't be alignment issues.
Ken Dyckecfc7552011-02-24 01:13:28 +00001860 if (Packed && UnpackedAlignment > CharUnits::One() &&
Ken Dyck1b4420e2011-02-28 02:01:38 +00001861 getSize() == UnpackedSize)
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001862 Diag(D->getLocation(), diag::warn_unnecessary_packed)
1863 << Context.getTypeDeclType(RD);
1864 }
Anders Carlsson79474332009-07-18 20:20:21 +00001865}
1866
Ken Dyck85ef0432011-02-19 18:58:07 +00001867void RecordLayoutBuilder::UpdateAlignment(CharUnits NewAlignment,
1868 CharUnits UnpackedNewAlignment) {
Douglas Gregore9fc3772012-01-26 07:55:45 +00001869 // The alignment is not modified when using 'mac68k' alignment or when
Douglas Gregor44ba7892012-01-28 00:53:29 +00001870 // we have an externally-supplied layout that also provides overall alignment.
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001871 if (IsMac68kAlign || (UseExternalLayout && !InferAlignment))
Daniel Dunbar6da10982010-05-27 05:45:51 +00001872 return;
1873
Ken Dyck85ef0432011-02-19 18:58:07 +00001874 if (NewAlignment > Alignment) {
Reid Kleckner5a63d702015-03-24 23:46:25 +00001875 assert(llvm::isPowerOf2_64(NewAlignment.getQuantity()) &&
1876 "Alignment not a power of 2");
Ken Dyck85ef0432011-02-19 18:58:07 +00001877 Alignment = NewAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001878 }
1879
Ken Dyck85ef0432011-02-19 18:58:07 +00001880 if (UnpackedNewAlignment > UnpackedAlignment) {
Reid Kleckner5a63d702015-03-24 23:46:25 +00001881 assert(llvm::isPowerOf2_64(UnpackedNewAlignment.getQuantity()) &&
1882 "Alignment not a power of 2");
Ken Dyck85ef0432011-02-19 18:58:07 +00001883 UnpackedAlignment = UnpackedNewAlignment;
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001884 }
1885}
1886
Douglas Gregor44ba7892012-01-28 00:53:29 +00001887uint64_t
1888RecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field,
1889 uint64_t ComputedOffset) {
Reid Kleckner8b6d0342015-02-25 19:17:45 +00001890 uint64_t ExternalFieldOffset = External.getExternalFieldOffset(Field);
NAKAMURA Takumi472041f2015-02-25 10:32:20 +00001891
Douglas Gregor44ba7892012-01-28 00:53:29 +00001892 if (InferAlignment && ExternalFieldOffset < ComputedOffset) {
1893 // The externally-supplied field offset is before the field offset we
1894 // computed. Assume that the structure is packed.
Douglas Gregor1423a5c2012-10-26 22:31:14 +00001895 Alignment = CharUnits::One();
Douglas Gregor44ba7892012-01-28 00:53:29 +00001896 InferAlignment = false;
1897 }
1898
1899 // Use the externally-supplied field offset.
Benjamin Kramer648e68b2012-08-31 22:14:25 +00001900 return ExternalFieldOffset;
1901}
1902
1903/// \brief Get diagnostic %select index for tag kind for
1904/// field padding diagnostic message.
1905/// WARNING: Indexes apply to particular diagnostics only!
1906///
1907/// \returns diagnostic %select index.
1908static unsigned getPaddingDiagFromTagKind(TagTypeKind Tag) {
1909 switch (Tag) {
1910 case TTK_Struct: return 0;
1911 case TTK_Interface: return 1;
1912 case TTK_Class: return 2;
1913 default: llvm_unreachable("Invalid tag kind for field padding diagnostic!");
1914 }
1915}
1916
1917void RecordLayoutBuilder::CheckFieldPadding(uint64_t Offset,
1918 uint64_t UnpaddedOffset,
1919 uint64_t UnpackedOffset,
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001920 unsigned UnpackedAlign,
1921 bool isPacked,
1922 const FieldDecl *D) {
1923 // We let objc ivars without warning, objc interfaces generally are not used
1924 // for padding tricks.
1925 if (isa<ObjCIvarDecl>(D))
Anders Carlsson79474332009-07-18 20:20:21 +00001926 return;
Mike Stump11289f42009-09-09 15:08:12 +00001927
Ted Kremenekfed48af2011-09-06 19:40:45 +00001928 // Don't warn about structs created without a SourceLocation. This can
1929 // be done by clients of the AST, such as codegen.
1930 if (D->getLocation().isInvalid())
1931 return;
1932
Douglas Gregore8bbc122011-09-02 00:18:52 +00001933 unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
Mike Stump11289f42009-09-09 15:08:12 +00001934
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001935 // Warn if padding was introduced to the struct/class.
1936 if (!IsUnion && Offset > UnpaddedOffset) {
1937 unsigned PadSize = Offset - UnpaddedOffset;
1938 bool InBits = true;
1939 if (PadSize % CharBitNum == 0) {
1940 PadSize = PadSize / CharBitNum;
1941 InBits = false;
Benjamin Kramer648e68b2012-08-31 22:14:25 +00001942 }
1943 if (D->getIdentifier())
1944 Diag(D->getLocation(), diag::warn_padded_struct_field)
1945 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
1946 << Context.getTypeDeclType(D->getParent())
1947 << PadSize
1948 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1) // plural or not
1949 << D->getIdentifier();
1950 else
1951 Diag(D->getLocation(), diag::warn_padded_struct_anon_field)
1952 << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
1953 << Context.getTypeDeclType(D->getParent())
1954 << PadSize
1955 << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00001956 }
1957
1958 // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
1959 // bother since there won't be alignment issues.
1960 if (isPacked && UnpackedAlign > CharBitNum && Offset == UnpackedOffset)
1961 Diag(D->getLocation(), diag::warn_unnecessary_packed)
1962 << D->getIdentifier();
Anders Carlsson79474332009-07-18 20:20:21 +00001963}
Mike Stump11289f42009-09-09 15:08:12 +00001964
John McCall6bd2a892013-01-25 22:31:03 +00001965static const CXXMethodDecl *computeKeyFunction(ASTContext &Context,
1966 const CXXRecordDecl *RD) {
Daniel Dunbarccabe482010-04-19 20:44:53 +00001967 // If a class isn't polymorphic it doesn't have a key function.
Anders Carlsson5ebf8b42009-12-07 04:35:11 +00001968 if (!RD->isPolymorphic())
Craig Topper36250ad2014-05-12 05:36:57 +00001969 return nullptr;
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001970
Eli Friedman300f55d2011-06-10 21:53:06 +00001971 // A class that is not externally visible doesn't have a key function. (Or
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001972 // at least, there's no point to assigning a key function to such a class;
1973 // this doesn't affect the ABI.)
Rafael Espindola3ae00052013-05-13 00:12:11 +00001974 if (!RD->isExternallyVisible())
Craig Topper36250ad2014-05-12 05:36:57 +00001975 return nullptr;
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001976
Richard Smith750f5112014-03-24 23:54:09 +00001977 // Template instantiations don't have key functions per Itanium C++ ABI 5.2.6.
Argyrios Kyrtzidis8c64bbe2010-10-13 02:39:41 +00001978 // Same behavior as GCC.
1979 TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
1980 if (TSK == TSK_ImplicitInstantiation ||
Richard Smith750f5112014-03-24 23:54:09 +00001981 TSK == TSK_ExplicitInstantiationDeclaration ||
Argyrios Kyrtzidis8c64bbe2010-10-13 02:39:41 +00001982 TSK == TSK_ExplicitInstantiationDefinition)
Craig Topper36250ad2014-05-12 05:36:57 +00001983 return nullptr;
Argyrios Kyrtzidis8c64bbe2010-10-13 02:39:41 +00001984
John McCall6bd2a892013-01-25 22:31:03 +00001985 bool allowInlineFunctions =
1986 Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline();
1987
David Majnemerc964b4b2014-07-16 06:04:00 +00001988 for (const CXXMethodDecl *MD : RD->methods()) {
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001989 if (!MD->isVirtual())
1990 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001991
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00001992 if (MD->isPure())
1993 continue;
Eli Friedmanf2c79b62009-12-08 03:56:49 +00001994
Anders Carlssonf98849e2009-12-02 17:15:43 +00001995 // Ignore implicit member functions, they are always marked as inline, but
1996 // they don't have a body until they're defined.
1997 if (MD->isImplicit())
1998 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00001999
Douglas Gregora318efd2010-01-05 19:06:31 +00002000 if (MD->isInlineSpecified())
2001 continue;
Eli Friedman71a26d82009-12-06 20:50:05 +00002002
2003 if (MD->hasInlineBody())
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002004 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002005
Benjamin Kramer4a902082012-08-03 15:43:22 +00002006 // Ignore inline deleted or defaulted functions.
Benjamin Kramer73d1be72012-08-03 08:39:58 +00002007 if (!MD->isUserProvided())
2008 continue;
2009
John McCall6bd2a892013-01-25 22:31:03 +00002010 // In certain ABIs, ignore functions with out-of-line inline definitions.
2011 if (!allowInlineFunctions) {
2012 const FunctionDecl *Def;
2013 if (MD->hasBody(Def) && Def->isInlineSpecified())
2014 continue;
2015 }
2016
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002017 // We found it.
2018 return MD;
2019 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00002020
Craig Topper36250ad2014-05-12 05:36:57 +00002021 return nullptr;
Anders Carlssonb1d3f7c2009-11-30 23:41:22 +00002022}
2023
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002024DiagnosticBuilder
2025RecordLayoutBuilder::Diag(SourceLocation Loc, unsigned DiagID) {
Argyrios Kyrtzidisd0040642010-11-18 20:06:41 +00002026 return Context.getDiagnostics().Report(Loc, DiagID);
Argyrios Kyrtzidisca0d0cd2010-09-22 14:32:24 +00002027}
2028
John McCall5c1f1d02013-01-29 01:14:22 +00002029/// Does the target C++ ABI require us to skip over the tail-padding
2030/// of the given class (considering it as a base class) when allocating
2031/// objects?
2032static bool mustSkipTailPadding(TargetCXXABI ABI, const CXXRecordDecl *RD) {
2033 switch (ABI.getTailPaddingUseRules()) {
2034 case TargetCXXABI::AlwaysUseTailPadding:
2035 return false;
2036
2037 case TargetCXXABI::UseTailPaddingUnlessPOD03:
2038 // FIXME: To the extent that this is meant to cover the Itanium ABI
2039 // rules, we should implement the restrictions about over-sized
2040 // bitfields:
2041 //
2042 // http://mentorembedded.github.com/cxx-abi/abi.html#POD :
2043 // In general, a type is considered a POD for the purposes of
2044 // layout if it is a POD type (in the sense of ISO C++
2045 // [basic.types]). However, a POD-struct or POD-union (in the
2046 // sense of ISO C++ [class]) with a bitfield member whose
2047 // declared width is wider than the declared type of the
2048 // bitfield is not a POD for the purpose of layout. Similarly,
2049 // an array type is not a POD for the purpose of layout if the
2050 // element type of the array is not a POD for the purpose of
2051 // layout.
2052 //
2053 // Where references to the ISO C++ are made in this paragraph,
2054 // the Technical Corrigendum 1 version of the standard is
2055 // intended.
2056 return RD->isPOD();
2057
2058 case TargetCXXABI::UseTailPaddingUnlessPOD11:
2059 // This is equivalent to RD->getTypeForDecl().isCXX11PODType(),
2060 // but with a lot of abstraction penalty stripped off. This does
2061 // assume that these properties are set correctly even in C++98
2062 // mode; fortunately, that is true because we want to assign
2063 // consistently semantics to the type-traits intrinsics (or at
2064 // least as many of them as possible).
2065 return RD->isTrivial() && RD->isStandardLayout();
2066 }
2067
2068 llvm_unreachable("bad tail-padding use kind");
2069}
2070
Warren Hunt8f8bad72013-10-11 20:19:00 +00002071static bool isMsLayout(const RecordDecl* D) {
Warren Hunt55d8e822013-10-23 23:53:07 +00002072 return D->getASTContext().getTargetInfo().getCXXABI().isMicrosoft();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002073}
2074
2075// This section contains an implementation of struct layout that is, up to the
Warren Hunt917f97f2014-04-11 00:54:15 +00002076// included tests, compatible with cl.exe (2013). The layout produced is
Warren Hunt8f8bad72013-10-11 20:19:00 +00002077// significantly different than those produced by the Itanium ABI. Here we note
2078// the most important differences.
2079//
2080// * The alignment of bitfields in unions is ignored when computing the
2081// alignment of the union.
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002082// * The existence of zero-width bitfield that occurs after anything other than
Warren Hunt8f8bad72013-10-11 20:19:00 +00002083// a non-zero length bitfield is ignored.
Warren Hunt917f97f2014-04-11 00:54:15 +00002084// * There is no explicit primary base for the purposes of layout. All bases
2085// with vfptrs are laid out first, followed by all bases without vfptrs.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002086// * The Itanium equivalent vtable pointers are split into a vfptr (virtual
2087// function pointer) and a vbptr (virtual base pointer). They can each be
Warren Hunt55d8e822013-10-23 23:53:07 +00002088// shared with a, non-virtual bases. These bases need not be the same. vfptrs
Warren Hunt917f97f2014-04-11 00:54:15 +00002089// always occur at offset 0. vbptrs can occur at an arbitrary offset and are
2090// placed after the lexiographically last non-virtual base. This placement
2091// is always before fields but can be in the middle of the non-virtual bases
2092// due to the two-pass layout scheme for non-virtual-bases.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002093// * Virtual bases sometimes require a 'vtordisp' field that is laid out before
2094// the virtual base and is used in conjunction with virtual overrides during
Warren Hunt917f97f2014-04-11 00:54:15 +00002095// construction and destruction. This is always a 4 byte value and is used as
2096// an alternative to constructor vtables.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002097// * vtordisps are allocated in a block of memory with size and alignment equal
2098// to the alignment of the completed structure (before applying __declspec(
Warren Hunt55d8e822013-10-23 23:53:07 +00002099// align())). The vtordisp always occur at the end of the allocation block,
2100// immediately prior to the virtual base.
Warren Hunt917f97f2014-04-11 00:54:15 +00002101// * vfptrs are injected after all bases and fields have been laid out. In
2102// order to guarantee proper alignment of all fields, the vfptr injection
2103// pushes all bases and fields back by the alignment imposed by those bases
2104// and fields. This can potentially add a significant amount of padding.
2105// vfptrs are always injected at offset 0.
2106// * vbptrs are injected after all bases and fields have been laid out. In
2107// order to guarantee proper alignment of all fields, the vfptr injection
2108// pushes all bases and fields back by the alignment imposed by those bases
2109// and fields. This can potentially add a significant amount of padding.
2110// vbptrs are injected immediately after the last non-virtual base as
2111// lexiographically ordered in the code. If this site isn't pointer aligned
2112// the vbptr is placed at the next properly aligned location. Enough padding
2113// is added to guarantee a fit.
2114// * The last zero sized non-virtual base can be placed at the end of the
2115// struct (potentially aliasing another object), or may alias with the first
2116// field, even if they are of the same type.
2117// * The last zero size virtual base may be placed at the end of the struct
2118// potentially aliasing another object.
Warren Hunt049f6732013-12-06 19:54:25 +00002119// * The ABI attempts to avoid aliasing of zero sized bases by adding padding
2120// between bases or vbases with specific properties. The criteria for
2121// additional padding between two bases is that the first base is zero sized
Warren Hunt39a907b2014-04-09 21:57:24 +00002122// or ends with a zero sized subobject and the second base is zero sized or
Warren Hunt917f97f2014-04-11 00:54:15 +00002123// trails with a zero sized base or field (sharing of vfptrs can reorder the
2124// layout of the so the leading base is not always the first one declared).
2125// This rule does take into account fields that are not records, so padding
2126// will occur even if the last field is, e.g. an int. The padding added for
2127// bases is 1 byte. The padding added between vbases depends on the alignment
2128// of the object but is at least 4 bytes (in both 32 and 64 bit modes).
2129// * There is no concept of non-virtual alignment, non-virtual alignment and
2130// alignment are always identical.
2131// * There is a distinction between alignment and required alignment.
2132// __declspec(align) changes the required alignment of a struct. This
2133// alignment is _always_ obeyed, even in the presence of #pragma pack. A
Justin Bogner2ca9a4a2014-10-08 05:45:39 +00002134// record inherits required alignment from all of its fields and bases.
Warren Huntf4518def2014-01-10 01:28:05 +00002135// * __declspec(align) on bitfields has the effect of changing the bitfield's
Warren Hunt917f97f2014-04-11 00:54:15 +00002136// alignment instead of its required alignment. This is the only known way
2137// to make the alignment of a struct bigger than 8. Interestingly enough
2138// this alignment is also immune to the effects of #pragma pack and can be
2139// used to create structures with large alignment under #pragma pack.
2140// However, because it does not impact required alignment, such a structure,
2141// when used as a field or base, will not be aligned if #pragma pack is
2142// still active at the time of use.
2143//
Alp Toker08f6e9e2014-05-05 19:53:42 +00002144// Known incompatibilities:
Warren Hunt917f97f2014-04-11 00:54:15 +00002145// * all: #pragma pack between fields in a record
2146// * 2010 and back: If the last field in a record is a bitfield, every object
2147// laid out after the record will have extra padding inserted before it. The
2148// extra padding will have size equal to the size of the storage class of the
2149// bitfield. 0 sized bitfields don't exhibit this behavior and the extra
2150// padding can be avoided by adding a 0 sized bitfield after the non-zero-
2151// sized bitfield.
2152// * 2012 and back: In 64-bit mode, if the alignment of a record is 16 or
2153// greater due to __declspec(align()) then a second layout phase occurs after
2154// The locations of the vf and vb pointers are known. This layout phase
2155// suffers from the "last field is a bitfield" bug in 2010 and results in
2156// _every_ field getting padding put in front of it, potentially including the
2157// vfptr, leaving the vfprt at a non-zero location which results in a fault if
2158// anything tries to read the vftbl. The second layout phase also treats
Alp Toker08f6e9e2014-05-05 19:53:42 +00002159// bitfields as separate entities and gives them each storage rather than
Warren Hunt917f97f2014-04-11 00:54:15 +00002160// packing them. Additionally, because this phase appears to perform a
2161// (an unstable) sort on the members before laying them out and because merged
2162// bitfields have the same address, the bitfields end up in whatever order
2163// the sort left them in, a behavior we could never hope to replicate.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002164
2165namespace {
2166struct MicrosoftRecordLayoutBuilder {
Warren Huntd640d7d2014-01-09 00:30:56 +00002167 struct ElementInfo {
2168 CharUnits Size;
2169 CharUnits Alignment;
2170 };
Warren Hunt8f8bad72013-10-11 20:19:00 +00002171 typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
2172 MicrosoftRecordLayoutBuilder(const ASTContext &Context) : Context(Context) {}
2173private:
Aaron Ballmanabc18922015-02-15 22:54:08 +00002174 MicrosoftRecordLayoutBuilder(const MicrosoftRecordLayoutBuilder &) = delete;
2175 void operator=(const MicrosoftRecordLayoutBuilder &) = delete;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002176public:
Warren Hunt8f8bad72013-10-11 20:19:00 +00002177 void layout(const RecordDecl *RD);
2178 void cxxLayout(const CXXRecordDecl *RD);
2179 /// \brief Initializes size and alignment and honors some flags.
2180 void initializeLayout(const RecordDecl *RD);
2181 /// \brief Initialized C++ layout, compute alignment and virtual alignment and
Alp Tokerf6a24ce2013-12-05 16:25:25 +00002182 /// existence of vfptrs and vbptrs. Alignment is needed before the vfptr is
Warren Hunt8f8bad72013-10-11 20:19:00 +00002183 /// laid out.
2184 void initializeCXXLayout(const CXXRecordDecl *RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002185 void layoutNonVirtualBases(const CXXRecordDecl *RD);
Warren Huntd640d7d2014-01-09 00:30:56 +00002186 void layoutNonVirtualBase(const CXXRecordDecl *BaseDecl,
2187 const ASTRecordLayout &BaseLayout,
2188 const ASTRecordLayout *&PreviousBaseLayout);
2189 void injectVFPtr(const CXXRecordDecl *RD);
2190 void injectVBPtr(const CXXRecordDecl *RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002191 /// \brief Lays out the fields of the record. Also rounds size up to
2192 /// alignment.
2193 void layoutFields(const RecordDecl *RD);
2194 void layoutField(const FieldDecl *FD);
2195 void layoutBitField(const FieldDecl *FD);
2196 /// \brief Lays out a single zero-width bit-field in the record and handles
2197 /// special cases associated with zero-width bit-fields.
2198 void layoutZeroWidthBitField(const FieldDecl *FD);
2199 void layoutVirtualBases(const CXXRecordDecl *RD);
Warren Hunt1603e522013-12-10 01:44:39 +00002200 void finalizeLayout(const RecordDecl *RD);
Warren Huntd640d7d2014-01-09 00:30:56 +00002201 /// \brief Gets the size and alignment of a base taking pragma pack and
2202 /// __declspec(align) into account.
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002203 ElementInfo getAdjustedElementInfo(const ASTRecordLayout &Layout);
Warren Huntd640d7d2014-01-09 00:30:56 +00002204 /// \brief Gets the size and alignment of a field taking pragma pack and
2205 /// __declspec(align) into account. It also updates RequiredAlignment as a
2206 /// side effect because it is most convenient to do so here.
2207 ElementInfo getAdjustedElementInfo(const FieldDecl *FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002208 /// \brief Places a field at an offset in CharUnits.
2209 void placeFieldAtOffset(CharUnits FieldOffset) {
2210 FieldOffsets.push_back(Context.toBits(FieldOffset));
2211 }
2212 /// \brief Places a bitfield at a bit offset.
2213 void placeFieldAtBitOffset(uint64_t FieldOffset) {
2214 FieldOffsets.push_back(FieldOffset);
2215 }
2216 /// \brief Compute the set of virtual bases for which vtordisps are required.
David Majnemerc2e67532014-09-23 22:58:15 +00002217 void computeVtorDispSet(
2218 llvm::SmallPtrSetImpl<const CXXRecordDecl *> &HasVtorDispSet,
2219 const CXXRecordDecl *RD) const;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002220 const ASTContext &Context;
2221 /// \brief The size of the record being laid out.
2222 CharUnits Size;
Warren Huntf6ec7482014-02-21 01:40:35 +00002223 /// \brief The non-virtual size of the record layout.
2224 CharUnits NonVirtualSize;
2225 /// \brief The data size of the record layout.
Warren Huntd640d7d2014-01-09 00:30:56 +00002226 CharUnits DataSize;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002227 /// \brief The current alignment of the record layout.
2228 CharUnits Alignment;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002229 /// \brief The maximum allowed field alignment. This is set by #pragma pack.
2230 CharUnits MaxFieldAlignment;
Warren Hunt7b252d22013-12-06 00:01:17 +00002231 /// \brief The alignment that this record must obey. This is imposed by
2232 /// __declspec(align()) on the record itself or one of its fields or bases.
2233 CharUnits RequiredAlignment;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002234 /// \brief The size of the allocation of the currently active bitfield.
2235 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield
2236 /// is true.
2237 CharUnits CurrentBitfieldSize;
Warren Huntd640d7d2014-01-09 00:30:56 +00002238 /// \brief Offset to the virtual base table pointer (if one exists).
2239 CharUnits VBPtrOffset;
David Majnemer00a061d2014-09-30 06:45:43 +00002240 /// \brief Minimum record size possible.
2241 CharUnits MinEmptyStructSize;
Warren Huntd640d7d2014-01-09 00:30:56 +00002242 /// \brief The size and alignment info of a pointer.
2243 ElementInfo PointerInfo;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002244 /// \brief The primary base class (if one exists).
2245 const CXXRecordDecl *PrimaryBase;
2246 /// \brief The class we share our vb-pointer with.
2247 const CXXRecordDecl *SharedVBPtrBase;
Warren Huntd640d7d2014-01-09 00:30:56 +00002248 /// \brief The collection of field offsets.
2249 SmallVector<uint64_t, 16> FieldOffsets;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002250 /// \brief Base classes and their offsets in the record.
2251 BaseOffsetsMapTy Bases;
2252 /// \brief virtual base classes and their offsets in the record.
2253 ASTRecordLayout::VBaseOffsetsMapTy VBases;
Warren Huntd640d7d2014-01-09 00:30:56 +00002254 /// \brief The number of remaining bits in our last bitfield allocation.
2255 /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield is
2256 /// true.
2257 unsigned RemainingBitsInField;
2258 bool IsUnion : 1;
2259 /// \brief True if the last field laid out was a bitfield and was not 0
2260 /// width.
2261 bool LastFieldIsNonZeroWidthBitfield : 1;
2262 /// \brief True if the class has its own vftable pointer.
2263 bool HasOwnVFPtr : 1;
2264 /// \brief True if the class has a vbtable pointer.
2265 bool HasVBPtr : 1;
Warren Hunt39a907b2014-04-09 21:57:24 +00002266 /// \brief True if the last sub-object within the type is zero sized or the
2267 /// object itself is zero sized. This *does not* count members that are not
2268 /// records. Only used for MS-ABI.
2269 bool EndsWithZeroSizedObject : 1;
Warren Hunt049f6732013-12-06 19:54:25 +00002270 /// \brief True if this class is zero sized or first base is zero sized or
2271 /// has this property. Only used for MS-ABI.
2272 bool LeadsWithZeroSizedBase : 1;
Reid Kleckner8b6d0342015-02-25 19:17:45 +00002273
2274 /// \brief True if the external AST source provided a layout for this record.
2275 bool UseExternalLayout : 1;
2276
2277 /// \brief The layout provided by the external AST source. Only active if
2278 /// UseExternalLayout is true.
2279 ExternalLayout External;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002280};
2281} // namespace
2282
Warren Huntd640d7d2014-01-09 00:30:56 +00002283MicrosoftRecordLayoutBuilder::ElementInfo
2284MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002285 const ASTRecordLayout &Layout) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002286 ElementInfo Info;
2287 Info.Alignment = Layout.getAlignment();
2288 // Respect pragma pack.
Warren Hunt7b252d22013-12-06 00:01:17 +00002289 if (!MaxFieldAlignment.isZero())
Warren Huntd640d7d2014-01-09 00:30:56 +00002290 Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
2291 // Track zero-sized subobjects here where it's already available.
Warren Hunt39a907b2014-04-09 21:57:24 +00002292 EndsWithZeroSizedObject = Layout.hasZeroSizedSubObject();
Warren Huntd640d7d2014-01-09 00:30:56 +00002293 // Respect required alignment, this is necessary because we may have adjusted
Warren Hunt94258912014-01-11 01:16:40 +00002294 // the alignment in the case of pragam pack. Note that the required alignment
2295 // doesn't actually apply to the struct alignment at this point.
2296 Alignment = std::max(Alignment, Info.Alignment);
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002297 RequiredAlignment = std::max(RequiredAlignment, Layout.getRequiredAlignment());
Warren Huntd640d7d2014-01-09 00:30:56 +00002298 Info.Alignment = std::max(Info.Alignment, Layout.getRequiredAlignment());
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002299 Info.Size = Layout.getNonVirtualSize();
Warren Huntd640d7d2014-01-09 00:30:56 +00002300 return Info;
Warren Hunt7b252d22013-12-06 00:01:17 +00002301}
2302
Warren Huntd640d7d2014-01-09 00:30:56 +00002303MicrosoftRecordLayoutBuilder::ElementInfo
2304MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
2305 const FieldDecl *FD) {
David Majnemer34b57492014-07-30 01:30:47 +00002306 // Get the alignment of the field type's natural alignment, ignore any
2307 // alignment attributes.
Warren Huntd640d7d2014-01-09 00:30:56 +00002308 ElementInfo Info;
Benjamin Kramer867ea1d2014-03-02 13:01:17 +00002309 std::tie(Info.Size, Info.Alignment) =
David Majnemer34b57492014-07-30 01:30:47 +00002310 Context.getTypeInfoInChars(FD->getType()->getUnqualifiedDesugaredType());
2311 // Respect align attributes on the field.
2312 CharUnits FieldRequiredAlignment =
Warren Huntf4518def2014-01-10 01:28:05 +00002313 Context.toCharUnitsFromBits(FD->getMaxAlignment());
David Majnemer34b57492014-07-30 01:30:47 +00002314 // Respect align attributes on the type.
2315 if (Context.isAlignmentRequired(FD->getType()))
2316 FieldRequiredAlignment = std::max(
2317 Context.getTypeAlignInChars(FD->getType()), FieldRequiredAlignment);
Warren Hunt049f6732013-12-06 19:54:25 +00002318 // Respect attributes applied to subobjects of the field.
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002319 if (FD->isBitField())
2320 // For some reason __declspec align impacts alignment rather than required
2321 // alignment when it is applied to bitfields.
Warren Huntf4518def2014-01-10 01:28:05 +00002322 Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002323 else {
2324 if (auto RT =
2325 FD->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
2326 auto const &Layout = Context.getASTRecordLayout(RT->getDecl());
2327 EndsWithZeroSizedObject = Layout.hasZeroSizedSubObject();
2328 FieldRequiredAlignment = std::max(FieldRequiredAlignment,
2329 Layout.getRequiredAlignment());
2330 }
Warren Huntf4518def2014-01-10 01:28:05 +00002331 // Capture required alignment as a side-effect.
2332 RequiredAlignment = std::max(RequiredAlignment, FieldRequiredAlignment);
2333 }
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002334 // Respect pragma pack, attribute pack and declspec align
2335 if (!MaxFieldAlignment.isZero())
2336 Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
2337 if (FD->hasAttr<PackedAttr>())
2338 Info.Alignment = CharUnits::One();
2339 Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002340 return Info;
2341}
2342
2343void MicrosoftRecordLayoutBuilder::layout(const RecordDecl *RD) {
David Majnemer00a061d2014-09-30 06:45:43 +00002344 // For C record layout, zero-sized records always have size 4.
2345 MinEmptyStructSize = CharUnits::fromQuantity(4);
Warren Huntd640d7d2014-01-09 00:30:56 +00002346 initializeLayout(RD);
2347 layoutFields(RD);
2348 DataSize = Size = Size.RoundUpToAlignment(Alignment);
David Majnemer79a1c892014-02-12 00:43:02 +00002349 RequiredAlignment = std::max(
2350 RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
Warren Huntd640d7d2014-01-09 00:30:56 +00002351 finalizeLayout(RD);
2352}
2353
2354void MicrosoftRecordLayoutBuilder::cxxLayout(const CXXRecordDecl *RD) {
David Majnemer00a061d2014-09-30 06:45:43 +00002355 // The C++ standard says that empty structs have size 1.
2356 MinEmptyStructSize = CharUnits::One();
Warren Huntd640d7d2014-01-09 00:30:56 +00002357 initializeLayout(RD);
2358 initializeCXXLayout(RD);
2359 layoutNonVirtualBases(RD);
2360 layoutFields(RD);
Warren Huntc89450e2014-03-24 21:37:27 +00002361 injectVBPtr(RD);
2362 injectVFPtr(RD);
2363 if (HasOwnVFPtr || (HasVBPtr && !SharedVBPtrBase))
2364 Alignment = std::max(Alignment, PointerInfo.Alignment);
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002365 auto RoundingAlignment = Alignment;
2366 if (!MaxFieldAlignment.isZero())
2367 RoundingAlignment = std::min(RoundingAlignment, MaxFieldAlignment);
2368 NonVirtualSize = Size = Size.RoundUpToAlignment(RoundingAlignment);
David Majnemer79a1c892014-02-12 00:43:02 +00002369 RequiredAlignment = std::max(
2370 RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
Warren Huntd640d7d2014-01-09 00:30:56 +00002371 layoutVirtualBases(RD);
2372 finalizeLayout(RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002373}
2374
2375void MicrosoftRecordLayoutBuilder::initializeLayout(const RecordDecl *RD) {
2376 IsUnion = RD->isUnion();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002377 Size = CharUnits::Zero();
2378 Alignment = CharUnits::One();
Warren Hunt7b252d22013-12-06 00:01:17 +00002379 // In 64-bit mode we always perform an alignment step after laying out vbases.
2380 // In 32-bit mode we do not. The check to see if we need to perform alignment
2381 // checks the RequiredAlignment field and performs alignment if it isn't 0.
David Majnemer37ea5782015-04-24 01:24:59 +00002382 RequiredAlignment = Context.getTargetInfo().getTriple().isArch64Bit()
2383 ? CharUnits::One()
2384 : CharUnits::Zero();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002385 // Compute the maximum field alignment.
2386 MaxFieldAlignment = CharUnits::Zero();
2387 // Honor the default struct packing maximum alignment flag.
2388 if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct)
Warren Huntf4518def2014-01-10 01:28:05 +00002389 MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
2390 // Honor the packing attribute. The MS-ABI ignores pragma pack if its larger
2391 // than the pointer size.
2392 if (const MaxFieldAlignmentAttr *MFAA = RD->getAttr<MaxFieldAlignmentAttr>()){
2393 unsigned PackedAlignment = MFAA->getAlignment();
2394 if (PackedAlignment <= Context.getTargetInfo().getPointerWidth(0))
2395 MaxFieldAlignment = Context.toCharUnitsFromBits(PackedAlignment);
2396 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002397 // Packed attribute forces max field alignment to be 1.
2398 if (RD->hasAttr<PackedAttr>())
2399 MaxFieldAlignment = CharUnits::One();
Reid Kleckner8b6d0342015-02-25 19:17:45 +00002400
2401 // Try to respect the external layout if present.
2402 UseExternalLayout = false;
2403 if (ExternalASTSource *Source = Context.getExternalSource())
2404 UseExternalLayout = Source->layoutRecordType(
2405 RD, External.Size, External.Align, External.FieldOffsets,
2406 External.BaseOffsets, External.VirtualBaseOffsets);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002407}
2408
Warren Hunt8f8bad72013-10-11 20:19:00 +00002409void
2410MicrosoftRecordLayoutBuilder::initializeCXXLayout(const CXXRecordDecl *RD) {
Warren Hunt39a907b2014-04-09 21:57:24 +00002411 EndsWithZeroSizedObject = false;
Warren Hunt049f6732013-12-06 19:54:25 +00002412 LeadsWithZeroSizedBase = false;
Warren Huntd640d7d2014-01-09 00:30:56 +00002413 HasOwnVFPtr = false;
2414 HasVBPtr = false;
Craig Topper36250ad2014-05-12 05:36:57 +00002415 PrimaryBase = nullptr;
2416 SharedVBPtrBase = nullptr;
Warren Huntd640d7d2014-01-09 00:30:56 +00002417 // Calculate pointer size and alignment. These are used for vfptr and vbprt
2418 // injection.
2419 PointerInfo.Size =
2420 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
David Majnemer37ea5782015-04-24 01:24:59 +00002421 PointerInfo.Alignment =
2422 Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
Warren Huntd640d7d2014-01-09 00:30:56 +00002423 // Respect pragma pack.
2424 if (!MaxFieldAlignment.isZero())
2425 PointerInfo.Alignment = std::min(PointerInfo.Alignment, MaxFieldAlignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002426}
2427
2428void
2429MicrosoftRecordLayoutBuilder::layoutNonVirtualBases(const CXXRecordDecl *RD) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002430 // The MS-ABI lays out all bases that contain leading vfptrs before it lays
2431 // out any bases that do not contain vfptrs. We implement this as two passes
2432 // over the bases. This approach guarantees that the primary base is laid out
2433 // first. We use these passes to calculate some additional aggregated
2434 // information about the bases, such as reqruied alignment and the presence of
2435 // zero sized members.
Craig Topper36250ad2014-05-12 05:36:57 +00002436 const ASTRecordLayout *PreviousBaseLayout = nullptr;
Warren Huntd640d7d2014-01-09 00:30:56 +00002437 // Iterate through the bases and lay out the non-virtual ones.
David Majnemerc964b4b2014-07-16 06:04:00 +00002438 for (const CXXBaseSpecifier &Base : RD->bases()) {
2439 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002440 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
Warren Huntd640d7d2014-01-09 00:30:56 +00002441 // Mark and skip virtual bases.
David Majnemerc964b4b2014-07-16 06:04:00 +00002442 if (Base.isVirtual()) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002443 HasVBPtr = true;
2444 continue;
2445 }
2446 // Check fo a base to share a VBPtr with.
2447 if (!SharedVBPtrBase && BaseLayout.hasVBPtr()) {
2448 SharedVBPtrBase = BaseDecl;
2449 HasVBPtr = true;
2450 }
2451 // Only lay out bases with extendable VFPtrs on the first pass.
2452 if (!BaseLayout.hasExtendableVFPtr())
2453 continue;
2454 // If we don't have a primary base, this one qualifies.
Warren Huntbadf9e02014-01-13 19:55:52 +00002455 if (!PrimaryBase) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002456 PrimaryBase = BaseDecl;
Warren Huntbadf9e02014-01-13 19:55:52 +00002457 LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
2458 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002459 // Lay out the base.
2460 layoutNonVirtualBase(BaseDecl, BaseLayout, PreviousBaseLayout);
2461 }
2462 // Figure out if we need a fresh VFPtr for this class.
2463 if (!PrimaryBase && RD->isDynamicClass())
2464 for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2465 e = RD->method_end();
2466 !HasOwnVFPtr && i != e; ++i)
2467 HasOwnVFPtr = i->isVirtual() && i->size_overridden_methods() == 0;
2468 // If we don't have a primary base then we have a leading object that could
2469 // itself lead with a zero-sized object, something we track.
2470 bool CheckLeadingLayout = !PrimaryBase;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002471 // Iterate through the bases and lay out the non-virtual ones.
David Majnemerc964b4b2014-07-16 06:04:00 +00002472 for (const CXXBaseSpecifier &Base : RD->bases()) {
2473 if (Base.isVirtual())
Warren Hunt8f8bad72013-10-11 20:19:00 +00002474 continue;
David Majnemerc964b4b2014-07-16 06:04:00 +00002475 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002476 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2477 // Only lay out bases without extendable VFPtrs on the second pass.
Warren Huntbb9c3c32014-04-10 23:23:34 +00002478 if (BaseLayout.hasExtendableVFPtr()) {
2479 VBPtrOffset = Bases[BaseDecl] + BaseLayout.getNonVirtualSize();
Warren Hunt4431fe62013-12-12 22:33:37 +00002480 continue;
Warren Huntbb9c3c32014-04-10 23:23:34 +00002481 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002482 // If this is the first layout, check to see if it leads with a zero sized
2483 // object. If it does, so do we.
2484 if (CheckLeadingLayout) {
2485 CheckLeadingLayout = false;
2486 LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
Warren Hunt049f6732013-12-06 19:54:25 +00002487 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002488 // Lay out the base.
2489 layoutNonVirtualBase(BaseDecl, BaseLayout, PreviousBaseLayout);
Warren Huntbb9c3c32014-04-10 23:23:34 +00002490 VBPtrOffset = Bases[BaseDecl] + BaseLayout.getNonVirtualSize();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002491 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002492 // Set our VBPtroffset if we know it at this point.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002493 if (!HasVBPtr)
2494 VBPtrOffset = CharUnits::fromQuantity(-1);
Warren Hunt6eba9072014-01-14 00:31:30 +00002495 else if (SharedVBPtrBase) {
2496 const ASTRecordLayout &Layout = Context.getASTRecordLayout(SharedVBPtrBase);
2497 VBPtrOffset = Bases[SharedVBPtrBase] + Layout.getVBPtrOffset();
2498 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002499}
2500
2501void MicrosoftRecordLayoutBuilder::layoutNonVirtualBase(
2502 const CXXRecordDecl *BaseDecl,
2503 const ASTRecordLayout &BaseLayout,
2504 const ASTRecordLayout *&PreviousBaseLayout) {
Warren Huntf4518def2014-01-10 01:28:05 +00002505 // Insert padding between two bases if the left first one is zero sized or
2506 // contains a zero sized subobject and the right is zero sized or one leads
2507 // with a zero sized base.
2508 if (PreviousBaseLayout && PreviousBaseLayout->hasZeroSizedSubObject() &&
2509 BaseLayout.leadsWithZeroSizedBase())
2510 Size++;
2511 ElementInfo Info = getAdjustedElementInfo(BaseLayout);
Reid Kleckner8b6d0342015-02-25 19:17:45 +00002512 CharUnits BaseOffset;
2513
2514 // Respect the external AST source base offset, if present.
2515 bool FoundBase = false;
2516 if (UseExternalLayout) {
2517 FoundBase = External.getExternalNVBaseOffset(BaseDecl, BaseOffset);
2518 if (FoundBase)
2519 assert(BaseOffset >= Size && "base offset already allocated");
2520 }
2521
2522 if (!FoundBase)
2523 BaseOffset = Size.RoundUpToAlignment(Info.Alignment);
Warren Huntf4518def2014-01-10 01:28:05 +00002524 Bases.insert(std::make_pair(BaseDecl, BaseOffset));
Warren Huntf6ec7482014-02-21 01:40:35 +00002525 Size = BaseOffset + BaseLayout.getNonVirtualSize();
Warren Huntf4518def2014-01-10 01:28:05 +00002526 PreviousBaseLayout = &BaseLayout;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002527}
2528
2529void MicrosoftRecordLayoutBuilder::layoutFields(const RecordDecl *RD) {
2530 LastFieldIsNonZeroWidthBitfield = false;
David Majnemerc964b4b2014-07-16 06:04:00 +00002531 for (const FieldDecl *Field : RD->fields())
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00002532 layoutField(Field);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002533}
2534
2535void MicrosoftRecordLayoutBuilder::layoutField(const FieldDecl *FD) {
2536 if (FD->isBitField()) {
2537 layoutBitField(FD);
2538 return;
2539 }
2540 LastFieldIsNonZeroWidthBitfield = false;
Warren Huntd640d7d2014-01-09 00:30:56 +00002541 ElementInfo Info = getAdjustedElementInfo(FD);
David Majnemeradc45bb2014-04-13 08:15:50 +00002542 Alignment = std::max(Alignment, Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002543 if (IsUnion) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002544 placeFieldAtOffset(CharUnits::Zero());
2545 Size = std::max(Size, Info.Size);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002546 } else {
Reid Kleckner8b6d0342015-02-25 19:17:45 +00002547 CharUnits FieldOffset;
2548 if (UseExternalLayout) {
2549 FieldOffset =
2550 Context.toCharUnitsFromBits(External.getExternalFieldOffset(FD));
2551 assert(FieldOffset >= Size && "field offset already allocated");
2552 } else {
2553 FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
2554 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002555 placeFieldAtOffset(FieldOffset);
Warren Huntd640d7d2014-01-09 00:30:56 +00002556 Size = FieldOffset + Info.Size;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002557 }
2558}
2559
2560void MicrosoftRecordLayoutBuilder::layoutBitField(const FieldDecl *FD) {
2561 unsigned Width = FD->getBitWidthValue(Context);
2562 if (Width == 0) {
2563 layoutZeroWidthBitField(FD);
2564 return;
2565 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002566 ElementInfo Info = getAdjustedElementInfo(FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002567 // Clamp the bitfield to a containable size for the sake of being able
2568 // to lay them out. Sema will throw an error.
Warren Huntd640d7d2014-01-09 00:30:56 +00002569 if (Width > Context.toBits(Info.Size))
2570 Width = Context.toBits(Info.Size);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002571 // Check to see if this bitfield fits into an existing allocation. Note:
2572 // MSVC refuses to pack bitfields of formal types with different sizes
2573 // into the same allocation.
2574 if (!IsUnion && LastFieldIsNonZeroWidthBitfield &&
Warren Huntd640d7d2014-01-09 00:30:56 +00002575 CurrentBitfieldSize == Info.Size && Width <= RemainingBitsInField) {
Warren Hunt8f8bad72013-10-11 20:19:00 +00002576 placeFieldAtBitOffset(Context.toBits(Size) - RemainingBitsInField);
2577 RemainingBitsInField -= Width;
2578 return;
2579 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002580 LastFieldIsNonZeroWidthBitfield = true;
Warren Huntd640d7d2014-01-09 00:30:56 +00002581 CurrentBitfieldSize = Info.Size;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002582 if (IsUnion) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002583 placeFieldAtOffset(CharUnits::Zero());
2584 Size = std::max(Size, Info.Size);
David Majnemeradc45bb2014-04-13 08:15:50 +00002585 // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002586 } else {
2587 // Allocate a new block of memory and place the bitfield in it.
Warren Huntd640d7d2014-01-09 00:30:56 +00002588 CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002589 placeFieldAtOffset(FieldOffset);
Warren Huntd640d7d2014-01-09 00:30:56 +00002590 Size = FieldOffset + Info.Size;
David Majnemeradc45bb2014-04-13 08:15:50 +00002591 Alignment = std::max(Alignment, Info.Alignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002592 RemainingBitsInField = Context.toBits(Info.Size) - Width;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002593 }
2594}
2595
2596void
2597MicrosoftRecordLayoutBuilder::layoutZeroWidthBitField(const FieldDecl *FD) {
2598 // Zero-width bitfields are ignored unless they follow a non-zero-width
2599 // bitfield.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002600 if (!LastFieldIsNonZeroWidthBitfield) {
2601 placeFieldAtOffset(IsUnion ? CharUnits::Zero() : Size);
2602 // TODO: Add a Sema warning that MS ignores alignment for zero
Alp Tokerd4733632013-12-05 04:47:09 +00002603 // sized bitfields that occur after zero-size bitfields or non-bitfields.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002604 return;
2605 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002606 LastFieldIsNonZeroWidthBitfield = false;
Warren Huntd640d7d2014-01-09 00:30:56 +00002607 ElementInfo Info = getAdjustedElementInfo(FD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002608 if (IsUnion) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002609 placeFieldAtOffset(CharUnits::Zero());
2610 Size = std::max(Size, Info.Size);
David Majnemeradc45bb2014-04-13 08:15:50 +00002611 // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
Warren Hunt8f8bad72013-10-11 20:19:00 +00002612 } else {
2613 // Round up the current record size to the field's alignment boundary.
Warren Huntd640d7d2014-01-09 00:30:56 +00002614 CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002615 placeFieldAtOffset(FieldOffset);
2616 Size = FieldOffset;
David Majnemeradc45bb2014-04-13 08:15:50 +00002617 Alignment = std::max(Alignment, Info.Alignment);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002618 }
2619}
2620
Warren Huntd640d7d2014-01-09 00:30:56 +00002621void MicrosoftRecordLayoutBuilder::injectVBPtr(const CXXRecordDecl *RD) {
Warren Hunt6eba9072014-01-14 00:31:30 +00002622 if (!HasVBPtr || SharedVBPtrBase)
Warren Huntd640d7d2014-01-09 00:30:56 +00002623 return;
Warren Huntd640d7d2014-01-09 00:30:56 +00002624 // Inject the VBPointer at the injection site.
2625 CharUnits InjectionSite = VBPtrOffset;
2626 // But before we do, make sure it's properly aligned.
2627 VBPtrOffset = VBPtrOffset.RoundUpToAlignment(PointerInfo.Alignment);
Reid Kleckner8b6d0342015-02-25 19:17:45 +00002628 // Shift everything after the vbptr down, unless we're using an external
2629 // layout.
2630 if (UseExternalLayout)
2631 return;
Warren Huntd640d7d2014-01-09 00:30:56 +00002632 // Determine where the first field should be laid out after the vbptr.
2633 CharUnits FieldStart = VBPtrOffset + PointerInfo.Size;
2634 // Make sure that the amount we push the fields back by is a multiple of the
2635 // alignment.
David Majnemer79a1c892014-02-12 00:43:02 +00002636 CharUnits Offset = (FieldStart - InjectionSite).RoundUpToAlignment(
2637 std::max(RequiredAlignment, Alignment));
Warren Huntd640d7d2014-01-09 00:30:56 +00002638 Size += Offset;
David Majnemerc964b4b2014-07-16 06:04:00 +00002639 for (uint64_t &FieldOffset : FieldOffsets)
2640 FieldOffset += Context.toBits(Offset);
2641 for (BaseOffsetsMapTy::value_type &Base : Bases)
2642 if (Base.second >= InjectionSite)
2643 Base.second += Offset;
Warren Huntd640d7d2014-01-09 00:30:56 +00002644}
2645
2646void MicrosoftRecordLayoutBuilder::injectVFPtr(const CXXRecordDecl *RD) {
2647 if (!HasOwnVFPtr)
2648 return;
2649 // Make sure that the amount we push the struct back by is a multiple of the
2650 // alignment.
David Majnemer79a1c892014-02-12 00:43:02 +00002651 CharUnits Offset = PointerInfo.Size.RoundUpToAlignment(
2652 std::max(RequiredAlignment, Alignment));
Warren Huntd640d7d2014-01-09 00:30:56 +00002653 // Increase the size of the object and push back all fields, the vbptr and all
2654 // bases by the offset amount.
2655 Size += Offset;
David Majnemerc964b4b2014-07-16 06:04:00 +00002656 for (uint64_t &FieldOffset : FieldOffsets)
2657 FieldOffset += Context.toBits(Offset);
Warren Huntd640d7d2014-01-09 00:30:56 +00002658 if (HasVBPtr)
2659 VBPtrOffset += Offset;
David Majnemerc964b4b2014-07-16 06:04:00 +00002660 for (BaseOffsetsMapTy::value_type &Base : Bases)
2661 Base.second += Offset;
Warren Huntd640d7d2014-01-09 00:30:56 +00002662}
2663
Warren Hunt8f8bad72013-10-11 20:19:00 +00002664void MicrosoftRecordLayoutBuilder::layoutVirtualBases(const CXXRecordDecl *RD) {
2665 if (!HasVBPtr)
2666 return;
Warren Huntd640d7d2014-01-09 00:30:56 +00002667 // Vtordisps are always 4 bytes (even in 64-bit mode)
2668 CharUnits VtorDispSize = CharUnits::fromQuantity(4);
2669 CharUnits VtorDispAlignment = VtorDispSize;
2670 // vtordisps respect pragma pack.
2671 if (!MaxFieldAlignment.isZero())
2672 VtorDispAlignment = std::min(VtorDispAlignment, MaxFieldAlignment);
2673 // The alignment of the vtordisp is at least the required alignment of the
2674 // entire record. This requirement may be present to support vtordisp
2675 // injection.
David Majnemerc964b4b2014-07-16 06:04:00 +00002676 for (const CXXBaseSpecifier &VBase : RD->vbases()) {
2677 const CXXRecordDecl *BaseDecl = VBase.getType()->getAsCXXRecordDecl();
David Majnemer79a1c892014-02-12 00:43:02 +00002678 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2679 RequiredAlignment =
2680 std::max(RequiredAlignment, BaseLayout.getRequiredAlignment());
2681 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002682 VtorDispAlignment = std::max(VtorDispAlignment, RequiredAlignment);
2683 // Compute the vtordisp set.
David Majnemerc2e67532014-09-23 22:58:15 +00002684 llvm::SmallPtrSet<const CXXRecordDecl *, 2> HasVtorDispSet;
2685 computeVtorDispSet(HasVtorDispSet, RD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002686 // Iterate through the virtual bases and lay them out.
Craig Topper36250ad2014-05-12 05:36:57 +00002687 const ASTRecordLayout *PreviousBaseLayout = nullptr;
David Majnemerc964b4b2014-07-16 06:04:00 +00002688 for (const CXXBaseSpecifier &VBase : RD->vbases()) {
2689 const CXXRecordDecl *BaseDecl = VBase.getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002690 const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
David Majnemerc2e67532014-09-23 22:58:15 +00002691 bool HasVtordisp = HasVtorDispSet.count(BaseDecl) > 0;
Warren Huntd640d7d2014-01-09 00:30:56 +00002692 // Insert padding between two bases if the left first one is zero sized or
2693 // contains a zero sized subobject and the right is zero sized or one leads
2694 // with a zero sized base. The padding between virtual bases is 4
2695 // bytes (in both 32 and 64 bits modes) and always involves rounding up to
2696 // the required alignment, we don't know why.
Warren Hunt4f7efb72014-04-12 00:20:50 +00002697 if ((PreviousBaseLayout && PreviousBaseLayout->hasZeroSizedSubObject() &&
David Majnemerbf3d4302014-07-16 07:16:58 +00002698 BaseLayout.leadsWithZeroSizedBase()) || HasVtordisp) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002699 Size = Size.RoundUpToAlignment(VtorDispAlignment) + VtorDispSize;
David Majnemera2464682014-07-17 00:55:19 +00002700 Alignment = std::max(VtorDispAlignment, Alignment);
David Majnemerbf3d4302014-07-16 07:16:58 +00002701 }
Warren Huntd640d7d2014-01-09 00:30:56 +00002702 // Insert the virtual base.
2703 ElementInfo Info = getAdjustedElementInfo(BaseLayout);
Reid Kleckner8b6d0342015-02-25 19:17:45 +00002704 CharUnits BaseOffset;
2705
2706 // Respect the external AST source base offset, if present.
2707 bool FoundBase = false;
2708 if (UseExternalLayout) {
2709 FoundBase = External.getExternalVBaseOffset(BaseDecl, BaseOffset);
2710 if (FoundBase)
2711 assert(BaseOffset >= Size && "base offset already allocated");
2712 }
2713 if (!FoundBase)
2714 BaseOffset = Size.RoundUpToAlignment(Info.Alignment);
2715
Warren Huntd640d7d2014-01-09 00:30:56 +00002716 VBases.insert(std::make_pair(BaseDecl,
2717 ASTRecordLayout::VBaseInfo(BaseOffset, HasVtordisp)));
Warren Huntf6ec7482014-02-21 01:40:35 +00002718 Size = BaseOffset + BaseLayout.getNonVirtualSize();
Warren Huntd640d7d2014-01-09 00:30:56 +00002719 PreviousBaseLayout = &BaseLayout;
Warren Hunt8f8bad72013-10-11 20:19:00 +00002720 }
2721}
2722
Warren Huntc3384312013-12-11 22:28:32 +00002723void MicrosoftRecordLayoutBuilder::finalizeLayout(const RecordDecl *RD) {
Warren Huntd640d7d2014-01-09 00:30:56 +00002724 // Respect required alignment. Note that in 32-bit mode Required alignment
David Majnemer00a061d2014-09-30 06:45:43 +00002725 // may be 0 and cause size not to be updated.
Warren Huntf6ec7482014-02-21 01:40:35 +00002726 DataSize = Size;
Warren Huntd640d7d2014-01-09 00:30:56 +00002727 if (!RequiredAlignment.isZero()) {
2728 Alignment = std::max(Alignment, RequiredAlignment);
Warren Hunt5d9eebf2014-04-10 22:15:18 +00002729 auto RoundingAlignment = Alignment;
2730 if (!MaxFieldAlignment.isZero())
2731 RoundingAlignment = std::min(RoundingAlignment, MaxFieldAlignment);
2732 RoundingAlignment = std::max(RoundingAlignment, RequiredAlignment);
2733 Size = Size.RoundUpToAlignment(RoundingAlignment);
Warren Huntd640d7d2014-01-09 00:30:56 +00002734 }
Warren Hunt049f6732013-12-06 19:54:25 +00002735 if (Size.isZero()) {
Warren Hunt39a907b2014-04-09 21:57:24 +00002736 EndsWithZeroSizedObject = true;
Warren Hunt049f6732013-12-06 19:54:25 +00002737 LeadsWithZeroSizedBase = true;
David Majnemer00a061d2014-09-30 06:45:43 +00002738 // Zero-sized structures have size equal to their alignment if a
2739 // __declspec(align) came into play.
2740 if (RequiredAlignment >= MinEmptyStructSize)
2741 Size = Alignment;
2742 else
2743 Size = MinEmptyStructSize;
Warren Hunt049f6732013-12-06 19:54:25 +00002744 }
Reid Kleckner8b6d0342015-02-25 19:17:45 +00002745
2746 if (UseExternalLayout) {
2747 Size = Context.toCharUnitsFromBits(External.Size);
2748 if (External.Align)
2749 Alignment = Context.toCharUnitsFromBits(External.Align);
2750 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002751}
2752
Warren Hunt73f43982014-04-11 22:05:28 +00002753// Recursively walks the non-virtual bases of a class and determines if any of
2754// them are in the bases with overridden methods set.
David Majnemer12727642014-07-16 06:30:31 +00002755static bool
2756RequiresVtordisp(const llvm::SmallPtrSetImpl<const CXXRecordDecl *> &
2757 BasesWithOverriddenMethods,
2758 const CXXRecordDecl *RD) {
Warren Hunt73f43982014-04-11 22:05:28 +00002759 if (BasesWithOverriddenMethods.count(RD))
Warren Hunt8f8bad72013-10-11 20:19:00 +00002760 return true;
2761 // If any of a virtual bases non-virtual bases (recursively) requires a
2762 // vtordisp than so does this virtual base.
David Majnemerc964b4b2014-07-16 06:04:00 +00002763 for (const CXXBaseSpecifier &Base : RD->bases())
2764 if (!Base.isVirtual() &&
Warren Hunt73f43982014-04-11 22:05:28 +00002765 RequiresVtordisp(BasesWithOverriddenMethods,
David Majnemerc964b4b2014-07-16 06:04:00 +00002766 Base.getType()->getAsCXXRecordDecl()))
Warren Hunt8f8bad72013-10-11 20:19:00 +00002767 return true;
2768 return false;
2769}
2770
David Majnemerc2e67532014-09-23 22:58:15 +00002771void MicrosoftRecordLayoutBuilder::computeVtorDispSet(
2772 llvm::SmallPtrSetImpl<const CXXRecordDecl *> &HasVtordispSet,
2773 const CXXRecordDecl *RD) const {
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00002774 // /vd2 or #pragma vtordisp(2): Always use vtordisps for virtual bases with
2775 // vftables.
2776 if (RD->getMSVtorDispMode() == MSVtorDispAttr::ForVFTable) {
David Majnemerc964b4b2014-07-16 06:04:00 +00002777 for (const CXXBaseSpecifier &Base : RD->vbases()) {
2778 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00002779 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
2780 if (Layout.hasExtendableVFPtr())
2781 HasVtordispSet.insert(BaseDecl);
2782 }
David Majnemerc2e67532014-09-23 22:58:15 +00002783 return;
Reid Klecknerc0dca6d2014-02-12 23:50:26 +00002784 }
2785
Warren Hunt8f8bad72013-10-11 20:19:00 +00002786 // If any of our bases need a vtordisp for this type, so do we. Check our
2787 // direct bases for vtordisp requirements.
David Majnemerc964b4b2014-07-16 06:04:00 +00002788 for (const CXXBaseSpecifier &Base : RD->bases()) {
2789 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Warren Hunt8f8bad72013-10-11 20:19:00 +00002790 const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
Reid Klecknercd612ab2014-04-11 16:57:42 +00002791 for (const auto &bi : Layout.getVBaseOffsetsMap())
2792 if (bi.second.hasVtorDisp())
2793 HasVtordispSet.insert(bi.first);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002794 }
David Majnemerd43388c2014-04-13 02:27:32 +00002795 // We don't introduce any additional vtordisps if either:
2796 // * A user declared constructor or destructor aren't declared.
2797 // * #pragma vtordisp(0) or the /vd0 flag are in use.
2798 if ((!RD->hasUserDeclaredConstructor() && !RD->hasUserDeclaredDestructor()) ||
2799 RD->getMSVtorDispMode() == MSVtorDispAttr::Never)
David Majnemerc2e67532014-09-23 22:58:15 +00002800 return;
David Majnemerd43388c2014-04-13 02:27:32 +00002801 // /vd1 or #pragma vtordisp(1): Try to guess based on whether we think it's
2802 // possible for a partially constructed object with virtual base overrides to
2803 // escape a non-trivial constructor.
2804 assert(RD->getMSVtorDispMode() == MSVtorDispAttr::ForVBaseOverride);
Warren Hunt73f43982014-04-11 22:05:28 +00002805 // Compute a set of base classes which define methods we override. A virtual
2806 // base in this set will require a vtordisp. A virtual base that transitively
2807 // contains one of these bases as a non-virtual base will also require a
2808 // vtordisp.
2809 llvm::SmallPtrSet<const CXXMethodDecl *, 8> Work;
2810 llvm::SmallPtrSet<const CXXRecordDecl *, 2> BasesWithOverriddenMethods;
David Majnemerc2e67532014-09-23 22:58:15 +00002811 // Seed the working set with our non-destructor, non-pure virtual methods.
David Majnemerc964b4b2014-07-16 06:04:00 +00002812 for (const CXXMethodDecl *MD : RD->methods())
David Majnemerc2e67532014-09-23 22:58:15 +00002813 if (MD->isVirtual() && !isa<CXXDestructorDecl>(MD) && !MD->isPure())
David Majnemerc964b4b2014-07-16 06:04:00 +00002814 Work.insert(MD);
Warren Hunt73f43982014-04-11 22:05:28 +00002815 while (!Work.empty()) {
2816 const CXXMethodDecl *MD = *Work.begin();
2817 CXXMethodDecl::method_iterator i = MD->begin_overridden_methods(),
2818 e = MD->end_overridden_methods();
2819 // If a virtual method has no-overrides it lives in its parent's vtable.
2820 if (i == e)
2821 BasesWithOverriddenMethods.insert(MD->getParent());
2822 else
2823 Work.insert(i, e);
2824 // We've finished processing this element, remove it from the working set.
2825 Work.erase(MD);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002826 }
Warren Hunt73f43982014-04-11 22:05:28 +00002827 // For each of our virtual bases, check if it is in the set of overridden
2828 // bases or if it transitively contains a non-virtual base that is.
David Majnemerc964b4b2014-07-16 06:04:00 +00002829 for (const CXXBaseSpecifier &Base : RD->vbases()) {
2830 const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
Warren Huntd640d7d2014-01-09 00:30:56 +00002831 if (!HasVtordispSet.count(BaseDecl) &&
Warren Hunt73f43982014-04-11 22:05:28 +00002832 RequiresVtordisp(BasesWithOverriddenMethods, BaseDecl))
Warren Huntd640d7d2014-01-09 00:30:56 +00002833 HasVtordispSet.insert(BaseDecl);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002834 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00002835}
2836
2837/// \brief Get or compute information about the layout of the specified record
2838/// (struct/union/class), which indicates its size and field position
2839/// information.
2840const ASTRecordLayout *
2841ASTContext::BuildMicrosoftASTRecordLayout(const RecordDecl *D) const {
2842 MicrosoftRecordLayoutBuilder Builder(*this);
2843 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2844 Builder.cxxLayout(RD);
2845 return new (*this) ASTRecordLayout(
Warren Hunt7b252d22013-12-06 00:01:17 +00002846 *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment,
Warren Huntd640d7d2014-01-09 00:30:56 +00002847 Builder.HasOwnVFPtr,
2848 Builder.HasOwnVFPtr || Builder.PrimaryBase,
Warren Huntf6ec7482014-02-21 01:40:35 +00002849 Builder.VBPtrOffset, Builder.NonVirtualSize, Builder.FieldOffsets.data(),
2850 Builder.FieldOffsets.size(), Builder.NonVirtualSize,
Warren Huntd640d7d2014-01-09 00:30:56 +00002851 Builder.Alignment, CharUnits::Zero(), Builder.PrimaryBase,
Warren Hunt049f6732013-12-06 19:54:25 +00002852 false, Builder.SharedVBPtrBase,
Warren Hunt39a907b2014-04-09 21:57:24 +00002853 Builder.EndsWithZeroSizedObject, Builder.LeadsWithZeroSizedBase,
Warren Hunt049f6732013-12-06 19:54:25 +00002854 Builder.Bases, Builder.VBases);
Warren Hunt8f8bad72013-10-11 20:19:00 +00002855 } else {
2856 Builder.layout(D);
2857 return new (*this) ASTRecordLayout(
Warren Hunt7b252d22013-12-06 00:01:17 +00002858 *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment,
2859 Builder.Size, Builder.FieldOffsets.data(), Builder.FieldOffsets.size());
Warren Hunt8f8bad72013-10-11 20:19:00 +00002860 }
2861}
2862
Anders Carlssondf291d82010-05-26 04:56:53 +00002863/// getASTRecordLayout - Get or compute information about the layout of the
2864/// specified record (struct/union/class), which indicates its size and field
2865/// position information.
Jay Foad39c79802011-01-12 09:06:06 +00002866const ASTRecordLayout &
2867ASTContext::getASTRecordLayout(const RecordDecl *D) const {
John McCall0710e552011-10-07 02:39:22 +00002868 // These asserts test different things. A record has a definition
2869 // as soon as we begin to parse the definition. That definition is
2870 // not a complete definition (which is what isDefinition() tests)
2871 // until we *finish* parsing the definition.
Sean Callanan56c19892012-02-08 00:04:52 +00002872
2873 if (D->hasExternalLexicalStorage() && !D->getDefinition())
2874 getExternalSource()->CompleteType(const_cast<RecordDecl*>(D));
2875
Anders Carlssondf291d82010-05-26 04:56:53 +00002876 D = D->getDefinition();
2877 assert(D && "Cannot get layout of forward declarations!");
Matt Beaumont-Gay35779952013-06-25 22:19:15 +00002878 assert(!D->isInvalidDecl() && "Cannot get layout of invalid decl!");
John McCallf937c022011-10-07 06:10:15 +00002879 assert(D->isCompleteDefinition() && "Cannot layout type before complete!");
Anders Carlssondf291d82010-05-26 04:56:53 +00002880
2881 // Look up this layout, if already laid out, return what we have.
2882 // Note that we can't save a reference to the entry because this function
2883 // is recursive.
2884 const ASTRecordLayout *Entry = ASTRecordLayouts[D];
2885 if (Entry) return *Entry;
2886
Craig Topper36250ad2014-05-12 05:36:57 +00002887 const ASTRecordLayout *NewEntry = nullptr;
Anders Carlssond2954862010-05-26 05:10:47 +00002888
Reid Kleckner8b6d0342015-02-25 19:17:45 +00002889 if (isMsLayout(D)) {
Warren Hunt8f8bad72013-10-11 20:19:00 +00002890 NewEntry = BuildMicrosoftASTRecordLayout(D);
2891 } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
Anders Carlssonc121b4e2010-05-27 00:07:01 +00002892 EmptySubobjectMap EmptySubobjects(*this, RD);
John McCall0153cd32011-11-08 04:01:03 +00002893 RecordLayoutBuilder Builder(*this, &EmptySubobjects);
2894 Builder.Layout(RD);
Anders Carlsson439edd12010-05-27 05:41:06 +00002895
John McCall5c1f1d02013-01-29 01:14:22 +00002896 // In certain situations, we are allowed to lay out objects in the
2897 // tail-padding of base classes. This is ABI-dependent.
2898 // FIXME: this should be stored in the record layout.
2899 bool skipTailPadding =
2900 mustSkipTailPadding(getTargetInfo().getCXXABI(), cast<CXXRecordDecl>(D));
Anders Carlssond2954862010-05-26 05:10:47 +00002901
2902 // FIXME: This should be done in FinalizeLayout.
Ken Dyck1b4420e2011-02-28 02:01:38 +00002903 CharUnits DataSize =
John McCall5c1f1d02013-01-29 01:14:22 +00002904 skipTailPadding ? Builder.getSize() : Builder.getDataSize();
Ken Dyck1b4420e2011-02-28 02:01:38 +00002905 CharUnits NonVirtualSize =
John McCall5c1f1d02013-01-29 01:14:22 +00002906 skipTailPadding ? DataSize : Builder.NonVirtualSize;
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002907 NewEntry =
John McCall0153cd32011-11-08 04:01:03 +00002908 new (*this) ASTRecordLayout(*this, Builder.getSize(),
2909 Builder.Alignment,
Warren Hunt7b252d22013-12-06 00:01:17 +00002910 /*RequiredAlignment : used by MS-ABI)*/
2911 Builder.Alignment,
John McCalle42a3362012-05-01 08:55:32 +00002912 Builder.HasOwnVFPtr,
Warren Hunt8f8bad72013-10-11 20:19:00 +00002913 RD->isDynamicClass(),
Warren Hunt55d8e822013-10-23 23:53:07 +00002914 CharUnits::fromQuantity(-1),
Ken Dyck1b4420e2011-02-28 02:01:38 +00002915 DataSize,
John McCall0153cd32011-11-08 04:01:03 +00002916 Builder.FieldOffsets.data(),
2917 Builder.FieldOffsets.size(),
Ken Dyckaf1c83f2011-02-16 01:52:01 +00002918 NonVirtualSize,
John McCall0153cd32011-11-08 04:01:03 +00002919 Builder.NonVirtualAlignment,
Anders Carlssonc121b4e2010-05-27 00:07:01 +00002920 EmptySubobjects.SizeOfLargestEmptySubobject,
John McCall0153cd32011-11-08 04:01:03 +00002921 Builder.PrimaryBase,
2922 Builder.PrimaryBaseIsVirtual,
Craig Topper36250ad2014-05-12 05:36:57 +00002923 nullptr, false, false,
John McCall0153cd32011-11-08 04:01:03 +00002924 Builder.Bases, Builder.VBases);
Anders Carlssond2954862010-05-26 05:10:47 +00002925 } else {
Craig Topper36250ad2014-05-12 05:36:57 +00002926 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/nullptr);
Anders Carlssond2954862010-05-26 05:10:47 +00002927 Builder.Layout(D);
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002928
Anders Carlssond2954862010-05-26 05:10:47 +00002929 NewEntry =
Ken Dyck1b4420e2011-02-28 02:01:38 +00002930 new (*this) ASTRecordLayout(*this, Builder.getSize(),
Ken Dyck4731d5b2011-02-16 02:05:21 +00002931 Builder.Alignment,
Warren Hunt7b252d22013-12-06 00:01:17 +00002932 /*RequiredAlignment : used by MS-ABI)*/
2933 Builder.Alignment,
Ken Dyck1b4420e2011-02-28 02:01:38 +00002934 Builder.getSize(),
Anders Carlssond2954862010-05-26 05:10:47 +00002935 Builder.FieldOffsets.data(),
2936 Builder.FieldOffsets.size());
2937 }
2938
Anders Carlssondf291d82010-05-26 04:56:53 +00002939 ASTRecordLayouts[D] = NewEntry;
2940
David Blaikiebbafb8a2012-03-11 07:00:24 +00002941 if (getLangOpts().DumpRecordLayouts) {
Argyrios Kyrtzidis8ade08e2013-07-12 22:30:03 +00002942 llvm::outs() << "\n*** Dumping AST Record Layout\n";
2943 DumpRecordLayout(D, llvm::outs(), getLangOpts().DumpRecordLayoutsSimple);
Anders Carlssondf291d82010-05-26 04:56:53 +00002944 }
2945
2946 return *NewEntry;
2947}
2948
John McCall6bd2a892013-01-25 22:31:03 +00002949const CXXMethodDecl *ASTContext::getCurrentKeyFunction(const CXXRecordDecl *RD) {
Reid Kleckner5d7f2982013-05-29 16:18:30 +00002950 if (!getTargetInfo().getCXXABI().hasKeyFunctions())
Craig Topper36250ad2014-05-12 05:36:57 +00002951 return nullptr;
Reid Kleckner5d7f2982013-05-29 16:18:30 +00002952
John McCall6bd2a892013-01-25 22:31:03 +00002953 assert(RD->getDefinition() && "Cannot get key function for forward decl!");
Anders Carlssondf291d82010-05-26 04:56:53 +00002954 RD = cast<CXXRecordDecl>(RD->getDefinition());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002955
Richard Smitha9a1c682014-07-07 06:38:20 +00002956 // Beware:
2957 // 1) computing the key function might trigger deserialization, which might
2958 // invalidate iterators into KeyFunctions
2959 // 2) 'get' on the LazyDeclPtr might also trigger deserialization and
2960 // invalidate the LazyDeclPtr within the map itself
2961 LazyDeclPtr Entry = KeyFunctions[RD];
2962 const Decl *Result =
2963 Entry ? Entry.get(getExternalSource()) : computeKeyFunction(*this, RD);
Daniel Dunbar592a85c2010-05-27 02:25:46 +00002964
Richard Smitha9a1c682014-07-07 06:38:20 +00002965 // Store it back if it changed.
2966 if (Entry.isOffset() || Entry.isValid() != bool(Result))
2967 KeyFunctions[RD] = const_cast<Decl*>(Result);
2968
2969 return cast_or_null<CXXMethodDecl>(Result);
John McCall6bd2a892013-01-25 22:31:03 +00002970}
2971
Richard Smith676c4042013-08-29 23:59:27 +00002972void ASTContext::setNonKeyFunction(const CXXMethodDecl *Method) {
Rafael Espindola8db352d2013-10-17 15:37:26 +00002973 assert(Method == Method->getFirstDecl() &&
John McCall6bd2a892013-01-25 22:31:03 +00002974 "not working with method declaration from class definition");
2975
2976 // Look up the cache entry. Since we're working with the first
2977 // declaration, its parent must be the class definition, which is
2978 // the correct key for the KeyFunctions hash.
Reid Klecknerb4a26ed2015-05-21 00:12:53 +00002979 const auto &Map = KeyFunctions;
2980 auto I = Map.find(Method->getParent());
John McCall6bd2a892013-01-25 22:31:03 +00002981
2982 // If it's not cached, there's nothing to do.
Reid Klecknerb4a26ed2015-05-21 00:12:53 +00002983 if (I == Map.end()) return;
John McCall6bd2a892013-01-25 22:31:03 +00002984
2985 // If it is cached, check whether it's the target method, and if so,
Richard Smitha9a1c682014-07-07 06:38:20 +00002986 // remove it from the cache. Note, the call to 'get' might invalidate
2987 // the iterator and the LazyDeclPtr object within the map.
2988 LazyDeclPtr Ptr = I->second;
2989 if (Ptr.get(getExternalSource()) == Method) {
John McCall6bd2a892013-01-25 22:31:03 +00002990 // FIXME: remember that we did this for module / chained PCH state?
Richard Smitha9a1c682014-07-07 06:38:20 +00002991 KeyFunctions.erase(Method->getParent());
John McCall6bd2a892013-01-25 22:31:03 +00002992 }
Anders Carlssondf291d82010-05-26 04:56:53 +00002993}
2994
Richard Smithdafff942012-01-14 04:30:29 +00002995static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) {
2996 const ASTRecordLayout &Layout = C.getASTRecordLayout(FD->getParent());
2997 return Layout.getFieldOffset(FD->getFieldIndex());
2998}
2999
3000uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const {
3001 uint64_t OffsetInBits;
3002 if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
3003 OffsetInBits = ::getFieldOffset(*this, FD);
3004 } else {
3005 const IndirectFieldDecl *IFD = cast<IndirectFieldDecl>(VD);
3006
3007 OffsetInBits = 0;
David Majnemerc964b4b2014-07-16 06:04:00 +00003008 for (const NamedDecl *ND : IFD->chain())
3009 OffsetInBits += ::getFieldOffset(*this, cast<FieldDecl>(ND));
Richard Smithdafff942012-01-14 04:30:29 +00003010 }
3011
3012 return OffsetInBits;
3013}
3014
Eric Christopher8a39a012011-10-05 06:00:51 +00003015/// getObjCLayout - Get or compute information about the layout of the
3016/// given interface.
Anders Carlssondf291d82010-05-26 04:56:53 +00003017///
3018/// \param Impl - If given, also include the layout of the interface's
3019/// implementation. This may differ by including synthesized ivars.
3020const ASTRecordLayout &
3021ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
Jay Foad39c79802011-01-12 09:06:06 +00003022 const ObjCImplementationDecl *Impl) const {
Douglas Gregor64d92572011-12-20 15:50:13 +00003023 // Retrieve the definition
Sean Callanand9a909c2012-03-15 16:33:08 +00003024 if (D->hasExternalLexicalStorage() && !D->getDefinition())
3025 getExternalSource()->CompleteType(const_cast<ObjCInterfaceDecl*>(D));
Douglas Gregor64d92572011-12-20 15:50:13 +00003026 D = D->getDefinition();
3027 assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!");
Anders Carlssondf291d82010-05-26 04:56:53 +00003028
3029 // Look up this layout, if already laid out, return what we have.
Roman Divackye6377112012-09-06 15:59:27 +00003030 const ObjCContainerDecl *Key =
3031 Impl ? (const ObjCContainerDecl*) Impl : (const ObjCContainerDecl*) D;
Anders Carlssondf291d82010-05-26 04:56:53 +00003032 if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
3033 return *Entry;
3034
3035 // Add in synthesized ivar count if laying out an implementation.
3036 if (Impl) {
3037 unsigned SynthCount = CountNonClassIvars(D);
3038 // If there aren't any sythesized ivars then reuse the interface
3039 // entry. Note we can't cache this because we simply free all
3040 // entries later; however we shouldn't look up implementations
3041 // frequently.
3042 if (SynthCount == 0)
Craig Topper36250ad2014-05-12 05:36:57 +00003043 return getObjCLayout(D, nullptr);
Anders Carlssondf291d82010-05-26 04:56:53 +00003044 }
3045
Craig Topper36250ad2014-05-12 05:36:57 +00003046 RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/nullptr);
Anders Carlsson6ed3a9a2010-05-26 05:04:25 +00003047 Builder.Layout(D);
3048
Anders Carlssondf291d82010-05-26 04:56:53 +00003049 const ASTRecordLayout *NewEntry =
Ken Dyck1b4420e2011-02-28 02:01:38 +00003050 new (*this) ASTRecordLayout(*this, Builder.getSize(),
Ken Dyck4731d5b2011-02-16 02:05:21 +00003051 Builder.Alignment,
Warren Hunt7b252d22013-12-06 00:01:17 +00003052 /*RequiredAlignment : used by MS-ABI)*/
3053 Builder.Alignment,
Ken Dyck1b4420e2011-02-28 02:01:38 +00003054 Builder.getDataSize(),
Anders Carlsson6ed3a9a2010-05-26 05:04:25 +00003055 Builder.FieldOffsets.data(),
3056 Builder.FieldOffsets.size());
Daniel Dunbar592a85c2010-05-27 02:25:46 +00003057
Anders Carlssondf291d82010-05-26 04:56:53 +00003058 ObjCLayouts[Key] = NewEntry;
3059
3060 return *NewEntry;
3061}
3062
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003063static void PrintOffset(raw_ostream &OS,
Anders Carlsson3f018712010-10-31 23:45:59 +00003064 CharUnits Offset, unsigned IndentLevel) {
Benjamin Kramer96ad7172011-11-05 09:02:52 +00003065 OS << llvm::format("%4" PRId64 " | ", (int64_t)Offset.getQuantity());
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003066 OS.indent(IndentLevel * 2);
3067}
3068
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00003069static void PrintIndentNoOffset(raw_ostream &OS, unsigned IndentLevel) {
3070 OS << " | ";
3071 OS.indent(IndentLevel * 2);
3072}
3073
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003074static void DumpCXXRecordLayout(raw_ostream &OS,
Jay Foad39c79802011-01-12 09:06:06 +00003075 const CXXRecordDecl *RD, const ASTContext &C,
Anders Carlsson3f018712010-10-31 23:45:59 +00003076 CharUnits Offset,
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003077 unsigned IndentLevel,
3078 const char* Description,
3079 bool IncludeVirtualBases) {
Anders Carlsson3f018712010-10-31 23:45:59 +00003080 const ASTRecordLayout &Layout = C.getASTRecordLayout(RD);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003081
3082 PrintOffset(OS, Offset, IndentLevel);
Dan Gohman145f3f12010-04-19 16:39:44 +00003083 OS << C.getTypeDeclType(const_cast<CXXRecordDecl *>(RD)).getAsString();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003084 if (Description)
3085 OS << ' ' << Description;
3086 if (RD->isEmpty())
3087 OS << " (empty)";
3088 OS << '\n';
3089
3090 IndentLevel++;
3091
Anders Carlsson3f018712010-10-31 23:45:59 +00003092 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
Warren Hunt8f8bad72013-10-11 20:19:00 +00003093 bool HasOwnVFPtr = Layout.hasOwnVFPtr();
3094 bool HasOwnVBPtr = Layout.hasOwnVBPtr();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003095
3096 // Vtable pointer.
Warren Hunt8f8bad72013-10-11 20:19:00 +00003097 if (RD->isDynamicClass() && !PrimaryBase && !isMsLayout(RD)) {
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003098 PrintOffset(OS, Offset, IndentLevel);
Benjamin Kramerb89514a2011-10-14 18:45:37 +00003099 OS << '(' << *RD << " vtable pointer)\n";
Warren Hunt8f8bad72013-10-11 20:19:00 +00003100 } else if (HasOwnVFPtr) {
3101 PrintOffset(OS, Offset, IndentLevel);
3102 // vfptr (for Microsoft C++ ABI)
3103 OS << '(' << *RD << " vftable pointer)\n";
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003104 }
Warren Hunt8f8bad72013-10-11 20:19:00 +00003105
Reid Klecknerad59deb2014-02-28 01:03:09 +00003106 // Collect nvbases.
3107 SmallVector<const CXXRecordDecl *, 4> Bases;
David Majnemerc964b4b2014-07-16 06:04:00 +00003108 for (const CXXBaseSpecifier &Base : RD->bases()) {
3109 assert(!Base.getType()->isDependentType() &&
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003110 "Cannot layout class with dependent bases.");
David Majnemerc964b4b2014-07-16 06:04:00 +00003111 if (!Base.isVirtual())
3112 Bases.push_back(Base.getType()->getAsCXXRecordDecl());
Reid Klecknerad59deb2014-02-28 01:03:09 +00003113 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003114
Reid Klecknerad59deb2014-02-28 01:03:09 +00003115 // Sort nvbases by offset.
Benjamin Kramerbbdd7642014-03-01 14:48:57 +00003116 std::stable_sort(Bases.begin(), Bases.end(),
3117 [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
3118 return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
3119 });
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003120
Reid Klecknerad59deb2014-02-28 01:03:09 +00003121 // Dump (non-virtual) bases
David Majnemerc964b4b2014-07-16 06:04:00 +00003122 for (const CXXRecordDecl *Base : Bases) {
Anders Carlsson3f018712010-10-31 23:45:59 +00003123 CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003124 DumpCXXRecordLayout(OS, Base, C, BaseOffset, IndentLevel,
3125 Base == PrimaryBase ? "(primary base)" : "(base)",
3126 /*IncludeVirtualBases=*/false);
3127 }
Eli Friedman43114f92011-10-21 22:49:56 +00003128
Warren Hunt8f8bad72013-10-11 20:19:00 +00003129 // vbptr (for Microsoft C++ ABI)
3130 if (HasOwnVBPtr) {
Eli Friedman84d2d3a2011-09-27 19:12:27 +00003131 PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel);
Benjamin Kramerb89514a2011-10-14 18:45:37 +00003132 OS << '(' << *RD << " vbtable pointer)\n";
Eli Friedman84d2d3a2011-09-27 19:12:27 +00003133 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003134
3135 // Dump fields.
3136 uint64_t FieldNo = 0;
3137 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
3138 E = RD->field_end(); I != E; ++I, ++FieldNo) {
David Blaikie40ed2972012-06-06 20:45:41 +00003139 const FieldDecl &Field = **I;
Anders Carlsson3f018712010-10-31 23:45:59 +00003140 CharUnits FieldOffset = Offset +
Ken Dyck86a7fcc2011-01-18 01:56:16 +00003141 C.toCharUnitsFromBits(Layout.getFieldOffset(FieldNo));
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003142
Reid Klecknercd612ab2014-04-11 16:57:42 +00003143 if (const CXXRecordDecl *D = Field.getType()->getAsCXXRecordDecl()) {
3144 DumpCXXRecordLayout(OS, D, C, FieldOffset, IndentLevel,
3145 Field.getName().data(),
3146 /*IncludeVirtualBases=*/true);
3147 continue;
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003148 }
3149
3150 PrintOffset(OS, FieldOffset, IndentLevel);
David Blaikie2d7c57e2012-04-30 02:36:29 +00003151 OS << Field.getType().getAsString() << ' ' << Field << '\n';
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003152 }
3153
3154 if (!IncludeVirtualBases)
3155 return;
3156
3157 // Dump virtual bases.
John McCalle42a3362012-05-01 08:55:32 +00003158 const ASTRecordLayout::VBaseOffsetsMapTy &vtordisps =
3159 Layout.getVBaseOffsetsMap();
David Majnemerc964b4b2014-07-16 06:04:00 +00003160 for (const CXXBaseSpecifier &Base : RD->vbases()) {
3161 assert(Base.isVirtual() && "Found non-virtual class!");
3162 const CXXRecordDecl *VBase = Base.getType()->getAsCXXRecordDecl();
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003163
Anders Carlsson3f018712010-10-31 23:45:59 +00003164 CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
John McCalle42a3362012-05-01 08:55:32 +00003165
3166 if (vtordisps.find(VBase)->second.hasVtorDisp()) {
3167 PrintOffset(OS, VBaseOffset - CharUnits::fromQuantity(4), IndentLevel);
3168 OS << "(vtordisp for vbase " << *VBase << ")\n";
3169 }
3170
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003171 DumpCXXRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel,
3172 VBase == PrimaryBase ?
3173 "(primary virtual base)" : "(virtual base)",
3174 /*IncludeVirtualBases=*/false);
3175 }
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003176
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00003177 PrintIndentNoOffset(OS, IndentLevel - 1);
3178 OS << "[sizeof=" << Layout.getSize().getQuantity();
Warren Hunt8f8bad72013-10-11 20:19:00 +00003179 if (!isMsLayout(RD))
3180 OS << ", dsize=" << Layout.getDataSize().getQuantity();
Ken Dyck7ad11e72011-02-15 02:32:40 +00003181 OS << ", align=" << Layout.getAlignment().getQuantity() << '\n';
Eli Benderskyf6f93ee2012-12-08 00:07:24 +00003182
3183 PrintIndentNoOffset(OS, IndentLevel - 1);
3184 OS << " nvsize=" << Layout.getNonVirtualSize().getQuantity();
Warren Huntd640d7d2014-01-09 00:30:56 +00003185 OS << ", nvalign=" << Layout.getNonVirtualAlignment().getQuantity() << "]\n";
Daniel Dunbaraa423af2010-04-08 02:59:49 +00003186}
Daniel Dunbarccabe482010-04-19 20:44:53 +00003187
3188void ASTContext::DumpRecordLayout(const RecordDecl *RD,
Douglas Gregore9fc3772012-01-26 07:55:45 +00003189 raw_ostream &OS,
3190 bool Simple) const {
Daniel Dunbarccabe482010-04-19 20:44:53 +00003191 const ASTRecordLayout &Info = getASTRecordLayout(RD);
3192
3193 if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
Douglas Gregore9fc3772012-01-26 07:55:45 +00003194 if (!Simple)
Craig Topper36250ad2014-05-12 05:36:57 +00003195 return DumpCXXRecordLayout(OS, CXXRD, *this, CharUnits(), 0, nullptr,
Douglas Gregore9fc3772012-01-26 07:55:45 +00003196 /*IncludeVirtualBases=*/true);
Daniel Dunbarccabe482010-04-19 20:44:53 +00003197
3198 OS << "Type: " << getTypeDeclType(RD).getAsString() << "\n";
Douglas Gregore9fc3772012-01-26 07:55:45 +00003199 if (!Simple) {
3200 OS << "Record: ";
3201 RD->dump();
3202 }
Daniel Dunbarccabe482010-04-19 20:44:53 +00003203 OS << "\nLayout: ";
3204 OS << "<ASTRecordLayout\n";
Ken Dyckb0fcc592011-02-11 01:54:29 +00003205 OS << " Size:" << toBits(Info.getSize()) << "\n";
Warren Hunt8f8bad72013-10-11 20:19:00 +00003206 if (!isMsLayout(RD))
3207 OS << " DataSize:" << toBits(Info.getDataSize()) << "\n";
Ken Dyck7ad11e72011-02-15 02:32:40 +00003208 OS << " Alignment:" << toBits(Info.getAlignment()) << "\n";
Daniel Dunbarccabe482010-04-19 20:44:53 +00003209 OS << " FieldOffsets: [";
3210 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) {
3211 if (i) OS << ", ";
3212 OS << Info.getFieldOffset(i);
3213 }
3214 OS << "]>\n";
3215}