blob: 7704091b5bb5f8c23c0e2658eb1f3a56d20dd03c [file] [log] [blame]
Daniel Dunbar23ee4b72010-03-31 00:11:27 +00001//===--- CGRecordLayoutBuilder.cpp - CGRecordLayout builder ----*- C++ -*-===//
Anders Carlsson307846f2009-07-23 03:17:50 +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//
Daniel Dunbar23ee4b72010-03-31 00:11:27 +000010// Builder implementation for CGRecordLayout objects.
Anders Carlsson307846f2009-07-23 03:17:50 +000011//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbar072d0bb2010-03-30 22:26:10 +000014#include "CGRecordLayout.h"
Anders Carlsson307846f2009-07-23 03:17:50 +000015#include "clang/AST/ASTContext.h"
16#include "clang/AST/Attr.h"
Anders Carlsson4131f002010-11-24 22:50:27 +000017#include "clang/AST/CXXInheritance.h"
Anders Carlsson307846f2009-07-23 03:17:50 +000018#include "clang/AST/DeclCXX.h"
19#include "clang/AST/Expr.h"
20#include "clang/AST/RecordLayout.h"
21#include "CodeGenTypes.h"
John McCall614dbdc2010-08-22 21:01:12 +000022#include "CGCXXABI.h"
Anders Carlsson307846f2009-07-23 03:17:50 +000023#include "llvm/DerivedTypes.h"
Daniel Dunbarb97bff92010-04-12 18:14:18 +000024#include "llvm/Type.h"
Daniel Dunbar2ba67442010-04-21 19:10:49 +000025#include "llvm/Support/Debug.h"
Daniel Dunbarb97bff92010-04-12 18:14:18 +000026#include "llvm/Support/raw_ostream.h"
Anders Carlsson307846f2009-07-23 03:17:50 +000027#include "llvm/Target/TargetData.h"
Anders Carlsson307846f2009-07-23 03:17:50 +000028using namespace clang;
29using namespace CodeGen;
30
John McCallbcd38212010-11-30 23:17:27 +000031namespace {
Daniel Dunbar23ee4b72010-03-31 00:11:27 +000032
33class CGRecordLayoutBuilder {
34public:
35 /// FieldTypes - Holds the LLVM types that the struct is created from.
John McCall0217dfc22011-02-15 06:40:56 +000036 ///
Daniel Dunbar23ee4b72010-03-31 00:11:27 +000037 std::vector<const llvm::Type *> FieldTypes;
38
John McCall0217dfc22011-02-15 06:40:56 +000039 /// BaseSubobjectType - Holds the LLVM type for the non-virtual part
Anders Carlssonc1351ca2010-11-09 05:25:47 +000040 /// of the struct. For example, consider:
41 ///
42 /// struct A { int i; };
43 /// struct B { void *v; };
44 /// struct C : virtual A, B { };
45 ///
46 /// The LLVM type of C will be
47 /// %struct.C = type { i32 (...)**, %struct.A, i32, %struct.B }
48 ///
49 /// And the LLVM type of the non-virtual base struct will be
50 /// %struct.C.base = type { i32 (...)**, %struct.A, i32 }
John McCall0217dfc22011-02-15 06:40:56 +000051 ///
52 /// This only gets initialized if the base subobject type is
53 /// different from the complete-object type.
54 const llvm::StructType *BaseSubobjectType;
Anders Carlssonc1351ca2010-11-09 05:25:47 +000055
John McCall0217dfc22011-02-15 06:40:56 +000056 /// FieldInfo - Holds a field and its corresponding LLVM field number.
57 llvm::DenseMap<const FieldDecl *, unsigned> Fields;
Daniel Dunbar23ee4b72010-03-31 00:11:27 +000058
John McCall0217dfc22011-02-15 06:40:56 +000059 /// BitFieldInfo - Holds location and size information about a bit field.
60 llvm::DenseMap<const FieldDecl *, CGBitFieldInfo> BitFields;
Daniel Dunbar23ee4b72010-03-31 00:11:27 +000061
John McCall0217dfc22011-02-15 06:40:56 +000062 llvm::DenseMap<const CXXRecordDecl *, unsigned> NonVirtualBases;
63 llvm::DenseMap<const CXXRecordDecl *, unsigned> VirtualBases;
Anders Carlsson4131f002010-11-24 22:50:27 +000064
65 /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are
66 /// primary base classes for some other direct or indirect base class.
67 CXXIndirectPrimaryBaseSet IndirectPrimaryBases;
68
Anders Carlssona459adb2010-11-28 19:18:44 +000069 /// LaidOutVirtualBases - A set of all laid out virtual bases, used to avoid
70 /// avoid laying out virtual bases more than once.
71 llvm::SmallPtrSet<const CXXRecordDecl *, 4> LaidOutVirtualBases;
72
John McCall614dbdc2010-08-22 21:01:12 +000073 /// IsZeroInitializable - Whether this struct can be C++
74 /// zero-initialized with an LLVM zeroinitializer.
75 bool IsZeroInitializable;
John McCall0217dfc22011-02-15 06:40:56 +000076 bool IsZeroInitializableAsBase;
Daniel Dunbar23ee4b72010-03-31 00:11:27 +000077
78 /// Packed - Whether the resulting LLVM struct will be packed or not.
79 bool Packed;
80
81private:
82 CodeGenTypes &Types;
83
84 /// Alignment - Contains the alignment of the RecordDecl.
85 //
86 // FIXME: This is not needed and should be removed.
John McCall4d9f1422011-02-15 22:21:29 +000087 CharUnits Alignment;
Daniel Dunbar23ee4b72010-03-31 00:11:27 +000088
Daniel Dunbar23ee4b72010-03-31 00:11:27 +000089 /// BitsAvailableInLastField - If a bit field spans only part of a LLVM field,
90 /// this will have the number of bits still available in the field.
91 char BitsAvailableInLastField;
92
John McCall4d9f1422011-02-15 22:21:29 +000093 /// NextFieldOffset - Holds the next field offset.
94 CharUnits NextFieldOffset;
Daniel Dunbar23ee4b72010-03-31 00:11:27 +000095
Anders Carlsson1de2f572010-04-17 20:49:27 +000096 /// LayoutUnionField - Will layout a field in an union and return the type
97 /// that the field will have.
98 const llvm::Type *LayoutUnionField(const FieldDecl *Field,
99 const ASTRecordLayout &Layout);
100
Daniel Dunbar23ee4b72010-03-31 00:11:27 +0000101 /// LayoutUnion - Will layout a union RecordDecl.
102 void LayoutUnion(const RecordDecl *D);
103
104 /// LayoutField - try to layout all fields in the record decl.
105 /// Returns false if the operation failed because the struct is not packed.
106 bool LayoutFields(const RecordDecl *D);
107
Anders Carlssona518b2a2010-12-04 23:59:48 +0000108 /// Layout a single base, virtual or non-virtual
John McCall4d9f1422011-02-15 22:21:29 +0000109 void LayoutBase(const CXXRecordDecl *base,
110 const CGRecordLayout &baseLayout,
111 CharUnits baseOffset);
Anders Carlssona518b2a2010-12-04 23:59:48 +0000112
Anders Carlsson1f95ee32010-11-25 01:59:35 +0000113 /// LayoutVirtualBase - layout a single virtual base.
John McCall4d9f1422011-02-15 22:21:29 +0000114 void LayoutVirtualBase(const CXXRecordDecl *base,
115 CharUnits baseOffset);
Anders Carlsson1f95ee32010-11-25 01:59:35 +0000116
Anders Carlssona459adb2010-11-28 19:18:44 +0000117 /// LayoutVirtualBases - layout the virtual bases of a record decl.
118 void LayoutVirtualBases(const CXXRecordDecl *RD,
119 const ASTRecordLayout &Layout);
120
Anders Carlssonaf9e5af2010-05-18 05:12:20 +0000121 /// LayoutNonVirtualBase - layout a single non-virtual base.
John McCall4d9f1422011-02-15 22:21:29 +0000122 void LayoutNonVirtualBase(const CXXRecordDecl *base,
123 CharUnits baseOffset);
Anders Carlssonaf9e5af2010-05-18 05:12:20 +0000124
Anders Carlssona459adb2010-11-28 19:18:44 +0000125 /// LayoutNonVirtualBases - layout the virtual bases of a record decl.
Anders Carlssonaf9e5af2010-05-18 05:12:20 +0000126 void LayoutNonVirtualBases(const CXXRecordDecl *RD,
127 const ASTRecordLayout &Layout);
Daniel Dunbar23ee4b72010-03-31 00:11:27 +0000128
Anders Carlssonc1351ca2010-11-09 05:25:47 +0000129 /// ComputeNonVirtualBaseType - Compute the non-virtual base field types.
Argyrios Kyrtzidis648fcbe2010-12-10 00:11:00 +0000130 bool ComputeNonVirtualBaseType(const CXXRecordDecl *RD);
Anders Carlssonc1351ca2010-11-09 05:25:47 +0000131
Daniel Dunbar23ee4b72010-03-31 00:11:27 +0000132 /// LayoutField - layout a single field. Returns false if the operation failed
133 /// because the current struct is not packed.
134 bool LayoutField(const FieldDecl *D, uint64_t FieldOffset);
135
136 /// LayoutBitField - layout a single bit field.
137 void LayoutBitField(const FieldDecl *D, uint64_t FieldOffset);
138
139 /// AppendField - Appends a field with the given offset and type.
John McCall4d9f1422011-02-15 22:21:29 +0000140 void AppendField(CharUnits fieldOffset, const llvm::Type *FieldTy);
Daniel Dunbar23ee4b72010-03-31 00:11:27 +0000141
Daniel Dunbar23ee4b72010-03-31 00:11:27 +0000142 /// AppendPadding - Appends enough padding bytes so that the total
143 /// struct size is a multiple of the field alignment.
John McCall4d9f1422011-02-15 22:21:29 +0000144 void AppendPadding(CharUnits fieldOffset, CharUnits fieldAlignment);
Daniel Dunbar23ee4b72010-03-31 00:11:27 +0000145
Anders Carlssonc1351ca2010-11-09 05:25:47 +0000146 /// getByteArrayType - Returns a byte array type with the given number of
147 /// elements.
John McCall4d9f1422011-02-15 22:21:29 +0000148 const llvm::Type *getByteArrayType(CharUnits NumBytes);
Anders Carlssonc1351ca2010-11-09 05:25:47 +0000149
Daniel Dunbar23ee4b72010-03-31 00:11:27 +0000150 /// AppendBytes - Append a given number of bytes to the record.
John McCall4d9f1422011-02-15 22:21:29 +0000151 void AppendBytes(CharUnits numBytes);
Daniel Dunbar23ee4b72010-03-31 00:11:27 +0000152
153 /// AppendTailPadding - Append enough tail padding so that the type will have
154 /// the passed size.
155 void AppendTailPadding(uint64_t RecordSize);
156
John McCall4d9f1422011-02-15 22:21:29 +0000157 CharUnits getTypeAlignment(const llvm::Type *Ty) const;
Daniel Dunbar23ee4b72010-03-31 00:11:27 +0000158
Anders Carlssonacf877b2010-11-28 23:06:23 +0000159 /// getAlignmentAsLLVMStruct - Returns the maximum alignment of all the
160 /// LLVM element types.
John McCall4d9f1422011-02-15 22:21:29 +0000161 CharUnits getAlignmentAsLLVMStruct() const;
Anders Carlssonacf877b2010-11-28 23:06:23 +0000162
John McCall614dbdc2010-08-22 21:01:12 +0000163 /// CheckZeroInitializable - Check if the given type contains a pointer
Daniel Dunbar23ee4b72010-03-31 00:11:27 +0000164 /// to data member.
John McCall614dbdc2010-08-22 21:01:12 +0000165 void CheckZeroInitializable(QualType T);
Daniel Dunbar23ee4b72010-03-31 00:11:27 +0000166
167public:
168 CGRecordLayoutBuilder(CodeGenTypes &Types)
John McCall0217dfc22011-02-15 06:40:56 +0000169 : BaseSubobjectType(0),
170 IsZeroInitializable(true), IsZeroInitializableAsBase(true),
John McCall4d9f1422011-02-15 22:21:29 +0000171 Packed(false), Types(Types), BitsAvailableInLastField(0) { }
Daniel Dunbar23ee4b72010-03-31 00:11:27 +0000172
173 /// Layout - Will layout a RecordDecl.
174 void Layout(const RecordDecl *D);
175};
176
177}
Daniel Dunbar23ee4b72010-03-31 00:11:27 +0000178
Anders Carlsson307846f2009-07-23 03:17:50 +0000179void CGRecordLayoutBuilder::Layout(const RecordDecl *D) {
John McCall4d9f1422011-02-15 22:21:29 +0000180 Alignment = Types.getContext().getASTRecordLayout(D).getAlignment();
Anders Carlsson09a37742009-09-02 17:51:33 +0000181 Packed = D->hasAttr<PackedAttr>();
Anders Carlsson28a5fa22009-08-08 19:38:24 +0000182
Anders Carlsson697f6592009-07-23 03:43:54 +0000183 if (D->isUnion()) {
184 LayoutUnion(D);
185 return;
186 }
Anders Carlsson68e0b682009-08-08 18:23:56 +0000187
Anders Carlsson307846f2009-07-23 03:17:50 +0000188 if (LayoutFields(D))
189 return;
Mike Stump11289f42009-09-09 15:08:12 +0000190
Anders Carlsson307846f2009-07-23 03:17:50 +0000191 // We weren't able to layout the struct. Try again with a packed struct
Anders Carlssond78fc892009-07-23 17:24:40 +0000192 Packed = true;
John McCall4d9f1422011-02-15 22:21:29 +0000193 NextFieldOffset = CharUnits::Zero();
Anders Carlsson307846f2009-07-23 03:17:50 +0000194 FieldTypes.clear();
John McCall0217dfc22011-02-15 06:40:56 +0000195 Fields.clear();
196 BitFields.clear();
197 NonVirtualBases.clear();
198 VirtualBases.clear();
Mike Stump11289f42009-09-09 15:08:12 +0000199
Anders Carlsson307846f2009-07-23 03:17:50 +0000200 LayoutFields(D);
201}
202
Daniel Dunbarc7f9bba2010-09-02 23:53:28 +0000203CGBitFieldInfo CGBitFieldInfo::MakeInfo(CodeGenTypes &Types,
204 const FieldDecl *FD,
205 uint64_t FieldOffset,
206 uint64_t FieldSize,
207 uint64_t ContainingTypeSizeInBits,
208 unsigned ContainingTypeAlign) {
Daniel Dunbarf9c24f82010-04-12 21:01:28 +0000209 const llvm::Type *Ty = Types.ConvertTypeForMemRecursive(FD->getType());
Daniel Dunbarb935b932010-04-13 20:58:55 +0000210 uint64_t TypeSizeInBytes = Types.getTargetData().getTypeAllocSize(Ty);
211 uint64_t TypeSizeInBits = TypeSizeInBytes * 8;
Daniel Dunbarf9c24f82010-04-12 21:01:28 +0000212
213 bool IsSigned = FD->getType()->isSignedIntegerType();
Daniel Dunbarf9c24f82010-04-12 21:01:28 +0000214
Anders Carlssonbe6f3182010-04-16 16:23:02 +0000215 if (FieldSize > TypeSizeInBits) {
Anders Carlssond5f27b02010-04-17 22:54:57 +0000216 // We have a wide bit-field. The extra bits are only used for padding, so
217 // if we have a bitfield of type T, with size N:
218 //
219 // T t : N;
220 //
221 // We can just assume that it's:
222 //
223 // T t : sizeof(T);
224 //
225 FieldSize = TypeSizeInBits;
Anders Carlssonbe6f3182010-04-16 16:23:02 +0000226 }
227
Daniel Dunbar488f55c2010-04-22 02:35:46 +0000228 // Compute the access components. The policy we use is to start by attempting
229 // to access using the width of the bit-field type itself and to always access
230 // at aligned indices of that type. If such an access would fail because it
231 // extends past the bound of the type, then we reduce size to the next smaller
232 // power of two and retry. The current algorithm assumes pow2 sized types,
233 // although this is easy to fix.
234 //
235 // FIXME: This algorithm is wrong on big-endian systems, I think.
236 assert(llvm::isPowerOf2_32(TypeSizeInBits) && "Unexpected type size!");
237 CGBitFieldInfo::AccessInfo Components[3];
238 unsigned NumComponents = 0;
239 unsigned AccessedTargetBits = 0; // The tumber of target bits accessed.
240 unsigned AccessWidth = TypeSizeInBits; // The current access width to attempt.
Anders Carlssonbe6f3182010-04-16 16:23:02 +0000241
Daniel Dunbar488f55c2010-04-22 02:35:46 +0000242 // Round down from the field offset to find the first access position that is
243 // at an aligned offset of the initial access type.
Daniel Dunbar59813772010-04-22 15:22:33 +0000244 uint64_t AccessStart = FieldOffset - (FieldOffset % AccessWidth);
245
246 // Adjust initial access size to fit within record.
247 while (AccessWidth > 8 &&
248 AccessStart + AccessWidth > ContainingTypeSizeInBits) {
249 AccessWidth >>= 1;
250 AccessStart = FieldOffset - (FieldOffset % AccessWidth);
251 }
Daniel Dunbar9c78d632010-04-15 05:09:32 +0000252
Daniel Dunbar488f55c2010-04-22 02:35:46 +0000253 while (AccessedTargetBits < FieldSize) {
254 // Check that we can access using a type of this size, without reading off
255 // the end of the structure. This can occur with packed structures and
256 // -fno-bitfield-type-align, for example.
257 if (AccessStart + AccessWidth > ContainingTypeSizeInBits) {
258 // If so, reduce access size to the next smaller power-of-two and retry.
259 AccessWidth >>= 1;
260 assert(AccessWidth >= 8 && "Cannot access under byte size!");
261 continue;
262 }
Daniel Dunbarb935b932010-04-13 20:58:55 +0000263
Daniel Dunbar488f55c2010-04-22 02:35:46 +0000264 // Otherwise, add an access component.
Daniel Dunbarb935b932010-04-13 20:58:55 +0000265
Daniel Dunbar488f55c2010-04-22 02:35:46 +0000266 // First, compute the bits inside this access which are part of the
267 // target. We are reading bits [AccessStart, AccessStart + AccessWidth); the
268 // intersection with [FieldOffset, FieldOffset + FieldSize) gives the bits
269 // in the target that we are reading.
Daniel Dunbar59813772010-04-22 15:22:33 +0000270 assert(FieldOffset < AccessStart + AccessWidth && "Invalid access start!");
271 assert(AccessStart < FieldOffset + FieldSize && "Invalid access start!");
Daniel Dunbar488f55c2010-04-22 02:35:46 +0000272 uint64_t AccessBitsInFieldStart = std::max(AccessStart, FieldOffset);
273 uint64_t AccessBitsInFieldSize =
Daniel Dunbar59813772010-04-22 15:22:33 +0000274 std::min(AccessWidth + AccessStart,
275 FieldOffset + FieldSize) - AccessBitsInFieldStart;
Daniel Dunbar5d6c07e2010-04-22 14:56:10 +0000276
Daniel Dunbar488f55c2010-04-22 02:35:46 +0000277 assert(NumComponents < 3 && "Unexpected number of components!");
278 CGBitFieldInfo::AccessInfo &AI = Components[NumComponents++];
279 AI.FieldIndex = 0;
280 // FIXME: We still follow the old access pattern of only using the field
281 // byte offset. We should switch this once we fix the struct layout to be
282 // pretty.
283 AI.FieldByteOffset = AccessStart / 8;
284 AI.FieldBitStart = AccessBitsInFieldStart - AccessStart;
285 AI.AccessWidth = AccessWidth;
Daniel Dunbarfc66e0e2010-04-22 03:17:04 +0000286 AI.AccessAlignment = llvm::MinAlign(ContainingTypeAlign, AccessStart) / 8;
Daniel Dunbar488f55c2010-04-22 02:35:46 +0000287 AI.TargetBitOffset = AccessedTargetBits;
288 AI.TargetBitWidth = AccessBitsInFieldSize;
289
290 AccessStart += AccessWidth;
291 AccessedTargetBits += AI.TargetBitWidth;
Daniel Dunbarb935b932010-04-13 20:58:55 +0000292 }
293
Daniel Dunbar488f55c2010-04-22 02:35:46 +0000294 assert(AccessedTargetBits == FieldSize && "Invalid bit-field access!");
Daniel Dunbar9c78d632010-04-15 05:09:32 +0000295 return CGBitFieldInfo(FieldSize, NumComponents, Components, IsSigned);
Daniel Dunbarf9c24f82010-04-12 21:01:28 +0000296}
297
Daniel Dunbarc7f9bba2010-09-02 23:53:28 +0000298CGBitFieldInfo CGBitFieldInfo::MakeInfo(CodeGenTypes &Types,
299 const FieldDecl *FD,
300 uint64_t FieldOffset,
301 uint64_t FieldSize) {
302 const RecordDecl *RD = FD->getParent();
303 const ASTRecordLayout &RL = Types.getContext().getASTRecordLayout(RD);
Ken Dyckb0fcc592011-02-11 01:54:29 +0000304 uint64_t ContainingTypeSizeInBits = Types.getContext().toBits(RL.getSize());
Ken Dyck7ad11e72011-02-15 02:32:40 +0000305 unsigned ContainingTypeAlign = Types.getContext().toBits(RL.getAlignment());
Daniel Dunbarc7f9bba2010-09-02 23:53:28 +0000306
307 return MakeInfo(Types, FD, FieldOffset, FieldSize, ContainingTypeSizeInBits,
308 ContainingTypeAlign);
309}
310
Anders Carlsson307846f2009-07-23 03:17:50 +0000311void CGRecordLayoutBuilder::LayoutBitField(const FieldDecl *D,
John McCall4d9f1422011-02-15 22:21:29 +0000312 uint64_t fieldOffset) {
313 uint64_t fieldSize =
Anders Carlsson307846f2009-07-23 03:17:50 +0000314 D->getBitWidth()->EvaluateAsInt(Types.getContext()).getZExtValue();
Mike Stump11289f42009-09-09 15:08:12 +0000315
John McCall4d9f1422011-02-15 22:21:29 +0000316 if (fieldSize == 0)
Anders Carlsson307846f2009-07-23 03:17:50 +0000317 return;
318
John McCall4d9f1422011-02-15 22:21:29 +0000319 uint64_t nextFieldOffsetInBits = NextFieldOffset.getQuantity() * 8;
320 unsigned numBytesToAppend;
Mike Stump11289f42009-09-09 15:08:12 +0000321
John McCall4d9f1422011-02-15 22:21:29 +0000322 if (fieldOffset < nextFieldOffsetInBits) {
Anders Carlsson307846f2009-07-23 03:17:50 +0000323 assert(BitsAvailableInLastField && "Bitfield size mismatch!");
John McCall4d9f1422011-02-15 22:21:29 +0000324 assert(!NextFieldOffset.isZero() && "Must have laid out at least one byte");
Mike Stump11289f42009-09-09 15:08:12 +0000325
Anders Carlsson307846f2009-07-23 03:17:50 +0000326 // The bitfield begins in the previous bit-field.
John McCall4d9f1422011-02-15 22:21:29 +0000327 numBytesToAppend =
328 llvm::RoundUpToAlignment(fieldSize - BitsAvailableInLastField, 8) / 8;
Anders Carlsson307846f2009-07-23 03:17:50 +0000329 } else {
John McCall4d9f1422011-02-15 22:21:29 +0000330 assert(fieldOffset % 8 == 0 && "Field offset not aligned correctly");
Anders Carlsson307846f2009-07-23 03:17:50 +0000331
332 // Append padding if necessary.
John McCall4d9f1422011-02-15 22:21:29 +0000333 AppendPadding(CharUnits::fromQuantity(fieldOffset / 8), CharUnits::One());
Mike Stump11289f42009-09-09 15:08:12 +0000334
John McCall4d9f1422011-02-15 22:21:29 +0000335 numBytesToAppend = llvm::RoundUpToAlignment(fieldSize, 8) / 8;
Mike Stump11289f42009-09-09 15:08:12 +0000336
John McCall4d9f1422011-02-15 22:21:29 +0000337 assert(numBytesToAppend && "No bytes to append!");
Anders Carlsson307846f2009-07-23 03:17:50 +0000338 }
339
Daniel Dunbarf9c24f82010-04-12 21:01:28 +0000340 // Add the bit field info.
John McCall0217dfc22011-02-15 06:40:56 +0000341 BitFields.insert(std::make_pair(D,
John McCall4d9f1422011-02-15 22:21:29 +0000342 CGBitFieldInfo::MakeInfo(Types, D, fieldOffset, fieldSize)));
Mike Stump11289f42009-09-09 15:08:12 +0000343
John McCall4d9f1422011-02-15 22:21:29 +0000344 AppendBytes(CharUnits::fromQuantity(numBytesToAppend));
Mike Stump11289f42009-09-09 15:08:12 +0000345
Mike Stump11289f42009-09-09 15:08:12 +0000346 BitsAvailableInLastField =
John McCall4d9f1422011-02-15 22:21:29 +0000347 NextFieldOffset.getQuantity() * 8 - (fieldOffset + fieldSize);
Anders Carlsson307846f2009-07-23 03:17:50 +0000348}
349
350bool CGRecordLayoutBuilder::LayoutField(const FieldDecl *D,
John McCall4d9f1422011-02-15 22:21:29 +0000351 uint64_t fieldOffset) {
Anders Carlsson307846f2009-07-23 03:17:50 +0000352 // If the field is packed, then we need a packed struct.
Anders Carlsson68e0b682009-08-08 18:23:56 +0000353 if (!Packed && D->hasAttr<PackedAttr>())
Anders Carlsson307846f2009-07-23 03:17:50 +0000354 return false;
355
356 if (D->isBitField()) {
357 // We must use packed structs for unnamed bit fields since they
358 // don't affect the struct alignment.
Anders Carlssond78fc892009-07-23 17:24:40 +0000359 if (!Packed && !D->getDeclName())
Anders Carlsson307846f2009-07-23 03:17:50 +0000360 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000361
John McCall4d9f1422011-02-15 22:21:29 +0000362 LayoutBitField(D, fieldOffset);
Anders Carlsson307846f2009-07-23 03:17:50 +0000363 return true;
364 }
Mike Stump11289f42009-09-09 15:08:12 +0000365
John McCall614dbdc2010-08-22 21:01:12 +0000366 CheckZeroInitializable(D->getType());
Daniel Dunbar23ee4b72010-03-31 00:11:27 +0000367
John McCall4d9f1422011-02-15 22:21:29 +0000368 assert(fieldOffset % 8 == 0 && "FieldOffset is not on a byte boundary!");
369 CharUnits fieldOffsetInBytes = CharUnits::fromQuantity(fieldOffset / 8);
Mike Stump11289f42009-09-09 15:08:12 +0000370
Anders Carlsson19702bb2009-08-04 16:29:15 +0000371 const llvm::Type *Ty = Types.ConvertTypeForMemRecursive(D->getType());
John McCall4d9f1422011-02-15 22:21:29 +0000372 CharUnits typeAlignment = getTypeAlignment(Ty);
Anders Carlsson19702bb2009-08-04 16:29:15 +0000373
Anders Carlsson28a5fa22009-08-08 19:38:24 +0000374 // If the type alignment is larger then the struct alignment, we must use
375 // a packed struct.
John McCall4d9f1422011-02-15 22:21:29 +0000376 if (typeAlignment > Alignment) {
Anders Carlsson28a5fa22009-08-08 19:38:24 +0000377 assert(!Packed && "Alignment is wrong even with packed struct!");
378 return false;
379 }
Mike Stump11289f42009-09-09 15:08:12 +0000380
John McCall4d9f1422011-02-15 22:21:29 +0000381 if (!Packed) {
382 if (const RecordType *RT = D->getType()->getAs<RecordType>()) {
383 const RecordDecl *RD = cast<RecordDecl>(RT->getDecl());
384 if (const MaxFieldAlignmentAttr *MFAA =
385 RD->getAttr<MaxFieldAlignmentAttr>()) {
386 if (MFAA->getAlignment() != typeAlignment.getQuantity() * 8)
387 return false;
388 }
Anders Carlsson28a5fa22009-08-08 19:38:24 +0000389 }
390 }
391
Anders Carlsson19702bb2009-08-04 16:29:15 +0000392 // Round up the field offset to the alignment of the field type.
John McCall4d9f1422011-02-15 22:21:29 +0000393 CharUnits alignedNextFieldOffsetInBytes =
394 NextFieldOffset.RoundUpToAlignment(typeAlignment);
Anders Carlsson19702bb2009-08-04 16:29:15 +0000395
John McCall4d9f1422011-02-15 22:21:29 +0000396 if (fieldOffsetInBytes < alignedNextFieldOffsetInBytes) {
Anders Carlsson19702bb2009-08-04 16:29:15 +0000397 assert(!Packed && "Could not place field even with packed struct!");
398 return false;
399 }
Mike Stump11289f42009-09-09 15:08:12 +0000400
John McCall4d9f1422011-02-15 22:21:29 +0000401 AppendPadding(fieldOffsetInBytes, typeAlignment);
Mike Stump11289f42009-09-09 15:08:12 +0000402
Anders Carlsson307846f2009-07-23 03:17:50 +0000403 // Now append the field.
John McCall0217dfc22011-02-15 06:40:56 +0000404 Fields[D] = FieldTypes.size();
John McCall4d9f1422011-02-15 22:21:29 +0000405 AppendField(fieldOffsetInBytes, Ty);
Mike Stump11289f42009-09-09 15:08:12 +0000406
Anders Carlsson307846f2009-07-23 03:17:50 +0000407 return true;
408}
409
Anders Carlsson1de2f572010-04-17 20:49:27 +0000410const llvm::Type *
411CGRecordLayoutBuilder::LayoutUnionField(const FieldDecl *Field,
412 const ASTRecordLayout &Layout) {
413 if (Field->isBitField()) {
414 uint64_t FieldSize =
415 Field->getBitWidth()->EvaluateAsInt(Types.getContext()).getZExtValue();
416
417 // Ignore zero sized bit fields.
418 if (FieldSize == 0)
419 return 0;
420
Daniel Dunbar20b551a2010-04-20 17:52:30 +0000421 const llvm::Type *FieldTy = llvm::Type::getInt8Ty(Types.getLLVMContext());
422 unsigned NumBytesToAppend =
423 llvm::RoundUpToAlignment(FieldSize, 8) / 8;
Anders Carlsson2295f132010-04-17 21:04:52 +0000424
Daniel Dunbar20b551a2010-04-20 17:52:30 +0000425 if (NumBytesToAppend > 1)
426 FieldTy = llvm::ArrayType::get(FieldTy, NumBytesToAppend);
Anders Carlsson2295f132010-04-17 21:04:52 +0000427
Anders Carlsson1de2f572010-04-17 20:49:27 +0000428 // Add the bit field info.
John McCall0217dfc22011-02-15 06:40:56 +0000429 BitFields.insert(std::make_pair(Field,
430 CGBitFieldInfo::MakeInfo(Types, Field, 0, FieldSize)));
Anders Carlsson2295f132010-04-17 21:04:52 +0000431 return FieldTy;
Anders Carlsson1de2f572010-04-17 20:49:27 +0000432 }
Daniel Dunbar20b551a2010-04-20 17:52:30 +0000433
Anders Carlsson1de2f572010-04-17 20:49:27 +0000434 // This is a regular union field.
John McCall0217dfc22011-02-15 06:40:56 +0000435 Fields[Field] = 0;
Anders Carlsson1de2f572010-04-17 20:49:27 +0000436 return Types.ConvertTypeForMemRecursive(Field->getType());
437}
438
Anders Carlsson697f6592009-07-23 03:43:54 +0000439void CGRecordLayoutBuilder::LayoutUnion(const RecordDecl *D) {
440 assert(D->isUnion() && "Can't call LayoutUnion on a non-union record!");
Mike Stump11289f42009-09-09 15:08:12 +0000441
John McCall4d9f1422011-02-15 22:21:29 +0000442 const ASTRecordLayout &layout = Types.getContext().getASTRecordLayout(D);
Mike Stump11289f42009-09-09 15:08:12 +0000443
John McCall4d9f1422011-02-15 22:21:29 +0000444 const llvm::Type *unionType = 0;
445 CharUnits unionSize = CharUnits::Zero();
446 CharUnits unionAlign = CharUnits::Zero();
Mike Stump11289f42009-09-09 15:08:12 +0000447
John McCall4d9f1422011-02-15 22:21:29 +0000448 bool hasOnlyZeroSizedBitFields = true;
Daniel Dunbar23ee4b72010-03-31 00:11:27 +0000449
John McCall4d9f1422011-02-15 22:21:29 +0000450 unsigned fieldNo = 0;
451 for (RecordDecl::field_iterator field = D->field_begin(),
452 fieldEnd = D->field_end(); field != fieldEnd; ++field, ++fieldNo) {
453 assert(layout.getFieldOffset(fieldNo) == 0 &&
Anders Carlsson697f6592009-07-23 03:43:54 +0000454 "Union field offset did not start at the beginning of record!");
John McCall4d9f1422011-02-15 22:21:29 +0000455 const llvm::Type *fieldType = LayoutUnionField(*field, layout);
Anders Carlssonf814ee62009-07-23 04:00:39 +0000456
John McCall4d9f1422011-02-15 22:21:29 +0000457 if (!fieldType)
Anders Carlsson1de2f572010-04-17 20:49:27 +0000458 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000459
John McCall4d9f1422011-02-15 22:21:29 +0000460 hasOnlyZeroSizedBitFields = false;
Daniel Dunbar23ee4b72010-03-31 00:11:27 +0000461
John McCall4d9f1422011-02-15 22:21:29 +0000462 CharUnits fieldAlign = CharUnits::fromQuantity(
463 Types.getTargetData().getABITypeAlignment(fieldType));
464 CharUnits fieldSize = CharUnits::fromQuantity(
465 Types.getTargetData().getTypeAllocSize(fieldType));
Mike Stump11289f42009-09-09 15:08:12 +0000466
John McCall4d9f1422011-02-15 22:21:29 +0000467 if (fieldAlign < unionAlign)
Anders Carlsson697f6592009-07-23 03:43:54 +0000468 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000469
John McCall4d9f1422011-02-15 22:21:29 +0000470 if (fieldAlign > unionAlign || fieldSize > unionSize) {
471 unionType = fieldType;
472 unionAlign = fieldAlign;
473 unionSize = fieldSize;
Anders Carlsson697f6592009-07-23 03:43:54 +0000474 }
475 }
Mike Stump11289f42009-09-09 15:08:12 +0000476
Anders Carlsson697f6592009-07-23 03:43:54 +0000477 // Now add our field.
John McCall4d9f1422011-02-15 22:21:29 +0000478 if (unionType) {
479 AppendField(CharUnits::Zero(), unionType);
Anders Carlsson0e912752009-09-03 22:56:02 +0000480
John McCall4d9f1422011-02-15 22:21:29 +0000481 if (getTypeAlignment(unionType) > layout.getAlignment()) {
Anders Carlsson0e912752009-09-03 22:56:02 +0000482 // We need a packed struct.
483 Packed = true;
John McCall4d9f1422011-02-15 22:21:29 +0000484 unionAlign = CharUnits::One();
Anders Carlsson0e912752009-09-03 22:56:02 +0000485 }
486 }
John McCall4d9f1422011-02-15 22:21:29 +0000487 if (unionAlign.isZero()) {
488 assert(hasOnlyZeroSizedBitFields &&
Anders Carlssonb1ef9912010-01-28 18:22:03 +0000489 "0-align record did not have all zero-sized bit-fields!");
John McCall4d9f1422011-02-15 22:21:29 +0000490 unionAlign = CharUnits::One();
Fariborz Jahaniane8e631c2009-11-06 20:47:40 +0000491 }
Daniel Dunbar23ee4b72010-03-31 00:11:27 +0000492
Anders Carlsson697f6592009-07-23 03:43:54 +0000493 // Append tail padding.
John McCall4d9f1422011-02-15 22:21:29 +0000494 CharUnits recordSize = layout.getSize();
495 if (recordSize > unionSize)
496 AppendPadding(recordSize, unionAlign);
Anders Carlsson697f6592009-07-23 03:43:54 +0000497}
498
John McCall0217dfc22011-02-15 06:40:56 +0000499void CGRecordLayoutBuilder::LayoutBase(const CXXRecordDecl *base,
John McCall4d9f1422011-02-15 22:21:29 +0000500 const CGRecordLayout &baseLayout,
501 CharUnits baseOffset) {
502 AppendPadding(baseOffset, CharUnits::One());
Anders Carlssona518b2a2010-12-04 23:59:48 +0000503
John McCall0217dfc22011-02-15 06:40:56 +0000504 const ASTRecordLayout &baseASTLayout
505 = Types.getContext().getASTRecordLayout(base);
506
John McCall4d9f1422011-02-15 22:21:29 +0000507 // Fields and bases can be laid out in the tail padding of previous
508 // bases. If this happens, we need to allocate the base as an i8
509 // array; otherwise, we can use the subobject type. However,
510 // actually doing that would require knowledge of what immediately
511 // follows this base in the layout, so instead we do a conservative
512 // approximation, which is to use the base subobject type if it
513 // has the same LLVM storage size as the nvsize.
514
515 // The nvsize, i.e. the unpadded size of the base class.
516 CharUnits nvsize = baseASTLayout.getNonVirtualSize();
517
518#if 0
519 const llvm::StructType *subobjectType = baseLayout.getBaseSubobjectLLVMType();
520 const llvm::StructLayout *baseLLVMLayout =
521 Types.getTargetData().getStructLayout(subobjectType);
522 CharUnits stsize = CharUnits::fromQuantity(baseLLVMLayout->getSizeInBytes());
523
524 if (nvsize == stsize)
525 AppendField(baseOffset, subobjectType);
526 else
527#endif
528 AppendBytes(nvsize);
John McCall0217dfc22011-02-15 06:40:56 +0000529}
530
531void CGRecordLayoutBuilder::LayoutNonVirtualBase(const CXXRecordDecl *base,
John McCall4d9f1422011-02-15 22:21:29 +0000532 CharUnits baseOffset) {
John McCall0217dfc22011-02-15 06:40:56 +0000533 // Ignore empty bases.
534 if (base->isEmpty()) return;
535
536 const CGRecordLayout &baseLayout = Types.getCGRecordLayout(base);
537 if (IsZeroInitializableAsBase) {
538 assert(IsZeroInitializable &&
539 "class zero-initializable as base but not as complete object");
540
541 IsZeroInitializable = IsZeroInitializableAsBase =
542 baseLayout.isZeroInitializableAsBase();
543 }
544
John McCall4d9f1422011-02-15 22:21:29 +0000545 LayoutBase(base, baseLayout, baseOffset);
John McCall0217dfc22011-02-15 06:40:56 +0000546 NonVirtualBases[base] = (FieldTypes.size() - 1);
Anders Carlssona518b2a2010-12-04 23:59:48 +0000547}
548
Anders Carlsson1f95ee32010-11-25 01:59:35 +0000549void
John McCall0217dfc22011-02-15 06:40:56 +0000550CGRecordLayoutBuilder::LayoutVirtualBase(const CXXRecordDecl *base,
John McCall4d9f1422011-02-15 22:21:29 +0000551 CharUnits baseOffset) {
Anders Carlsson1f95ee32010-11-25 01:59:35 +0000552 // Ignore empty bases.
John McCall0217dfc22011-02-15 06:40:56 +0000553 if (base->isEmpty()) return;
Anders Carlsson1f95ee32010-11-25 01:59:35 +0000554
John McCall0217dfc22011-02-15 06:40:56 +0000555 const CGRecordLayout &baseLayout = Types.getCGRecordLayout(base);
556 if (IsZeroInitializable)
557 IsZeroInitializable = baseLayout.isZeroInitializableAsBase();
Anders Carlsson1f95ee32010-11-25 01:59:35 +0000558
John McCall4d9f1422011-02-15 22:21:29 +0000559 LayoutBase(base, baseLayout, baseOffset);
John McCall0217dfc22011-02-15 06:40:56 +0000560 VirtualBases[base] = (FieldTypes.size() - 1);
Anders Carlsson1f95ee32010-11-25 01:59:35 +0000561}
562
Anders Carlssona459adb2010-11-28 19:18:44 +0000563/// LayoutVirtualBases - layout the non-virtual bases of a record decl.
564void
565CGRecordLayoutBuilder::LayoutVirtualBases(const CXXRecordDecl *RD,
566 const ASTRecordLayout &Layout) {
567 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
568 E = RD->bases_end(); I != E; ++I) {
569 const CXXRecordDecl *BaseDecl =
570 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
571
572 // We only want to lay out virtual bases that aren't indirect primary bases
573 // of some other base.
574 if (I->isVirtual() && !IndirectPrimaryBases.count(BaseDecl)) {
575 // Only lay out the base once.
576 if (!LaidOutVirtualBases.insert(BaseDecl))
577 continue;
578
John McCall4d9f1422011-02-15 22:21:29 +0000579 CharUnits vbaseOffset = Layout.getVBaseClassOffset(BaseDecl);
580 LayoutVirtualBase(BaseDecl, vbaseOffset);
Anders Carlssona459adb2010-11-28 19:18:44 +0000581 }
582
583 if (!BaseDecl->getNumVBases()) {
584 // This base isn't interesting since it doesn't have any virtual bases.
585 continue;
586 }
587
588 LayoutVirtualBases(BaseDecl, Layout);
589 }
590}
591
Anders Carlssonaf9e5af2010-05-18 05:12:20 +0000592void
593CGRecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl *RD,
594 const ASTRecordLayout &Layout) {
595 const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
596
597 // Check if we need to add a vtable pointer.
598 if (RD->isDynamicClass()) {
599 if (!PrimaryBase) {
600 const llvm::Type *FunctionType =
601 llvm::FunctionType::get(llvm::Type::getInt32Ty(Types.getLLVMContext()),
602 /*isVarArg=*/true);
603 const llvm::Type *VTableTy = FunctionType->getPointerTo();
604
John McCall4d9f1422011-02-15 22:21:29 +0000605 assert(NextFieldOffset.isZero() &&
Anders Carlssonaf9e5af2010-05-18 05:12:20 +0000606 "VTable pointer must come first!");
John McCall4d9f1422011-02-15 22:21:29 +0000607 AppendField(CharUnits::Zero(), VTableTy->getPointerTo());
Anders Carlssonaf9e5af2010-05-18 05:12:20 +0000608 } else {
Anders Carlsson7f95cd12010-11-24 23:12:57 +0000609 if (!Layout.isPrimaryBaseVirtual())
John McCall4d9f1422011-02-15 22:21:29 +0000610 LayoutNonVirtualBase(PrimaryBase, CharUnits::Zero());
Anders Carlsson1f95ee32010-11-25 01:59:35 +0000611 else
John McCall4d9f1422011-02-15 22:21:29 +0000612 LayoutVirtualBase(PrimaryBase, CharUnits::Zero());
Anders Carlssonaf9e5af2010-05-18 05:12:20 +0000613 }
614 }
615
616 // Layout the non-virtual bases.
617 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
618 E = RD->bases_end(); I != E; ++I) {
619 if (I->isVirtual())
620 continue;
621
622 const CXXRecordDecl *BaseDecl =
623 cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
624
625 // We've already laid out the primary base.
Anders Carlsson7f95cd12010-11-24 23:12:57 +0000626 if (BaseDecl == PrimaryBase && !Layout.isPrimaryBaseVirtual())
Anders Carlssonaf9e5af2010-05-18 05:12:20 +0000627 continue;
628
John McCall4d9f1422011-02-15 22:21:29 +0000629 LayoutNonVirtualBase(BaseDecl, Layout.getBaseClassOffset(BaseDecl));
Anders Carlssond681a292009-12-16 17:27:20 +0000630 }
631}
632
Argyrios Kyrtzidis648fcbe2010-12-10 00:11:00 +0000633bool
Anders Carlssonc1351ca2010-11-09 05:25:47 +0000634CGRecordLayoutBuilder::ComputeNonVirtualBaseType(const CXXRecordDecl *RD) {
635 const ASTRecordLayout &Layout = Types.getContext().getASTRecordLayout(RD);
636
Ken Dyckbec02852011-02-08 02:02:47 +0000637 CharUnits NonVirtualSize = Layout.getNonVirtualSize();
638 CharUnits NonVirtualAlign = Layout.getNonVirtualAlign();
John McCall4d9f1422011-02-15 22:21:29 +0000639 CharUnits AlignedNonVirtualTypeSize =
640 NonVirtualSize.RoundUpToAlignment(NonVirtualAlign);
Anders Carlssonc1351ca2010-11-09 05:25:47 +0000641
Anders Carlssonc1351ca2010-11-09 05:25:47 +0000642 // First check if we can use the same fields as for the complete class.
John McCall4d9f1422011-02-15 22:21:29 +0000643 CharUnits RecordSize = Layout.getSize();
John McCall0217dfc22011-02-15 06:40:56 +0000644 if (AlignedNonVirtualTypeSize == RecordSize)
Argyrios Kyrtzidis648fcbe2010-12-10 00:11:00 +0000645 return true;
Anders Carlssonc1351ca2010-11-09 05:25:47 +0000646
Anders Carlssonc1351ca2010-11-09 05:25:47 +0000647 // Check if we need padding.
John McCall4d9f1422011-02-15 22:21:29 +0000648 CharUnits AlignedNextFieldOffset =
649 NextFieldOffset.RoundUpToAlignment(getAlignmentAsLLVMStruct());
Anders Carlssonc1351ca2010-11-09 05:25:47 +0000650
John McCall0217dfc22011-02-15 06:40:56 +0000651 if (AlignedNextFieldOffset > AlignedNonVirtualTypeSize) {
652 assert(!Packed && "cannot layout even as packed struct");
Argyrios Kyrtzidis648fcbe2010-12-10 00:11:00 +0000653 return false; // Needs packing.
Anders Carlssonc1351ca2010-11-09 05:25:47 +0000654 }
655
John McCall0217dfc22011-02-15 06:40:56 +0000656 bool needsPadding = (AlignedNonVirtualTypeSize != AlignedNextFieldOffset);
657 if (needsPadding) {
John McCall4d9f1422011-02-15 22:21:29 +0000658 CharUnits NumBytes = AlignedNonVirtualTypeSize - AlignedNextFieldOffset;
John McCall0217dfc22011-02-15 06:40:56 +0000659 FieldTypes.push_back(getByteArrayType(NumBytes));
660 }
661
662 BaseSubobjectType = llvm::StructType::get(Types.getLLVMContext(),
663 FieldTypes, Packed);
664
665 if (needsPadding) {
666 // Pull the padding back off.
667 FieldTypes.pop_back();
668 }
669
Argyrios Kyrtzidis648fcbe2010-12-10 00:11:00 +0000670 return true;
Anders Carlssonc1351ca2010-11-09 05:25:47 +0000671}
672
Anders Carlsson307846f2009-07-23 03:17:50 +0000673bool CGRecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
674 assert(!D->isUnion() && "Can't call LayoutFields on a union!");
John McCall4d9f1422011-02-15 22:21:29 +0000675 assert(!Alignment.isZero() && "Did not set alignment!");
Mike Stump11289f42009-09-09 15:08:12 +0000676
Anders Carlsson697f6592009-07-23 03:43:54 +0000677 const ASTRecordLayout &Layout = Types.getContext().getASTRecordLayout(D);
Mike Stump11289f42009-09-09 15:08:12 +0000678
Anders Carlssonc1351ca2010-11-09 05:25:47 +0000679 const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D);
680 if (RD)
Anders Carlssonaf9e5af2010-05-18 05:12:20 +0000681 LayoutNonVirtualBases(RD, Layout);
Daniel Dunbar23ee4b72010-03-31 00:11:27 +0000682
Anders Carlsson307846f2009-07-23 03:17:50 +0000683 unsigned FieldNo = 0;
Fariborz Jahanian7b2b1ec2009-07-27 20:57:45 +0000684
Mike Stump11289f42009-09-09 15:08:12 +0000685 for (RecordDecl::field_iterator Field = D->field_begin(),
Anders Carlsson307846f2009-07-23 03:17:50 +0000686 FieldEnd = D->field_end(); Field != FieldEnd; ++Field, ++FieldNo) {
687 if (!LayoutField(*Field, Layout.getFieldOffset(FieldNo))) {
Mike Stump11289f42009-09-09 15:08:12 +0000688 assert(!Packed &&
Anders Carlsson307846f2009-07-23 03:17:50 +0000689 "Could not layout fields even with a packed LLVM struct!");
690 return false;
691 }
692 }
693
Anders Carlsson1f95ee32010-11-25 01:59:35 +0000694 if (RD) {
Anders Carlssona459adb2010-11-28 19:18:44 +0000695 // We've laid out the non-virtual bases and the fields, now compute the
696 // non-virtual base field types.
Argyrios Kyrtzidis648fcbe2010-12-10 00:11:00 +0000697 if (!ComputeNonVirtualBaseType(RD)) {
698 assert(!Packed && "Could not layout even with a packed LLVM struct!");
699 return false;
700 }
Anders Carlsson1f95ee32010-11-25 01:59:35 +0000701
Anders Carlssona459adb2010-11-28 19:18:44 +0000702 // And lay out the virtual bases.
703 RD->getIndirectPrimaryBases(IndirectPrimaryBases);
704 if (Layout.isPrimaryBaseVirtual())
705 IndirectPrimaryBases.insert(Layout.getPrimaryBase());
706 LayoutVirtualBases(RD, Layout);
707 }
Anders Carlssonc1351ca2010-11-09 05:25:47 +0000708
Anders Carlsson307846f2009-07-23 03:17:50 +0000709 // Append tail padding if necessary.
Ken Dyckb0fcc592011-02-11 01:54:29 +0000710 AppendTailPadding(Types.getContext().toBits(Layout.getSize()));
Mike Stump11289f42009-09-09 15:08:12 +0000711
Anders Carlsson307846f2009-07-23 03:17:50 +0000712 return true;
713}
714
Anders Carlssonb97a3ec2009-07-27 14:55:54 +0000715void CGRecordLayoutBuilder::AppendTailPadding(uint64_t RecordSize) {
716 assert(RecordSize % 8 == 0 && "Invalid record size!");
Mike Stump11289f42009-09-09 15:08:12 +0000717
John McCall4d9f1422011-02-15 22:21:29 +0000718 CharUnits RecordSizeInBytes = CharUnits::fromQuantity(RecordSize / 8);
719 assert(NextFieldOffset <= RecordSizeInBytes && "Size mismatch!");
Mike Stump11289f42009-09-09 15:08:12 +0000720
John McCall4d9f1422011-02-15 22:21:29 +0000721 CharUnits AlignedNextFieldOffset =
722 NextFieldOffset.RoundUpToAlignment(getAlignmentAsLLVMStruct());
Anders Carlsson220bf4f2009-12-08 01:24:23 +0000723
724 if (AlignedNextFieldOffset == RecordSizeInBytes) {
725 // We don't need any padding.
726 return;
727 }
Daniel Dunbar23ee4b72010-03-31 00:11:27 +0000728
John McCall4d9f1422011-02-15 22:21:29 +0000729 CharUnits NumPadBytes = RecordSizeInBytes - NextFieldOffset;
Anders Carlssonb97a3ec2009-07-27 14:55:54 +0000730 AppendBytes(NumPadBytes);
731}
732
John McCall4d9f1422011-02-15 22:21:29 +0000733void CGRecordLayoutBuilder::AppendField(CharUnits fieldOffset,
734 const llvm::Type *fieldType) {
735 CharUnits fieldSize =
736 CharUnits::fromQuantity(Types.getTargetData().getTypeAllocSize(fieldType));
Anders Carlsson6e853bf2009-07-24 02:45:50 +0000737
John McCall4d9f1422011-02-15 22:21:29 +0000738 FieldTypes.push_back(fieldType);
Anders Carlsson307846f2009-07-23 03:17:50 +0000739
John McCall4d9f1422011-02-15 22:21:29 +0000740 NextFieldOffset = fieldOffset + fieldSize;
Anders Carlsson307846f2009-07-23 03:17:50 +0000741 BitsAvailableInLastField = 0;
742}
743
John McCall4d9f1422011-02-15 22:21:29 +0000744void CGRecordLayoutBuilder::AppendPadding(CharUnits fieldOffset,
745 CharUnits fieldAlignment) {
746 assert(NextFieldOffset <= fieldOffset &&
Anders Carlsson307846f2009-07-23 03:17:50 +0000747 "Incorrect field layout!");
Mike Stump11289f42009-09-09 15:08:12 +0000748
Anders Carlsson307846f2009-07-23 03:17:50 +0000749 // Round up the field offset to the alignment of the field type.
John McCall4d9f1422011-02-15 22:21:29 +0000750 CharUnits alignedNextFieldOffset =
751 NextFieldOffset.RoundUpToAlignment(fieldAlignment);
Anders Carlsson307846f2009-07-23 03:17:50 +0000752
John McCall4d9f1422011-02-15 22:21:29 +0000753 if (alignedNextFieldOffset < fieldOffset) {
Anders Carlsson307846f2009-07-23 03:17:50 +0000754 // Even with alignment, the field offset is not at the right place,
755 // insert padding.
John McCall4d9f1422011-02-15 22:21:29 +0000756 CharUnits padding = fieldOffset - NextFieldOffset;
Anders Carlsson307846f2009-07-23 03:17:50 +0000757
John McCall4d9f1422011-02-15 22:21:29 +0000758 AppendBytes(padding);
Anders Carlsson307846f2009-07-23 03:17:50 +0000759 }
760}
761
John McCall4d9f1422011-02-15 22:21:29 +0000762const llvm::Type *CGRecordLayoutBuilder::getByteArrayType(CharUnits numBytes) {
763 assert(!numBytes.isZero() && "Empty byte arrays aren't allowed.");
Mike Stump11289f42009-09-09 15:08:12 +0000764
Owen Anderson41a75022009-08-13 21:57:51 +0000765 const llvm::Type *Ty = llvm::Type::getInt8Ty(Types.getLLVMContext());
John McCall4d9f1422011-02-15 22:21:29 +0000766 if (numBytes > CharUnits::One())
767 Ty = llvm::ArrayType::get(Ty, numBytes.getQuantity());
Mike Stump11289f42009-09-09 15:08:12 +0000768
Anders Carlssonc1351ca2010-11-09 05:25:47 +0000769 return Ty;
770}
771
John McCall4d9f1422011-02-15 22:21:29 +0000772void CGRecordLayoutBuilder::AppendBytes(CharUnits numBytes) {
773 if (numBytes.isZero())
Anders Carlssonc1351ca2010-11-09 05:25:47 +0000774 return;
775
Anders Carlsson307846f2009-07-23 03:17:50 +0000776 // Append the padding field
John McCall4d9f1422011-02-15 22:21:29 +0000777 AppendField(NextFieldOffset, getByteArrayType(numBytes));
Anders Carlsson307846f2009-07-23 03:17:50 +0000778}
779
John McCall4d9f1422011-02-15 22:21:29 +0000780CharUnits CGRecordLayoutBuilder::getTypeAlignment(const llvm::Type *Ty) const {
Anders Carlssond78fc892009-07-23 17:24:40 +0000781 if (Packed)
John McCall4d9f1422011-02-15 22:21:29 +0000782 return CharUnits::One();
Mike Stump11289f42009-09-09 15:08:12 +0000783
John McCall4d9f1422011-02-15 22:21:29 +0000784 return CharUnits::fromQuantity(Types.getTargetData().getABITypeAlignment(Ty));
Anders Carlsson307846f2009-07-23 03:17:50 +0000785}
786
John McCall4d9f1422011-02-15 22:21:29 +0000787CharUnits CGRecordLayoutBuilder::getAlignmentAsLLVMStruct() const {
Anders Carlssonacf877b2010-11-28 23:06:23 +0000788 if (Packed)
John McCall4d9f1422011-02-15 22:21:29 +0000789 return CharUnits::One();
Anders Carlssonacf877b2010-11-28 23:06:23 +0000790
John McCall4d9f1422011-02-15 22:21:29 +0000791 CharUnits maxAlignment = CharUnits::One();
Anders Carlssonacf877b2010-11-28 23:06:23 +0000792 for (size_t i = 0; i != FieldTypes.size(); ++i)
John McCall4d9f1422011-02-15 22:21:29 +0000793 maxAlignment = std::max(maxAlignment, getTypeAlignment(FieldTypes[i]));
Anders Carlssonacf877b2010-11-28 23:06:23 +0000794
John McCall4d9f1422011-02-15 22:21:29 +0000795 return maxAlignment;
Anders Carlssonacf877b2010-11-28 23:06:23 +0000796}
797
John McCall0217dfc22011-02-15 06:40:56 +0000798/// Merge in whether a field of the given type is zero-initializable.
John McCall614dbdc2010-08-22 21:01:12 +0000799void CGRecordLayoutBuilder::CheckZeroInitializable(QualType T) {
Anders Carlssond606de72009-08-23 01:25:01 +0000800 // This record already contains a member pointer.
John McCall0217dfc22011-02-15 06:40:56 +0000801 if (!IsZeroInitializableAsBase)
Anders Carlssond606de72009-08-23 01:25:01 +0000802 return;
Mike Stump11289f42009-09-09 15:08:12 +0000803
Anders Carlssond606de72009-08-23 01:25:01 +0000804 // Can only have member pointers if we're compiling C++.
805 if (!Types.getContext().getLangOptions().CPlusPlus)
806 return;
Mike Stump11289f42009-09-09 15:08:12 +0000807
John McCall0217dfc22011-02-15 06:40:56 +0000808 const Type *elementType = T->getBaseElementTypeUnsafe();
Mike Stump11289f42009-09-09 15:08:12 +0000809
John McCall0217dfc22011-02-15 06:40:56 +0000810 if (const MemberPointerType *MPT = elementType->getAs<MemberPointerType>()) {
John McCall614dbdc2010-08-22 21:01:12 +0000811 if (!Types.getCXXABI().isZeroInitializable(MPT))
John McCall0217dfc22011-02-15 06:40:56 +0000812 IsZeroInitializable = IsZeroInitializableAsBase = false;
813 } else if (const RecordType *RT = elementType->getAs<RecordType>()) {
Anders Carlssone8bfe412010-02-02 05:17:25 +0000814 const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
John McCall0217dfc22011-02-15 06:40:56 +0000815 const CGRecordLayout &Layout = Types.getCGRecordLayout(RD);
816 if (!Layout.isZeroInitializable())
817 IsZeroInitializable = IsZeroInitializableAsBase = false;
Daniel Dunbar23ee4b72010-03-31 00:11:27 +0000818 }
Anders Carlssond606de72009-08-23 01:25:01 +0000819}
820
Daniel Dunbar23ee4b72010-03-31 00:11:27 +0000821CGRecordLayout *CodeGenTypes::ComputeRecordLayout(const RecordDecl *D) {
822 CGRecordLayoutBuilder Builder(*this);
Mike Stump11289f42009-09-09 15:08:12 +0000823
Anders Carlsson307846f2009-07-23 03:17:50 +0000824 Builder.Layout(D);
Anders Carlssone1d5ca52009-07-24 15:20:52 +0000825
Anders Carlsson36e2fa82010-11-24 19:37:16 +0000826 const llvm::StructType *Ty = llvm::StructType::get(getLLVMContext(),
827 Builder.FieldTypes,
828 Builder.Packed);
Mike Stump11289f42009-09-09 15:08:12 +0000829
John McCall0217dfc22011-02-15 06:40:56 +0000830 // If we're in C++, compute the base subobject type.
Anders Carlsson36e2fa82010-11-24 19:37:16 +0000831 const llvm::StructType *BaseTy = 0;
Anders Carlssonc1351ca2010-11-09 05:25:47 +0000832 if (isa<CXXRecordDecl>(D)) {
John McCall0217dfc22011-02-15 06:40:56 +0000833 BaseTy = Builder.BaseSubobjectType;
834 if (!BaseTy) BaseTy = Ty;
Anders Carlssonc1351ca2010-11-09 05:25:47 +0000835 }
836
Daniel Dunbar034299e2010-03-31 01:09:11 +0000837 CGRecordLayout *RL =
John McCall0217dfc22011-02-15 06:40:56 +0000838 new CGRecordLayout(Ty, BaseTy, Builder.IsZeroInitializable,
839 Builder.IsZeroInitializableAsBase);
Daniel Dunbar034299e2010-03-31 01:09:11 +0000840
John McCall0217dfc22011-02-15 06:40:56 +0000841 RL->NonVirtualBases.swap(Builder.NonVirtualBases);
842 RL->CompleteObjectVirtualBases.swap(Builder.VirtualBases);
Anders Carlsson061ca522010-05-18 05:22:06 +0000843
Anders Carlsson307846f2009-07-23 03:17:50 +0000844 // Add all the field numbers.
John McCall0217dfc22011-02-15 06:40:56 +0000845 RL->FieldInfo.swap(Builder.Fields);
Anders Carlsson307846f2009-07-23 03:17:50 +0000846
847 // Add bitfield info.
John McCall0217dfc22011-02-15 06:40:56 +0000848 RL->BitFields.swap(Builder.BitFields);
Mike Stump11289f42009-09-09 15:08:12 +0000849
Daniel Dunbar2ea51832010-04-19 20:44:47 +0000850 // Dump the layout, if requested.
Daniel Dunbarb935b932010-04-13 20:58:55 +0000851 if (getContext().getLangOptions().DumpRecordLayouts) {
Daniel Dunbarccabe482010-04-19 20:44:53 +0000852 llvm::errs() << "\n*** Dumping IRgen Record Layout\n";
Daniel Dunbarb935b932010-04-13 20:58:55 +0000853 llvm::errs() << "Record: ";
854 D->dump();
855 llvm::errs() << "\nLayout: ";
Daniel Dunbarb97bff92010-04-12 18:14:18 +0000856 RL->dump();
Daniel Dunbarb935b932010-04-13 20:58:55 +0000857 }
Daniel Dunbarb97bff92010-04-12 18:14:18 +0000858
Daniel Dunbar488f55c2010-04-22 02:35:46 +0000859#ifndef NDEBUG
Daniel Dunbar2ea51832010-04-19 20:44:47 +0000860 // Verify that the computed LLVM struct size matches the AST layout size.
Anders Carlssonc1351ca2010-11-09 05:25:47 +0000861 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(D);
862
Ken Dyckb0fcc592011-02-11 01:54:29 +0000863 uint64_t TypeSizeInBits = getContext().toBits(Layout.getSize());
Daniel Dunbar488f55c2010-04-22 02:35:46 +0000864 assert(TypeSizeInBits == getTargetData().getTypeAllocSizeInBits(Ty) &&
Daniel Dunbar2ea51832010-04-19 20:44:47 +0000865 "Type size mismatch!");
866
Anders Carlssonc1351ca2010-11-09 05:25:47 +0000867 if (BaseTy) {
Ken Dyckbec02852011-02-08 02:02:47 +0000868 CharUnits NonVirtualSize = Layout.getNonVirtualSize();
869 CharUnits NonVirtualAlign = Layout.getNonVirtualAlign();
870 CharUnits AlignedNonVirtualTypeSize =
871 NonVirtualSize.RoundUpToAlignment(NonVirtualAlign);
872
873 uint64_t AlignedNonVirtualTypeSizeInBits =
Ken Dyckb0fcc592011-02-11 01:54:29 +0000874 getContext().toBits(AlignedNonVirtualTypeSize);
Anders Carlssonc1351ca2010-11-09 05:25:47 +0000875
876 assert(AlignedNonVirtualTypeSizeInBits ==
877 getTargetData().getTypeAllocSizeInBits(BaseTy) &&
878 "Type size mismatch!");
879 }
880
Daniel Dunbar2ba67442010-04-21 19:10:49 +0000881 // Verify that the LLVM and AST field offsets agree.
Daniel Dunbar2ba67442010-04-21 19:10:49 +0000882 const llvm::StructType *ST =
883 dyn_cast<llvm::StructType>(RL->getLLVMType());
884 const llvm::StructLayout *SL = getTargetData().getStructLayout(ST);
885
886 const ASTRecordLayout &AST_RL = getContext().getASTRecordLayout(D);
887 RecordDecl::field_iterator it = D->field_begin();
888 for (unsigned i = 0, e = AST_RL.getFieldCount(); i != e; ++i, ++it) {
889 const FieldDecl *FD = *it;
Daniel Dunbar488f55c2010-04-22 02:35:46 +0000890
891 // For non-bit-fields, just check that the LLVM struct offset matches the
892 // AST offset.
893 if (!FD->isBitField()) {
Daniel Dunbar2ba67442010-04-21 19:10:49 +0000894 unsigned FieldNo = RL->getLLVMFieldNo(FD);
895 assert(AST_RL.getFieldOffset(i) == SL->getElementOffsetInBits(FieldNo) &&
896 "Invalid field offset!");
Daniel Dunbar488f55c2010-04-22 02:35:46 +0000897 continue;
898 }
899
900 // Ignore unnamed bit-fields.
901 if (!FD->getDeclName())
902 continue;
903
904 const CGBitFieldInfo &Info = RL->getBitFieldInfo(FD);
905 for (unsigned i = 0, e = Info.getNumComponents(); i != e; ++i) {
906 const CGBitFieldInfo::AccessInfo &AI = Info.getComponent(i);
907
908 // Verify that every component access is within the structure.
909 uint64_t FieldOffset = SL->getElementOffsetInBits(AI.FieldIndex);
910 uint64_t AccessBitOffset = FieldOffset + AI.FieldByteOffset * 8;
911 assert(AccessBitOffset + AI.AccessWidth <= TypeSizeInBits &&
912 "Invalid bit-field access (out of range)!");
Daniel Dunbar2ba67442010-04-21 19:10:49 +0000913 }
914 }
915#endif
Daniel Dunbar2ea51832010-04-19 20:44:47 +0000916
Daniel Dunbar034299e2010-03-31 01:09:11 +0000917 return RL;
Anders Carlsson307846f2009-07-23 03:17:50 +0000918}
Daniel Dunbarb97bff92010-04-12 18:14:18 +0000919
920void CGRecordLayout::print(llvm::raw_ostream &OS) const {
921 OS << "<CGRecordLayout\n";
John McCall0217dfc22011-02-15 06:40:56 +0000922 OS << " LLVMType:" << *CompleteObjectType << "\n";
923 if (BaseSubobjectType)
924 OS << " NonVirtualBaseLLVMType:" << *BaseSubobjectType << "\n";
John McCall614dbdc2010-08-22 21:01:12 +0000925 OS << " IsZeroInitializable:" << IsZeroInitializable << "\n";
Daniel Dunbarb97bff92010-04-12 18:14:18 +0000926 OS << " BitFields:[\n";
Daniel Dunbarb6f4b052010-04-22 02:35:36 +0000927
928 // Print bit-field infos in declaration order.
929 std::vector<std::pair<unsigned, const CGBitFieldInfo*> > BFIs;
Daniel Dunbarb97bff92010-04-12 18:14:18 +0000930 for (llvm::DenseMap<const FieldDecl*, CGBitFieldInfo>::const_iterator
931 it = BitFields.begin(), ie = BitFields.end();
932 it != ie; ++it) {
Daniel Dunbarb6f4b052010-04-22 02:35:36 +0000933 const RecordDecl *RD = it->first->getParent();
934 unsigned Index = 0;
935 for (RecordDecl::field_iterator
936 it2 = RD->field_begin(); *it2 != it->first; ++it2)
937 ++Index;
938 BFIs.push_back(std::make_pair(Index, &it->second));
939 }
940 llvm::array_pod_sort(BFIs.begin(), BFIs.end());
941 for (unsigned i = 0, e = BFIs.size(); i != e; ++i) {
Daniel Dunbarb935b932010-04-13 20:58:55 +0000942 OS.indent(4);
Daniel Dunbarb6f4b052010-04-22 02:35:36 +0000943 BFIs[i].second->print(OS);
Daniel Dunbarb97bff92010-04-12 18:14:18 +0000944 OS << "\n";
945 }
Daniel Dunbarb6f4b052010-04-22 02:35:36 +0000946
Daniel Dunbarb97bff92010-04-12 18:14:18 +0000947 OS << "]>\n";
948}
949
950void CGRecordLayout::dump() const {
951 print(llvm::errs());
952}
953
954void CGBitFieldInfo::print(llvm::raw_ostream &OS) const {
955 OS << "<CGBitFieldInfo";
Daniel Dunbarb97bff92010-04-12 18:14:18 +0000956 OS << " Size:" << Size;
Daniel Dunbarb935b932010-04-13 20:58:55 +0000957 OS << " IsSigned:" << IsSigned << "\n";
958
959 OS.indent(4 + strlen("<CGBitFieldInfo"));
960 OS << " NumComponents:" << getNumComponents();
961 OS << " Components: [";
962 if (getNumComponents()) {
963 OS << "\n";
964 for (unsigned i = 0, e = getNumComponents(); i != e; ++i) {
965 const AccessInfo &AI = getComponent(i);
966 OS.indent(8);
967 OS << "<AccessInfo"
968 << " FieldIndex:" << AI.FieldIndex
969 << " FieldByteOffset:" << AI.FieldByteOffset
970 << " FieldBitStart:" << AI.FieldBitStart
971 << " AccessWidth:" << AI.AccessWidth << "\n";
972 OS.indent(8 + strlen("<AccessInfo"));
973 OS << " AccessAlignment:" << AI.AccessAlignment
974 << " TargetBitOffset:" << AI.TargetBitOffset
975 << " TargetBitWidth:" << AI.TargetBitWidth
976 << ">\n";
977 }
978 OS.indent(4);
979 }
980 OS << "]>";
Daniel Dunbarb97bff92010-04-12 18:14:18 +0000981}
982
983void CGBitFieldInfo::dump() const {
984 print(llvm::errs());
985}