blob: 5f23a8ca46c05a74a53f386f44102794998e2312 [file] [log] [blame]
Anders Carlsson79474332009-07-18 20:20:21 +00001//=== ASTRecordLayoutBuilder.cpp - Helper class for building record layouts ==//
2//
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
10#include "RecordLayoutBuilder.h"
11
12#include "clang/AST/Attr.h"
13#include "clang/AST/Decl.h"
Anders Carlsson6d9f6f32009-07-19 00:18:47 +000014#include "clang/AST/DeclCXX.h"
Anders Carlsson4f516282009-07-18 20:50:59 +000015#include "clang/AST/DeclObjC.h"
Anders Carlsson79474332009-07-18 20:20:21 +000016#include "clang/AST/Expr.h"
17#include "clang/AST/RecordLayout.h"
18#include "clang/Basic/TargetInfo.h"
Mike Stumpd8fe7b22009-08-05 22:37:18 +000019#include <llvm/ADT/SmallSet.h>
Anders Carlsson79474332009-07-18 20:20:21 +000020#include <llvm/Support/MathExtras.h>
21
22using namespace clang;
23
24ASTRecordLayoutBuilder::ASTRecordLayoutBuilder(ASTContext &Ctx)
Anders Carlsson6d9f6f32009-07-19 00:18:47 +000025 : Ctx(Ctx), Size(0), Alignment(8), StructPacking(0), NextOffset(0),
Anders Carlssonfc8cfa82009-07-28 19:24:15 +000026 IsUnion(false), NonVirtualSize(0), NonVirtualAlignment(8) {}
Anders Carlsson79474332009-07-18 20:20:21 +000027
Mike Stump25094802009-08-06 00:38:46 +000028/// LayoutVtable - Lay out the vtable and set PrimaryBase.
Mike Stump3dc7eb92009-07-30 00:22:38 +000029void ASTRecordLayoutBuilder::LayoutVtable(const CXXRecordDecl *RD) {
Mike Stumpd8fe7b22009-08-05 22:37:18 +000030 // FIXME: audit indirect virtual bases
Mike Stump25094802009-08-06 00:38:46 +000031 if (!RD->isPolymorphic() && !RD->getNumVBases()) {
32 // There is no primary base in this case.
33 setPrimaryBase(0);
Mike Stumpd8fe7b22009-08-05 22:37:18 +000034 return;
Mike Stump25094802009-08-06 00:38:46 +000035 }
Mike Stumpd8fe7b22009-08-05 22:37:18 +000036
37 SelectPrimaryBase(RD);
38 if (PrimaryBase == 0) {
39 int AS = 0;
40 UpdateAlignment(Ctx.Target.getPointerAlign(AS));
41 Size += Ctx.Target.getPointerWidth(AS);
42 NextOffset = Size;
43 }
Mike Stump3dc7eb92009-07-30 00:22:38 +000044}
45
Anders Carlsson6d9f6f32009-07-19 00:18:47 +000046void
47ASTRecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl *RD) {
Anders Carlsson6d9f6f32009-07-19 00:18:47 +000048 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
49 e = RD->bases_end(); i != e; ++i) {
50 if (!i->isVirtual()) {
51 const CXXRecordDecl *Base =
Ted Kremenekc23c7e62009-07-29 21:53:49 +000052 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Mike Stump25094802009-08-06 00:38:46 +000053 // Skip the PrimaryBase here, as it is laid down first.
54 if (Base != PrimaryBase)
Mike Stump6b2556f2009-08-06 13:41:24 +000055 LayoutBaseNonVirtually(Base);
Anders Carlsson6d9f6f32009-07-19 00:18:47 +000056 }
57 }
58}
59
Mike Stumpd8fe7b22009-08-05 22:37:18 +000060// Helper routines related to the abi definition from:
61// http://www.codesourcery.com/public/cxx-abi/abi.html
62//
63/// IsNearlyEmpty - Indicates when a class has a vtable pointer, but
64/// no other data.
65bool ASTRecordLayoutBuilder::IsNearlyEmpty(const CXXRecordDecl *RD) {
66 // FIXME: Audit the corners
67 if (!RD->isDynamicClass())
68 return false;
69 const ASTRecordLayout &BaseInfo = Ctx.getASTRecordLayout(RD);
70 if (BaseInfo.getNonVirtualSize() == Ctx.Target.getPointerWidth(0))
71 return true;
72 return false;
73}
74
75void ASTRecordLayoutBuilder::SelectPrimaryForBase(const CXXRecordDecl *RD,
76 llvm::SmallSet<const CXXRecordDecl*, 32> &IndirectPrimary) {
77 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
78 e = RD->bases_end(); i != e; ++i) {
79 if (!i->isVirtual()) {
80 const CXXRecordDecl *Base =
81 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
82 // Only bases with virtual bases participate in computing the
83 // indirect primary base classes.
84 // FIXME: audit indirect virtual bases
85 if (Base->getNumVBases() == 0)
86 return;
87 // FIXME: This information is recomputed a whole lot, cache it instead.
88 SelectPrimaryBase(Base);
89 IndirectPrimary.insert(PrimaryBase);
90 SelectPrimaryForBase(Base, IndirectPrimary);
91 }
92 }
93}
94
95/// SelectPrimaryBase - Selects the primary base for the given class and
96/// records that with setPrimaryBase.
97void ASTRecordLayoutBuilder::SelectPrimaryBase(const CXXRecordDecl *RD) {
98 // The primary base is the first non-virtual indirect or direct base class,
99 // if one exists.
100 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
101 e = RD->bases_end(); i != e; ++i) {
102 if (!i->isVirtual()) {
103 const CXXRecordDecl *Base =
104 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
105 if (Base->isDynamicClass()) {
106 setPrimaryBase(Base);
107 return;
108 }
109 }
110 }
111
112 // Otherwise, it is the first nearly empty virtual base that is not an
113 // indirect primary base class, if one exists.
114
115 // If we have no virtual bases at this point, bail out as the searching below
116 // is expensive.
117 // FIXME: audit indirect virtual bases
118 if (RD->getNumVBases() == 0) {
119 setPrimaryBase(0);
120 return;
121 }
122
Mike Stumpe9c85a72009-08-06 12:52:13 +0000123 // First, we compute all the primary bases for all of our direct and indirect
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000124 // non-virtual bases, and record all their primary base classes.
125 const CXXRecordDecl *FirstPrimary = 0;
126 llvm::SmallSet<const CXXRecordDecl*, 32> IndirectPrimary;
127 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
128 e = RD->bases_end(); i != e; ++i) {
129 if (!i->isVirtual()) {
130 const CXXRecordDecl *Base =
131 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
132 SelectPrimaryForBase(Base, IndirectPrimary);
133 }
134 }
135
136 // Then we can search for the first nearly empty virtual base itself.
137 // FIXME: audit indirect virtual bases
138 for (CXXRecordDecl::base_class_const_iterator i = RD->vbases_begin(),
139 e = RD->vbases_end(); i != e; ++i) {
140 const CXXRecordDecl *Base =
141 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
142 if (IsNearlyEmpty(Base)) {
143 if (FirstPrimary==0)
144 FirstPrimary = Base;
145 if (!IndirectPrimary.count(Base)) {
146 setPrimaryBase(Base);
147 return;
148 }
149 }
150 }
151
152 // Otherwise if is the first nearly empty base, if one exists, otherwise
153 // there is no primary base class.
154 setPrimaryBase(FirstPrimary);
155 return;
156}
157
Mike Stump6b2556f2009-08-06 13:41:24 +0000158void ASTRecordLayoutBuilder::LayoutVirtualBase(const CXXRecordDecl *RD) {
159 LayoutBaseNonVirtually(RD);
160}
161
162void ASTRecordLayoutBuilder::LayoutVirtualBases(const CXXRecordDecl *RD) {
163 // FIXME: audit indirect virtual bases
164 for (CXXRecordDecl::base_class_const_iterator i = RD->vbases_begin(),
165 e = RD->vbases_end(); i != e; ++i) {
166 const CXXRecordDecl *Base =
167 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
168 if (Base != PrimaryBase)
169 LayoutVirtualBase(Base);
170 }
171}
172
173void ASTRecordLayoutBuilder::LayoutBaseNonVirtually(const CXXRecordDecl *RD) {
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000174 const ASTRecordLayout &BaseInfo = Ctx.getASTRecordLayout(RD);
175 assert(BaseInfo.getDataSize() > 0 &&
176 "FIXME: Handle empty classes.");
177
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000178 unsigned BaseAlign = BaseInfo.getNonVirtualAlign();
179 uint64_t BaseSize = BaseInfo.getNonVirtualSize();
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000180
181 // Round up the current record size to the base's alignment boundary.
182 Size = (Size + (BaseAlign-1)) & ~(BaseAlign-1);
183
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000184 // Add base class offsets.
185 Bases.push_back(RD);
186 BaseOffsets.push_back(Size);
187
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000188 // Reserve space for this base.
189 Size += BaseSize;
190
191 // Remember the next available offset.
192 NextOffset = Size;
193
194 // Remember max struct/class alignment.
195 UpdateAlignment(BaseAlign);
196}
197
Anders Carlsson79474332009-07-18 20:20:21 +0000198void ASTRecordLayoutBuilder::Layout(const RecordDecl *D) {
199 IsUnion = D->isUnion();
200
201 if (const PackedAttr* PA = D->getAttr<PackedAttr>())
202 StructPacking = PA->getAlignment();
203
204 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
205 UpdateAlignment(AA->getAlignment());
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000206
207 // If this is a C++ class, lay out the nonvirtual bases.
Mike Stump6b2556f2009-08-06 13:41:24 +0000208 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D);
209 if (RD) {
Mike Stump3dc7eb92009-07-30 00:22:38 +0000210 LayoutVtable(RD);
Mike Stump25094802009-08-06 00:38:46 +0000211 // PrimaryBase goes first.
212 if (PrimaryBase)
Mike Stump6b2556f2009-08-06 13:41:24 +0000213 LayoutBaseNonVirtually(PrimaryBase);
Mike Stump3dc7eb92009-07-30 00:22:38 +0000214 LayoutNonVirtualBases(RD);
Mike Stump3dc7eb92009-07-30 00:22:38 +0000215 }
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000216
Anders Carlsson118ce162009-07-18 21:48:39 +0000217 LayoutFields(D);
Anders Carlsson79474332009-07-18 20:20:21 +0000218
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000219 NonVirtualSize = Size;
220 NonVirtualAlignment = Alignment;
Mike Stump3dc7eb92009-07-30 00:22:38 +0000221
Mike Stump6b2556f2009-08-06 13:41:24 +0000222 if (RD)
223 LayoutVirtualBases(RD);
224
Anders Carlsson79474332009-07-18 20:20:21 +0000225 // Finally, round the size of the total struct up to the alignment of the
226 // struct itself.
227 FinishLayout();
228}
229
Anders Carlsson4f516282009-07-18 20:50:59 +0000230void ASTRecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D,
231 const ObjCImplementationDecl *Impl) {
232 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
233 const ASTRecordLayout &SL = Ctx.getASTObjCInterfaceLayout(SD);
234
235 UpdateAlignment(SL.getAlignment());
236
237 // We start laying out ivars not at the end of the superclass
238 // structure, but at the next byte following the last field.
Anders Carlsson27b50132009-07-18 21:26:44 +0000239 Size = llvm::RoundUpToAlignment(SL.getDataSize(), 8);
Anders Carlsson4f516282009-07-18 20:50:59 +0000240 NextOffset = Size;
241 }
242
243 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
244 StructPacking = PA->getAlignment();
245
246 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
247 UpdateAlignment(AA->getAlignment());
248
249 // Layout each ivar sequentially.
250 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
251 Ctx.ShallowCollectObjCIvars(D, Ivars, Impl);
252 for (unsigned i = 0, e = Ivars.size(); i != e; ++i)
253 LayoutField(Ivars[i]);
254
255 // Finally, round the size of the total struct up to the alignment of the
256 // struct itself.
257 FinishLayout();
258}
259
Anders Carlsson118ce162009-07-18 21:48:39 +0000260void ASTRecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
261 // Layout each field, for now, just sequentially, respecting alignment. In
262 // the future, this will need to be tweakable by targets.
263 for (RecordDecl::field_iterator Field = D->field_begin(),
264 FieldEnd = D->field_end(); Field != FieldEnd; ++Field)
265 LayoutField(*Field);
266}
267
Anders Carlsson79474332009-07-18 20:20:21 +0000268void ASTRecordLayoutBuilder::LayoutField(const FieldDecl *D) {
269 unsigned FieldPacking = StructPacking;
270 uint64_t FieldOffset = IsUnion ? 0 : Size;
271 uint64_t FieldSize;
272 unsigned FieldAlign;
273
274 // FIXME: Should this override struct packing? Probably we want to
275 // take the minimum?
276 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
277 FieldPacking = PA->getAlignment();
278
279 if (const Expr *BitWidthExpr = D->getBitWidth()) {
280 // TODO: Need to check this algorithm on other targets!
281 // (tested on Linux-X86)
282 FieldSize = BitWidthExpr->EvaluateAsInt(Ctx).getZExtValue();
283
284 std::pair<uint64_t, unsigned> FieldInfo = Ctx.getTypeInfo(D->getType());
285 uint64_t TypeSize = FieldInfo.first;
286
287 // Determine the alignment of this bitfield. The packing
288 // attributes define a maximum and the alignment attribute defines
289 // a minimum.
290 // FIXME: What is the right behavior when the specified alignment
291 // is smaller than the specified packing?
292 FieldAlign = FieldInfo.second;
293 if (FieldPacking)
294 FieldAlign = std::min(FieldAlign, FieldPacking);
295 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
296 FieldAlign = std::max(FieldAlign, AA->getAlignment());
297
298 // Check if we need to add padding to give the field the correct
299 // alignment.
300 if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)
301 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
302
303 // Padding members don't affect overall alignment
304 if (!D->getIdentifier())
305 FieldAlign = 1;
306 } else {
307 if (D->getType()->isIncompleteArrayType()) {
308 // This is a flexible array member; we can't directly
309 // query getTypeInfo about these, so we figure it out here.
310 // Flexible array members don't have any size, but they
311 // have to be aligned appropriately for their element type.
312 FieldSize = 0;
313 const ArrayType* ATy = Ctx.getAsArrayType(D->getType());
314 FieldAlign = Ctx.getTypeAlign(ATy->getElementType());
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000315 } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) {
Anders Carlsson79474332009-07-18 20:20:21 +0000316 unsigned AS = RT->getPointeeType().getAddressSpace();
317 FieldSize = Ctx.Target.getPointerWidth(AS);
318 FieldAlign = Ctx.Target.getPointerAlign(AS);
319 } else {
320 std::pair<uint64_t, unsigned> FieldInfo = Ctx.getTypeInfo(D->getType());
321 FieldSize = FieldInfo.first;
322 FieldAlign = FieldInfo.second;
323 }
324
325 // Determine the alignment of this bitfield. The packing
326 // attributes define a maximum and the alignment attribute defines
327 // a minimum. Additionally, the packing alignment must be at least
328 // a byte for non-bitfields.
329 //
330 // FIXME: What is the right behavior when the specified alignment
331 // is smaller than the specified packing?
332 if (FieldPacking)
333 FieldAlign = std::min(FieldAlign, std::max(8U, FieldPacking));
334 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
335 FieldAlign = std::max(FieldAlign, AA->getAlignment());
336
337 // Round up the current record size to the field's alignment boundary.
338 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
339 }
340
341 // Place this field at the current location.
342 FieldOffsets.push_back(FieldOffset);
343
344 // Reserve space for this field.
345 if (IsUnion)
346 Size = std::max(Size, FieldSize);
347 else
348 Size = FieldOffset + FieldSize;
349
350 // Remember the next available offset.
351 NextOffset = Size;
352
353 // Remember max struct/class alignment.
354 UpdateAlignment(FieldAlign);
355}
356
357void ASTRecordLayoutBuilder::FinishLayout() {
358 // In C++, records cannot be of size 0.
359 if (Ctx.getLangOptions().CPlusPlus && Size == 0)
360 Size = 8;
361 // Finally, round the size of the record up to the alignment of the
362 // record itself.
363 Size = (Size + (Alignment-1)) & ~(Alignment-1);
364}
365
366void ASTRecordLayoutBuilder::UpdateAlignment(unsigned NewAlignment) {
367 if (NewAlignment <= Alignment)
368 return;
369
370 assert(llvm::isPowerOf2_32(NewAlignment && "Alignment not a power of 2"));
371
372 Alignment = NewAlignment;
373}
374
375const ASTRecordLayout *
376ASTRecordLayoutBuilder::ComputeLayout(ASTContext &Ctx,
377 const RecordDecl *D) {
378 ASTRecordLayoutBuilder Builder(Ctx);
379
380 Builder.Layout(D);
381
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000382 if (!isa<CXXRecordDecl>(D))
383 return new ASTRecordLayout(Builder.Size, Builder.Alignment, Builder.Size,
384 Builder.FieldOffsets.data(),
385 Builder.FieldOffsets.size());
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000386
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000387 // FIXME: This is not always correct. See the part about bitfields at
388 // http://www.codesourcery.com/public/cxx-abi/abi.html#POD for more info.
389 // FIXME: IsPODForThePurposeOfLayout should be stored in the record layout.
390 bool IsPODForThePurposeOfLayout = cast<CXXRecordDecl>(D)->isPOD();
391
392 assert(Builder.Bases.size() == Builder.BaseOffsets.size() &&
393 "Base offsets vector must be same size as bases vector!");
394
395 // FIXME: This should be done in FinalizeLayout.
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000396 uint64_t DataSize =
397 IsPODForThePurposeOfLayout ? Builder.Size : Builder.NextOffset;
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000398 uint64_t NonVirtualSize =
399 IsPODForThePurposeOfLayout ? DataSize : Builder.NonVirtualSize;
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000400
401 return new ASTRecordLayout(Builder.Size, Builder.Alignment, DataSize,
Anders Carlsson4f516282009-07-18 20:50:59 +0000402 Builder.FieldOffsets.data(),
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000403 Builder.FieldOffsets.size(),
404 NonVirtualSize,
405 Builder.NonVirtualAlignment,
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000406 Builder.PrimaryBase,
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000407 Builder.Bases.data(),
408 Builder.BaseOffsets.data(),
409 Builder.Bases.size());
Anders Carlsson4f516282009-07-18 20:50:59 +0000410}
411
412const ASTRecordLayout *
413ASTRecordLayoutBuilder::ComputeLayout(ASTContext &Ctx,
414 const ObjCInterfaceDecl *D,
415 const ObjCImplementationDecl *Impl) {
416 ASTRecordLayoutBuilder Builder(Ctx);
417
418 Builder.Layout(D, Impl);
419
420 return new ASTRecordLayout(Builder.Size, Builder.Alignment,
421 Builder.NextOffset,
Anders Carlsson79474332009-07-18 20:20:21 +0000422 Builder.FieldOffsets.data(),
423 Builder.FieldOffsets.size());
424}