blob: 10295f18835c37925c8f7a9153a18ede5852cfb8 [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 Stump3dc7eb92009-07-30 00:22:38 +000028void ASTRecordLayoutBuilder::LayoutVtable(const CXXRecordDecl *RD) {
Mike Stumpd8fe7b22009-08-05 22:37:18 +000029 // FIXME: audit indirect virtual bases
30 if (!RD->isPolymorphic() && !RD->getNumVBases())
31 return;
32
33 SelectPrimaryBase(RD);
34 if (PrimaryBase == 0) {
35 int AS = 0;
36 UpdateAlignment(Ctx.Target.getPointerAlign(AS));
37 Size += Ctx.Target.getPointerWidth(AS);
38 NextOffset = Size;
39 }
Mike Stump3dc7eb92009-07-30 00:22:38 +000040}
41
Anders Carlsson6d9f6f32009-07-19 00:18:47 +000042void
43ASTRecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl *RD) {
Anders Carlsson6d9f6f32009-07-19 00:18:47 +000044 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
45 e = RD->bases_end(); i != e; ++i) {
46 if (!i->isVirtual()) {
47 const CXXRecordDecl *Base =
Ted Kremenekc23c7e62009-07-29 21:53:49 +000048 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
Anders Carlsson6d9f6f32009-07-19 00:18:47 +000049 LayoutNonVirtualBase(Base);
50 }
51 }
52}
53
Mike Stumpd8fe7b22009-08-05 22:37:18 +000054// Helper routines related to the abi definition from:
55// http://www.codesourcery.com/public/cxx-abi/abi.html
56//
57/// IsNearlyEmpty - Indicates when a class has a vtable pointer, but
58/// no other data.
59bool ASTRecordLayoutBuilder::IsNearlyEmpty(const CXXRecordDecl *RD) {
60 // FIXME: Audit the corners
61 if (!RD->isDynamicClass())
62 return false;
63 const ASTRecordLayout &BaseInfo = Ctx.getASTRecordLayout(RD);
64 if (BaseInfo.getNonVirtualSize() == Ctx.Target.getPointerWidth(0))
65 return true;
66 return false;
67}
68
69void ASTRecordLayoutBuilder::SelectPrimaryForBase(const CXXRecordDecl *RD,
70 llvm::SmallSet<const CXXRecordDecl*, 32> &IndirectPrimary) {
71 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
72 e = RD->bases_end(); i != e; ++i) {
73 if (!i->isVirtual()) {
74 const CXXRecordDecl *Base =
75 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
76 // Only bases with virtual bases participate in computing the
77 // indirect primary base classes.
78 // FIXME: audit indirect virtual bases
79 if (Base->getNumVBases() == 0)
80 return;
81 // FIXME: This information is recomputed a whole lot, cache it instead.
82 SelectPrimaryBase(Base);
83 IndirectPrimary.insert(PrimaryBase);
84 SelectPrimaryForBase(Base, IndirectPrimary);
85 }
86 }
87}
88
89/// SelectPrimaryBase - Selects the primary base for the given class and
90/// records that with setPrimaryBase.
91void ASTRecordLayoutBuilder::SelectPrimaryBase(const CXXRecordDecl *RD) {
92 // The primary base is the first non-virtual indirect or direct base class,
93 // if one exists.
94 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
95 e = RD->bases_end(); i != e; ++i) {
96 if (!i->isVirtual()) {
97 const CXXRecordDecl *Base =
98 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
99 if (Base->isDynamicClass()) {
100 setPrimaryBase(Base);
101 return;
102 }
103 }
104 }
105
106 // Otherwise, it is the first nearly empty virtual base that is not an
107 // indirect primary base class, if one exists.
108
109 // If we have no virtual bases at this point, bail out as the searching below
110 // is expensive.
111 // FIXME: audit indirect virtual bases
112 if (RD->getNumVBases() == 0) {
113 setPrimaryBase(0);
114 return;
115 }
116
117 // First, we compute all the primary bases for all of out direct and indirect
118 // non-virtual bases, and record all their primary base classes.
119 const CXXRecordDecl *FirstPrimary = 0;
120 llvm::SmallSet<const CXXRecordDecl*, 32> IndirectPrimary;
121 for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
122 e = RD->bases_end(); i != e; ++i) {
123 if (!i->isVirtual()) {
124 const CXXRecordDecl *Base =
125 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
126 SelectPrimaryForBase(Base, IndirectPrimary);
127 }
128 }
129
130 // Then we can search for the first nearly empty virtual base itself.
131 // FIXME: audit indirect virtual bases
132 for (CXXRecordDecl::base_class_const_iterator i = RD->vbases_begin(),
133 e = RD->vbases_end(); i != e; ++i) {
134 const CXXRecordDecl *Base =
135 cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
136 if (IsNearlyEmpty(Base)) {
137 if (FirstPrimary==0)
138 FirstPrimary = Base;
139 if (!IndirectPrimary.count(Base)) {
140 setPrimaryBase(Base);
141 return;
142 }
143 }
144 }
145
146 // Otherwise if is the first nearly empty base, if one exists, otherwise
147 // there is no primary base class.
148 setPrimaryBase(FirstPrimary);
149 return;
150}
151
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000152void ASTRecordLayoutBuilder::LayoutNonVirtualBase(const CXXRecordDecl *RD) {
153 const ASTRecordLayout &BaseInfo = Ctx.getASTRecordLayout(RD);
154 assert(BaseInfo.getDataSize() > 0 &&
155 "FIXME: Handle empty classes.");
156
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000157 unsigned BaseAlign = BaseInfo.getNonVirtualAlign();
158 uint64_t BaseSize = BaseInfo.getNonVirtualSize();
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000159
160 // Round up the current record size to the base's alignment boundary.
161 Size = (Size + (BaseAlign-1)) & ~(BaseAlign-1);
162
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000163 // Add base class offsets.
164 Bases.push_back(RD);
165 BaseOffsets.push_back(Size);
166
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000167 // Reserve space for this base.
168 Size += BaseSize;
169
170 // Remember the next available offset.
171 NextOffset = Size;
172
173 // Remember max struct/class alignment.
174 UpdateAlignment(BaseAlign);
175}
176
Anders Carlsson79474332009-07-18 20:20:21 +0000177void ASTRecordLayoutBuilder::Layout(const RecordDecl *D) {
178 IsUnion = D->isUnion();
179
180 if (const PackedAttr* PA = D->getAttr<PackedAttr>())
181 StructPacking = PA->getAlignment();
182
183 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
184 UpdateAlignment(AA->getAlignment());
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000185
186 // If this is a C++ class, lay out the nonvirtual bases.
Mike Stump57724c22009-07-30 18:01:44 +0000187 if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
Mike Stump3dc7eb92009-07-30 00:22:38 +0000188 LayoutVtable(RD);
189 LayoutNonVirtualBases(RD);
190
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000191 // FIXME: audit indirect virtual bases
Mike Stump3dc7eb92009-07-30 00:22:38 +0000192 assert (RD->getNumVBases() == 0
193 && "FIXME: We don't support virtual bases yet!");
Mike Stump57724c22009-07-30 18:01:44 +0000194 // FIXME: We need to layout the virtual bases in the complete object layout.
Mike Stump3dc7eb92009-07-30 00:22:38 +0000195 }
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000196
Anders Carlsson118ce162009-07-18 21:48:39 +0000197 LayoutFields(D);
Anders Carlsson79474332009-07-18 20:20:21 +0000198
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000199 NonVirtualSize = Size;
200 NonVirtualAlignment = Alignment;
Mike Stump3dc7eb92009-07-30 00:22:38 +0000201
Anders Carlsson79474332009-07-18 20:20:21 +0000202 // Finally, round the size of the total struct up to the alignment of the
203 // struct itself.
204 FinishLayout();
205}
206
Anders Carlsson4f516282009-07-18 20:50:59 +0000207void ASTRecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D,
208 const ObjCImplementationDecl *Impl) {
209 if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
210 const ASTRecordLayout &SL = Ctx.getASTObjCInterfaceLayout(SD);
211
212 UpdateAlignment(SL.getAlignment());
213
214 // We start laying out ivars not at the end of the superclass
215 // structure, but at the next byte following the last field.
Anders Carlsson27b50132009-07-18 21:26:44 +0000216 Size = llvm::RoundUpToAlignment(SL.getDataSize(), 8);
Anders Carlsson4f516282009-07-18 20:50:59 +0000217 NextOffset = Size;
218 }
219
220 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
221 StructPacking = PA->getAlignment();
222
223 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
224 UpdateAlignment(AA->getAlignment());
225
226 // Layout each ivar sequentially.
227 llvm::SmallVector<ObjCIvarDecl*, 16> Ivars;
228 Ctx.ShallowCollectObjCIvars(D, Ivars, Impl);
229 for (unsigned i = 0, e = Ivars.size(); i != e; ++i)
230 LayoutField(Ivars[i]);
231
232 // Finally, round the size of the total struct up to the alignment of the
233 // struct itself.
234 FinishLayout();
235}
236
Anders Carlsson118ce162009-07-18 21:48:39 +0000237void ASTRecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
238 // Layout each field, for now, just sequentially, respecting alignment. In
239 // the future, this will need to be tweakable by targets.
240 for (RecordDecl::field_iterator Field = D->field_begin(),
241 FieldEnd = D->field_end(); Field != FieldEnd; ++Field)
242 LayoutField(*Field);
243}
244
Anders Carlsson79474332009-07-18 20:20:21 +0000245void ASTRecordLayoutBuilder::LayoutField(const FieldDecl *D) {
246 unsigned FieldPacking = StructPacking;
247 uint64_t FieldOffset = IsUnion ? 0 : Size;
248 uint64_t FieldSize;
249 unsigned FieldAlign;
250
251 // FIXME: Should this override struct packing? Probably we want to
252 // take the minimum?
253 if (const PackedAttr *PA = D->getAttr<PackedAttr>())
254 FieldPacking = PA->getAlignment();
255
256 if (const Expr *BitWidthExpr = D->getBitWidth()) {
257 // TODO: Need to check this algorithm on other targets!
258 // (tested on Linux-X86)
259 FieldSize = BitWidthExpr->EvaluateAsInt(Ctx).getZExtValue();
260
261 std::pair<uint64_t, unsigned> FieldInfo = Ctx.getTypeInfo(D->getType());
262 uint64_t TypeSize = FieldInfo.first;
263
264 // Determine the alignment of this bitfield. The packing
265 // attributes define a maximum and the alignment attribute defines
266 // a minimum.
267 // FIXME: What is the right behavior when the specified alignment
268 // is smaller than the specified packing?
269 FieldAlign = FieldInfo.second;
270 if (FieldPacking)
271 FieldAlign = std::min(FieldAlign, FieldPacking);
272 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
273 FieldAlign = std::max(FieldAlign, AA->getAlignment());
274
275 // Check if we need to add padding to give the field the correct
276 // alignment.
277 if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)
278 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
279
280 // Padding members don't affect overall alignment
281 if (!D->getIdentifier())
282 FieldAlign = 1;
283 } else {
284 if (D->getType()->isIncompleteArrayType()) {
285 // This is a flexible array member; we can't directly
286 // query getTypeInfo about these, so we figure it out here.
287 // Flexible array members don't have any size, but they
288 // have to be aligned appropriately for their element type.
289 FieldSize = 0;
290 const ArrayType* ATy = Ctx.getAsArrayType(D->getType());
291 FieldAlign = Ctx.getTypeAlign(ATy->getElementType());
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000292 } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) {
Anders Carlsson79474332009-07-18 20:20:21 +0000293 unsigned AS = RT->getPointeeType().getAddressSpace();
294 FieldSize = Ctx.Target.getPointerWidth(AS);
295 FieldAlign = Ctx.Target.getPointerAlign(AS);
296 } else {
297 std::pair<uint64_t, unsigned> FieldInfo = Ctx.getTypeInfo(D->getType());
298 FieldSize = FieldInfo.first;
299 FieldAlign = FieldInfo.second;
300 }
301
302 // Determine the alignment of this bitfield. The packing
303 // attributes define a maximum and the alignment attribute defines
304 // a minimum. Additionally, the packing alignment must be at least
305 // a byte for non-bitfields.
306 //
307 // FIXME: What is the right behavior when the specified alignment
308 // is smaller than the specified packing?
309 if (FieldPacking)
310 FieldAlign = std::min(FieldAlign, std::max(8U, FieldPacking));
311 if (const AlignedAttr *AA = D->getAttr<AlignedAttr>())
312 FieldAlign = std::max(FieldAlign, AA->getAlignment());
313
314 // Round up the current record size to the field's alignment boundary.
315 FieldOffset = (FieldOffset + (FieldAlign-1)) & ~(FieldAlign-1);
316 }
317
318 // Place this field at the current location.
319 FieldOffsets.push_back(FieldOffset);
320
321 // Reserve space for this field.
322 if (IsUnion)
323 Size = std::max(Size, FieldSize);
324 else
325 Size = FieldOffset + FieldSize;
326
327 // Remember the next available offset.
328 NextOffset = Size;
329
330 // Remember max struct/class alignment.
331 UpdateAlignment(FieldAlign);
332}
333
334void ASTRecordLayoutBuilder::FinishLayout() {
335 // In C++, records cannot be of size 0.
336 if (Ctx.getLangOptions().CPlusPlus && Size == 0)
337 Size = 8;
338 // Finally, round the size of the record up to the alignment of the
339 // record itself.
340 Size = (Size + (Alignment-1)) & ~(Alignment-1);
341}
342
343void ASTRecordLayoutBuilder::UpdateAlignment(unsigned NewAlignment) {
344 if (NewAlignment <= Alignment)
345 return;
346
347 assert(llvm::isPowerOf2_32(NewAlignment && "Alignment not a power of 2"));
348
349 Alignment = NewAlignment;
350}
351
352const ASTRecordLayout *
353ASTRecordLayoutBuilder::ComputeLayout(ASTContext &Ctx,
354 const RecordDecl *D) {
355 ASTRecordLayoutBuilder Builder(Ctx);
356
357 Builder.Layout(D);
358
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000359 if (!isa<CXXRecordDecl>(D))
360 return new ASTRecordLayout(Builder.Size, Builder.Alignment, Builder.Size,
361 Builder.FieldOffsets.data(),
362 Builder.FieldOffsets.size());
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000363
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000364 // FIXME: This is not always correct. See the part about bitfields at
365 // http://www.codesourcery.com/public/cxx-abi/abi.html#POD for more info.
366 // FIXME: IsPODForThePurposeOfLayout should be stored in the record layout.
367 bool IsPODForThePurposeOfLayout = cast<CXXRecordDecl>(D)->isPOD();
368
369 assert(Builder.Bases.size() == Builder.BaseOffsets.size() &&
370 "Base offsets vector must be same size as bases vector!");
371
372 // FIXME: This should be done in FinalizeLayout.
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000373 uint64_t DataSize =
374 IsPODForThePurposeOfLayout ? Builder.Size : Builder.NextOffset;
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000375 uint64_t NonVirtualSize =
376 IsPODForThePurposeOfLayout ? DataSize : Builder.NonVirtualSize;
Anders Carlsson6d9f6f32009-07-19 00:18:47 +0000377
378 return new ASTRecordLayout(Builder.Size, Builder.Alignment, DataSize,
Anders Carlsson4f516282009-07-18 20:50:59 +0000379 Builder.FieldOffsets.data(),
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000380 Builder.FieldOffsets.size(),
381 NonVirtualSize,
382 Builder.NonVirtualAlignment,
Mike Stumpd8fe7b22009-08-05 22:37:18 +0000383 Builder.PrimaryBase,
Anders Carlssonfc8cfa82009-07-28 19:24:15 +0000384 Builder.Bases.data(),
385 Builder.BaseOffsets.data(),
386 Builder.Bases.size());
Anders Carlsson4f516282009-07-18 20:50:59 +0000387}
388
389const ASTRecordLayout *
390ASTRecordLayoutBuilder::ComputeLayout(ASTContext &Ctx,
391 const ObjCInterfaceDecl *D,
392 const ObjCImplementationDecl *Impl) {
393 ASTRecordLayoutBuilder Builder(Ctx);
394
395 Builder.Layout(D, Impl);
396
397 return new ASTRecordLayout(Builder.Size, Builder.Alignment,
398 Builder.NextOffset,
Anders Carlsson79474332009-07-18 20:20:21 +0000399 Builder.FieldOffsets.data(),
400 Builder.FieldOffsets.size());
401}