xref: /openbsd-src/gnu/llvm/clang/lib/CodeGen/CGRecordLayoutBuilder.cpp (revision 12c855180aad702bbcca06e0398d774beeafb155)
1e5dd7070Spatrick //===--- CGRecordLayoutBuilder.cpp - CGRecordLayout builder  ----*- C++ -*-===//
2e5dd7070Spatrick //
3e5dd7070Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4e5dd7070Spatrick // See https://llvm.org/LICENSE.txt for license information.
5e5dd7070Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e5dd7070Spatrick //
7e5dd7070Spatrick //===----------------------------------------------------------------------===//
8e5dd7070Spatrick //
9e5dd7070Spatrick // Builder implementation for CGRecordLayout objects.
10e5dd7070Spatrick //
11e5dd7070Spatrick //===----------------------------------------------------------------------===//
12e5dd7070Spatrick 
13e5dd7070Spatrick #include "CGRecordLayout.h"
14e5dd7070Spatrick #include "CGCXXABI.h"
15e5dd7070Spatrick #include "CodeGenTypes.h"
16e5dd7070Spatrick #include "clang/AST/ASTContext.h"
17e5dd7070Spatrick #include "clang/AST/Attr.h"
18e5dd7070Spatrick #include "clang/AST/CXXInheritance.h"
19e5dd7070Spatrick #include "clang/AST/DeclCXX.h"
20e5dd7070Spatrick #include "clang/AST/Expr.h"
21e5dd7070Spatrick #include "clang/AST/RecordLayout.h"
22e5dd7070Spatrick #include "clang/Basic/CodeGenOptions.h"
23e5dd7070Spatrick #include "llvm/IR/DataLayout.h"
24e5dd7070Spatrick #include "llvm/IR/DerivedTypes.h"
25e5dd7070Spatrick #include "llvm/IR/Type.h"
26e5dd7070Spatrick #include "llvm/Support/Debug.h"
27e5dd7070Spatrick #include "llvm/Support/MathExtras.h"
28e5dd7070Spatrick #include "llvm/Support/raw_ostream.h"
29e5dd7070Spatrick using namespace clang;
30e5dd7070Spatrick using namespace CodeGen;
31e5dd7070Spatrick 
32e5dd7070Spatrick namespace {
33e5dd7070Spatrick /// The CGRecordLowering is responsible for lowering an ASTRecordLayout to an
34e5dd7070Spatrick /// llvm::Type.  Some of the lowering is straightforward, some is not.  Here we
35e5dd7070Spatrick /// detail some of the complexities and weirdnesses here.
36e5dd7070Spatrick /// * LLVM does not have unions - Unions can, in theory be represented by any
37e5dd7070Spatrick ///   llvm::Type with correct size.  We choose a field via a specific heuristic
38e5dd7070Spatrick ///   and add padding if necessary.
39e5dd7070Spatrick /// * LLVM does not have bitfields - Bitfields are collected into contiguous
40e5dd7070Spatrick ///   runs and allocated as a single storage type for the run.  ASTRecordLayout
41e5dd7070Spatrick ///   contains enough information to determine where the runs break.  Microsoft
42e5dd7070Spatrick ///   and Itanium follow different rules and use different codepaths.
43e5dd7070Spatrick /// * It is desired that, when possible, bitfields use the appropriate iN type
44e5dd7070Spatrick ///   when lowered to llvm types.  For example unsigned x : 24 gets lowered to
45e5dd7070Spatrick ///   i24.  This isn't always possible because i24 has storage size of 32 bit
46e5dd7070Spatrick ///   and if it is possible to use that extra byte of padding we must use
47e5dd7070Spatrick ///   [i8 x 3] instead of i24.  The function clipTailPadding does this.
48e5dd7070Spatrick ///   C++ examples that require clipping:
49e5dd7070Spatrick ///   struct { int a : 24; char b; }; // a must be clipped, b goes at offset 3
50e5dd7070Spatrick ///   struct A { int a : 24; }; // a must be clipped because a struct like B
51e5dd7070Spatrick //    could exist: struct B : A { char b; }; // b goes at offset 3
52e5dd7070Spatrick /// * Clang ignores 0 sized bitfields and 0 sized bases but *not* zero sized
53e5dd7070Spatrick ///   fields.  The existing asserts suggest that LLVM assumes that *every* field
54e5dd7070Spatrick ///   has an underlying storage type.  Therefore empty structures containing
55e5dd7070Spatrick ///   zero sized subobjects such as empty records or zero sized arrays still get
56e5dd7070Spatrick ///   a zero sized (empty struct) storage type.
57e5dd7070Spatrick /// * Clang reads the complete type rather than the base type when generating
58e5dd7070Spatrick ///   code to access fields.  Bitfields in tail position with tail padding may
59e5dd7070Spatrick ///   be clipped in the base class but not the complete class (we may discover
60e5dd7070Spatrick ///   that the tail padding is not used in the complete class.) However,
61e5dd7070Spatrick ///   because LLVM reads from the complete type it can generate incorrect code
62e5dd7070Spatrick ///   if we do not clip the tail padding off of the bitfield in the complete
63e5dd7070Spatrick ///   layout.  This introduces a somewhat awkward extra unnecessary clip stage.
64e5dd7070Spatrick ///   The location of the clip is stored internally as a sentinel of type
65e5dd7070Spatrick ///   SCISSOR.  If LLVM were updated to read base types (which it probably
66e5dd7070Spatrick ///   should because locations of things such as VBases are bogus in the llvm
67e5dd7070Spatrick ///   type anyway) then we could eliminate the SCISSOR.
68e5dd7070Spatrick /// * Itanium allows nearly empty primary virtual bases.  These bases don't get
69e5dd7070Spatrick ///   get their own storage because they're laid out as part of another base
70e5dd7070Spatrick ///   or at the beginning of the structure.  Determining if a VBase actually
71e5dd7070Spatrick ///   gets storage awkwardly involves a walk of all bases.
72e5dd7070Spatrick /// * VFPtrs and VBPtrs do *not* make a record NotZeroInitializable.
73e5dd7070Spatrick struct CGRecordLowering {
74e5dd7070Spatrick   // MemberInfo is a helper structure that contains information about a record
75e5dd7070Spatrick   // member.  In additional to the standard member types, there exists a
76e5dd7070Spatrick   // sentinel member type that ensures correct rounding.
77e5dd7070Spatrick   struct MemberInfo {
78e5dd7070Spatrick     CharUnits Offset;
79e5dd7070Spatrick     enum InfoKind { VFPtr, VBPtr, Field, Base, VBase, Scissor } Kind;
80e5dd7070Spatrick     llvm::Type *Data;
81e5dd7070Spatrick     union {
82e5dd7070Spatrick       const FieldDecl *FD;
83e5dd7070Spatrick       const CXXRecordDecl *RD;
84e5dd7070Spatrick     };
MemberInfo__anonb481c4a30111::CGRecordLowering::MemberInfo85e5dd7070Spatrick     MemberInfo(CharUnits Offset, InfoKind Kind, llvm::Type *Data,
86e5dd7070Spatrick                const FieldDecl *FD = nullptr)
87e5dd7070Spatrick       : Offset(Offset), Kind(Kind), Data(Data), FD(FD) {}
MemberInfo__anonb481c4a30111::CGRecordLowering::MemberInfo88e5dd7070Spatrick     MemberInfo(CharUnits Offset, InfoKind Kind, llvm::Type *Data,
89e5dd7070Spatrick                const CXXRecordDecl *RD)
90e5dd7070Spatrick       : Offset(Offset), Kind(Kind), Data(Data), RD(RD) {}
91e5dd7070Spatrick     // MemberInfos are sorted so we define a < operator.
operator <__anonb481c4a30111::CGRecordLowering::MemberInfo92e5dd7070Spatrick     bool operator <(const MemberInfo& a) const { return Offset < a.Offset; }
93e5dd7070Spatrick   };
94e5dd7070Spatrick   // The constructor.
95e5dd7070Spatrick   CGRecordLowering(CodeGenTypes &Types, const RecordDecl *D, bool Packed);
96e5dd7070Spatrick   // Short helper routines.
97e5dd7070Spatrick   /// Constructs a MemberInfo instance from an offset and llvm::Type *.
StorageInfo__anonb481c4a30111::CGRecordLowering98e5dd7070Spatrick   MemberInfo StorageInfo(CharUnits Offset, llvm::Type *Data) {
99e5dd7070Spatrick     return MemberInfo(Offset, MemberInfo::Field, Data);
100e5dd7070Spatrick   }
101e5dd7070Spatrick 
102e5dd7070Spatrick   /// The Microsoft bitfield layout rule allocates discrete storage
103e5dd7070Spatrick   /// units of the field's formal type and only combines adjacent
104e5dd7070Spatrick   /// fields of the same formal type.  We want to emit a layout with
105e5dd7070Spatrick   /// these discrete storage units instead of combining them into a
106e5dd7070Spatrick   /// continuous run.
isDiscreteBitFieldABI__anonb481c4a30111::CGRecordLowering107e5dd7070Spatrick   bool isDiscreteBitFieldABI() {
108e5dd7070Spatrick     return Context.getTargetInfo().getCXXABI().isMicrosoft() ||
109e5dd7070Spatrick            D->isMsStruct(Context);
110e5dd7070Spatrick   }
111e5dd7070Spatrick 
112a9ac8606Spatrick   /// Helper function to check if we are targeting AAPCS.
isAAPCS__anonb481c4a30111::CGRecordLowering113a9ac8606Spatrick   bool isAAPCS() const {
114a9ac8606Spatrick     return Context.getTargetInfo().getABI().startswith("aapcs");
115a9ac8606Spatrick   }
116a9ac8606Spatrick 
117a9ac8606Spatrick   /// Helper function to check if the target machine is BigEndian.
isBE__anonb481c4a30111::CGRecordLowering118a9ac8606Spatrick   bool isBE() const { return Context.getTargetInfo().isBigEndian(); }
119a9ac8606Spatrick 
120e5dd7070Spatrick   /// The Itanium base layout rule allows virtual bases to overlap
121e5dd7070Spatrick   /// other bases, which complicates layout in specific ways.
122e5dd7070Spatrick   ///
123e5dd7070Spatrick   /// Note specifically that the ms_struct attribute doesn't change this.
isOverlappingVBaseABI__anonb481c4a30111::CGRecordLowering124e5dd7070Spatrick   bool isOverlappingVBaseABI() {
125e5dd7070Spatrick     return !Context.getTargetInfo().getCXXABI().isMicrosoft();
126e5dd7070Spatrick   }
127e5dd7070Spatrick 
128e5dd7070Spatrick   /// Wraps llvm::Type::getIntNTy with some implicit arguments.
getIntNType__anonb481c4a30111::CGRecordLowering129e5dd7070Spatrick   llvm::Type *getIntNType(uint64_t NumBits) {
130a9ac8606Spatrick     unsigned AlignedBits = llvm::alignTo(NumBits, Context.getCharWidth());
131a9ac8606Spatrick     return llvm::Type::getIntNTy(Types.getLLVMContext(), AlignedBits);
132e5dd7070Spatrick   }
133a9ac8606Spatrick   /// Get the LLVM type sized as one character unit.
getCharType__anonb481c4a30111::CGRecordLowering134a9ac8606Spatrick   llvm::Type *getCharType() {
135a9ac8606Spatrick     return llvm::Type::getIntNTy(Types.getLLVMContext(),
136a9ac8606Spatrick                                  Context.getCharWidth());
137a9ac8606Spatrick   }
138a9ac8606Spatrick   /// Gets an llvm type of size NumChars and alignment 1.
getByteArrayType__anonb481c4a30111::CGRecordLowering139a9ac8606Spatrick   llvm::Type *getByteArrayType(CharUnits NumChars) {
140a9ac8606Spatrick     assert(!NumChars.isZero() && "Empty byte arrays aren't allowed.");
141a9ac8606Spatrick     llvm::Type *Type = getCharType();
142a9ac8606Spatrick     return NumChars == CharUnits::One() ? Type :
143a9ac8606Spatrick         (llvm::Type *)llvm::ArrayType::get(Type, NumChars.getQuantity());
144e5dd7070Spatrick   }
145e5dd7070Spatrick   /// Gets the storage type for a field decl and handles storage
146e5dd7070Spatrick   /// for itanium bitfields that are smaller than their declared type.
getStorageType__anonb481c4a30111::CGRecordLowering147e5dd7070Spatrick   llvm::Type *getStorageType(const FieldDecl *FD) {
148e5dd7070Spatrick     llvm::Type *Type = Types.ConvertTypeForMem(FD->getType());
149e5dd7070Spatrick     if (!FD->isBitField()) return Type;
150e5dd7070Spatrick     if (isDiscreteBitFieldABI()) return Type;
151e5dd7070Spatrick     return getIntNType(std::min(FD->getBitWidthValue(Context),
152e5dd7070Spatrick                              (unsigned)Context.toBits(getSize(Type))));
153e5dd7070Spatrick   }
154e5dd7070Spatrick   /// Gets the llvm Basesubobject type from a CXXRecordDecl.
getStorageType__anonb481c4a30111::CGRecordLowering155e5dd7070Spatrick   llvm::Type *getStorageType(const CXXRecordDecl *RD) {
156e5dd7070Spatrick     return Types.getCGRecordLayout(RD).getBaseSubobjectLLVMType();
157e5dd7070Spatrick   }
bitsToCharUnits__anonb481c4a30111::CGRecordLowering158e5dd7070Spatrick   CharUnits bitsToCharUnits(uint64_t BitOffset) {
159e5dd7070Spatrick     return Context.toCharUnitsFromBits(BitOffset);
160e5dd7070Spatrick   }
getSize__anonb481c4a30111::CGRecordLowering161e5dd7070Spatrick   CharUnits getSize(llvm::Type *Type) {
162e5dd7070Spatrick     return CharUnits::fromQuantity(DataLayout.getTypeAllocSize(Type));
163e5dd7070Spatrick   }
getAlignment__anonb481c4a30111::CGRecordLowering164e5dd7070Spatrick   CharUnits getAlignment(llvm::Type *Type) {
165*12c85518Srobert     return CharUnits::fromQuantity(DataLayout.getABITypeAlign(Type));
166e5dd7070Spatrick   }
isZeroInitializable__anonb481c4a30111::CGRecordLowering167e5dd7070Spatrick   bool isZeroInitializable(const FieldDecl *FD) {
168e5dd7070Spatrick     return Types.isZeroInitializable(FD->getType());
169e5dd7070Spatrick   }
isZeroInitializable__anonb481c4a30111::CGRecordLowering170e5dd7070Spatrick   bool isZeroInitializable(const RecordDecl *RD) {
171e5dd7070Spatrick     return Types.isZeroInitializable(RD);
172e5dd7070Spatrick   }
appendPaddingBytes__anonb481c4a30111::CGRecordLowering173e5dd7070Spatrick   void appendPaddingBytes(CharUnits Size) {
174e5dd7070Spatrick     if (!Size.isZero())
175e5dd7070Spatrick       FieldTypes.push_back(getByteArrayType(Size));
176e5dd7070Spatrick   }
getFieldBitOffset__anonb481c4a30111::CGRecordLowering177e5dd7070Spatrick   uint64_t getFieldBitOffset(const FieldDecl *FD) {
178e5dd7070Spatrick     return Layout.getFieldOffset(FD->getFieldIndex());
179e5dd7070Spatrick   }
180e5dd7070Spatrick   // Layout routines.
181e5dd7070Spatrick   void setBitFieldInfo(const FieldDecl *FD, CharUnits StartOffset,
182e5dd7070Spatrick                        llvm::Type *StorageType);
183e5dd7070Spatrick   /// Lowers an ASTRecordLayout to a llvm type.
184e5dd7070Spatrick   void lower(bool NonVirtualBaseType);
185e5dd7070Spatrick   void lowerUnion();
186e5dd7070Spatrick   void accumulateFields();
187e5dd7070Spatrick   void accumulateBitFields(RecordDecl::field_iterator Field,
188e5dd7070Spatrick                            RecordDecl::field_iterator FieldEnd);
189a9ac8606Spatrick   void computeVolatileBitfields();
190e5dd7070Spatrick   void accumulateBases();
191e5dd7070Spatrick   void accumulateVPtrs();
192e5dd7070Spatrick   void accumulateVBases();
193e5dd7070Spatrick   /// Recursively searches all of the bases to find out if a vbase is
194e5dd7070Spatrick   /// not the primary vbase of some base class.
195e5dd7070Spatrick   bool hasOwnStorage(const CXXRecordDecl *Decl, const CXXRecordDecl *Query);
196e5dd7070Spatrick   void calculateZeroInit();
197e5dd7070Spatrick   /// Lowers bitfield storage types to I8 arrays for bitfields with tail
198e5dd7070Spatrick   /// padding that is or can potentially be used.
199e5dd7070Spatrick   void clipTailPadding();
200e5dd7070Spatrick   /// Determines if we need a packed llvm struct.
201e5dd7070Spatrick   void determinePacked(bool NVBaseType);
202e5dd7070Spatrick   /// Inserts padding everywhere it's needed.
203e5dd7070Spatrick   void insertPadding();
204e5dd7070Spatrick   /// Fills out the structures that are ultimately consumed.
205e5dd7070Spatrick   void fillOutputFields();
206e5dd7070Spatrick   // Input memoization fields.
207e5dd7070Spatrick   CodeGenTypes &Types;
208e5dd7070Spatrick   const ASTContext &Context;
209e5dd7070Spatrick   const RecordDecl *D;
210e5dd7070Spatrick   const CXXRecordDecl *RD;
211e5dd7070Spatrick   const ASTRecordLayout &Layout;
212e5dd7070Spatrick   const llvm::DataLayout &DataLayout;
213e5dd7070Spatrick   // Helpful intermediate data-structures.
214e5dd7070Spatrick   std::vector<MemberInfo> Members;
215e5dd7070Spatrick   // Output fields, consumed by CodeGenTypes::ComputeRecordLayout.
216e5dd7070Spatrick   SmallVector<llvm::Type *, 16> FieldTypes;
217e5dd7070Spatrick   llvm::DenseMap<const FieldDecl *, unsigned> Fields;
218e5dd7070Spatrick   llvm::DenseMap<const FieldDecl *, CGBitFieldInfo> BitFields;
219e5dd7070Spatrick   llvm::DenseMap<const CXXRecordDecl *, unsigned> NonVirtualBases;
220e5dd7070Spatrick   llvm::DenseMap<const CXXRecordDecl *, unsigned> VirtualBases;
221e5dd7070Spatrick   bool IsZeroInitializable : 1;
222e5dd7070Spatrick   bool IsZeroInitializableAsBase : 1;
223e5dd7070Spatrick   bool Packed : 1;
224e5dd7070Spatrick private:
225e5dd7070Spatrick   CGRecordLowering(const CGRecordLowering &) = delete;
226e5dd7070Spatrick   void operator =(const CGRecordLowering &) = delete;
227e5dd7070Spatrick };
228e5dd7070Spatrick } // namespace {
229e5dd7070Spatrick 
CGRecordLowering(CodeGenTypes & Types,const RecordDecl * D,bool Packed)230e5dd7070Spatrick CGRecordLowering::CGRecordLowering(CodeGenTypes &Types, const RecordDecl *D,
231e5dd7070Spatrick                                    bool Packed)
232e5dd7070Spatrick     : Types(Types), Context(Types.getContext()), D(D),
233e5dd7070Spatrick       RD(dyn_cast<CXXRecordDecl>(D)),
234e5dd7070Spatrick       Layout(Types.getContext().getASTRecordLayout(D)),
235e5dd7070Spatrick       DataLayout(Types.getDataLayout()), IsZeroInitializable(true),
236e5dd7070Spatrick       IsZeroInitializableAsBase(true), Packed(Packed) {}
237e5dd7070Spatrick 
setBitFieldInfo(const FieldDecl * FD,CharUnits StartOffset,llvm::Type * StorageType)238e5dd7070Spatrick void CGRecordLowering::setBitFieldInfo(
239e5dd7070Spatrick     const FieldDecl *FD, CharUnits StartOffset, llvm::Type *StorageType) {
240e5dd7070Spatrick   CGBitFieldInfo &Info = BitFields[FD->getCanonicalDecl()];
241e5dd7070Spatrick   Info.IsSigned = FD->getType()->isSignedIntegerOrEnumerationType();
242e5dd7070Spatrick   Info.Offset = (unsigned)(getFieldBitOffset(FD) - Context.toBits(StartOffset));
243e5dd7070Spatrick   Info.Size = FD->getBitWidthValue(Context);
244e5dd7070Spatrick   Info.StorageSize = (unsigned)DataLayout.getTypeAllocSizeInBits(StorageType);
245e5dd7070Spatrick   Info.StorageOffset = StartOffset;
246e5dd7070Spatrick   if (Info.Size > Info.StorageSize)
247e5dd7070Spatrick     Info.Size = Info.StorageSize;
248e5dd7070Spatrick   // Reverse the bit offsets for big endian machines. Because we represent
249e5dd7070Spatrick   // a bitfield as a single large integer load, we can imagine the bits
250e5dd7070Spatrick   // counting from the most-significant-bit instead of the
251e5dd7070Spatrick   // least-significant-bit.
252e5dd7070Spatrick   if (DataLayout.isBigEndian())
253e5dd7070Spatrick     Info.Offset = Info.StorageSize - (Info.Offset + Info.Size);
254a9ac8606Spatrick 
255a9ac8606Spatrick   Info.VolatileStorageSize = 0;
256a9ac8606Spatrick   Info.VolatileOffset = 0;
257a9ac8606Spatrick   Info.VolatileStorageOffset = CharUnits::Zero();
258e5dd7070Spatrick }
259e5dd7070Spatrick 
lower(bool NVBaseType)260e5dd7070Spatrick void CGRecordLowering::lower(bool NVBaseType) {
261e5dd7070Spatrick   // The lowering process implemented in this function takes a variety of
262e5dd7070Spatrick   // carefully ordered phases.
263e5dd7070Spatrick   // 1) Store all members (fields and bases) in a list and sort them by offset.
264e5dd7070Spatrick   // 2) Add a 1-byte capstone member at the Size of the structure.
265e5dd7070Spatrick   // 3) Clip bitfield storages members if their tail padding is or might be
266e5dd7070Spatrick   //    used by another field or base.  The clipping process uses the capstone
267e5dd7070Spatrick   //    by treating it as another object that occurs after the record.
268e5dd7070Spatrick   // 4) Determine if the llvm-struct requires packing.  It's important that this
269e5dd7070Spatrick   //    phase occur after clipping, because clipping changes the llvm type.
270e5dd7070Spatrick   //    This phase reads the offset of the capstone when determining packedness
271e5dd7070Spatrick   //    and updates the alignment of the capstone to be equal of the alignment
272e5dd7070Spatrick   //    of the record after doing so.
273e5dd7070Spatrick   // 5) Insert padding everywhere it is needed.  This phase requires 'Packed' to
274e5dd7070Spatrick   //    have been computed and needs to know the alignment of the record in
275e5dd7070Spatrick   //    order to understand if explicit tail padding is needed.
276e5dd7070Spatrick   // 6) Remove the capstone, we don't need it anymore.
277e5dd7070Spatrick   // 7) Determine if this record can be zero-initialized.  This phase could have
278e5dd7070Spatrick   //    been placed anywhere after phase 1.
279e5dd7070Spatrick   // 8) Format the complete list of members in a way that can be consumed by
280e5dd7070Spatrick   //    CodeGenTypes::ComputeRecordLayout.
281e5dd7070Spatrick   CharUnits Size = NVBaseType ? Layout.getNonVirtualSize() : Layout.getSize();
282a9ac8606Spatrick   if (D->isUnion()) {
283a9ac8606Spatrick     lowerUnion();
284a9ac8606Spatrick     computeVolatileBitfields();
285a9ac8606Spatrick     return;
286a9ac8606Spatrick   }
287e5dd7070Spatrick   accumulateFields();
288e5dd7070Spatrick   // RD implies C++.
289e5dd7070Spatrick   if (RD) {
290e5dd7070Spatrick     accumulateVPtrs();
291e5dd7070Spatrick     accumulateBases();
292a9ac8606Spatrick     if (Members.empty()) {
293a9ac8606Spatrick       appendPaddingBytes(Size);
294a9ac8606Spatrick       computeVolatileBitfields();
295a9ac8606Spatrick       return;
296a9ac8606Spatrick     }
297e5dd7070Spatrick     if (!NVBaseType)
298e5dd7070Spatrick       accumulateVBases();
299e5dd7070Spatrick   }
300e5dd7070Spatrick   llvm::stable_sort(Members);
301e5dd7070Spatrick   Members.push_back(StorageInfo(Size, getIntNType(8)));
302e5dd7070Spatrick   clipTailPadding();
303e5dd7070Spatrick   determinePacked(NVBaseType);
304e5dd7070Spatrick   insertPadding();
305e5dd7070Spatrick   Members.pop_back();
306e5dd7070Spatrick   calculateZeroInit();
307e5dd7070Spatrick   fillOutputFields();
308a9ac8606Spatrick   computeVolatileBitfields();
309e5dd7070Spatrick }
310e5dd7070Spatrick 
lowerUnion()311e5dd7070Spatrick void CGRecordLowering::lowerUnion() {
312e5dd7070Spatrick   CharUnits LayoutSize = Layout.getSize();
313e5dd7070Spatrick   llvm::Type *StorageType = nullptr;
314e5dd7070Spatrick   bool SeenNamedMember = false;
315e5dd7070Spatrick   // Iterate through the fields setting bitFieldInfo and the Fields array. Also
316e5dd7070Spatrick   // locate the "most appropriate" storage type.  The heuristic for finding the
317e5dd7070Spatrick   // storage type isn't necessary, the first (non-0-length-bitfield) field's
318e5dd7070Spatrick   // type would work fine and be simpler but would be different than what we've
319e5dd7070Spatrick   // been doing and cause lit tests to change.
320e5dd7070Spatrick   for (const auto *Field : D->fields()) {
321e5dd7070Spatrick     if (Field->isBitField()) {
322e5dd7070Spatrick       if (Field->isZeroLengthBitField(Context))
323e5dd7070Spatrick         continue;
324e5dd7070Spatrick       llvm::Type *FieldType = getStorageType(Field);
325e5dd7070Spatrick       if (LayoutSize < getSize(FieldType))
326e5dd7070Spatrick         FieldType = getByteArrayType(LayoutSize);
327e5dd7070Spatrick       setBitFieldInfo(Field, CharUnits::Zero(), FieldType);
328e5dd7070Spatrick     }
329e5dd7070Spatrick     Fields[Field->getCanonicalDecl()] = 0;
330e5dd7070Spatrick     llvm::Type *FieldType = getStorageType(Field);
331e5dd7070Spatrick     // Compute zero-initializable status.
332e5dd7070Spatrick     // This union might not be zero initialized: it may contain a pointer to
333e5dd7070Spatrick     // data member which might have some exotic initialization sequence.
334e5dd7070Spatrick     // If this is the case, then we aught not to try and come up with a "better"
335e5dd7070Spatrick     // type, it might not be very easy to come up with a Constant which
336e5dd7070Spatrick     // correctly initializes it.
337e5dd7070Spatrick     if (!SeenNamedMember) {
338e5dd7070Spatrick       SeenNamedMember = Field->getIdentifier();
339e5dd7070Spatrick       if (!SeenNamedMember)
340e5dd7070Spatrick         if (const auto *FieldRD = Field->getType()->getAsRecordDecl())
341e5dd7070Spatrick           SeenNamedMember = FieldRD->findFirstNamedDataMember();
342e5dd7070Spatrick       if (SeenNamedMember && !isZeroInitializable(Field)) {
343e5dd7070Spatrick         IsZeroInitializable = IsZeroInitializableAsBase = false;
344e5dd7070Spatrick         StorageType = FieldType;
345e5dd7070Spatrick       }
346e5dd7070Spatrick     }
347e5dd7070Spatrick     // Because our union isn't zero initializable, we won't be getting a better
348e5dd7070Spatrick     // storage type.
349e5dd7070Spatrick     if (!IsZeroInitializable)
350e5dd7070Spatrick       continue;
351e5dd7070Spatrick     // Conditionally update our storage type if we've got a new "better" one.
352e5dd7070Spatrick     if (!StorageType ||
353e5dd7070Spatrick         getAlignment(FieldType) >  getAlignment(StorageType) ||
354e5dd7070Spatrick         (getAlignment(FieldType) == getAlignment(StorageType) &&
355e5dd7070Spatrick         getSize(FieldType) > getSize(StorageType)))
356e5dd7070Spatrick       StorageType = FieldType;
357e5dd7070Spatrick   }
358e5dd7070Spatrick   // If we have no storage type just pad to the appropriate size and return.
359e5dd7070Spatrick   if (!StorageType)
360e5dd7070Spatrick     return appendPaddingBytes(LayoutSize);
361e5dd7070Spatrick   // If our storage size was bigger than our required size (can happen in the
362e5dd7070Spatrick   // case of packed bitfields on Itanium) then just use an I8 array.
363e5dd7070Spatrick   if (LayoutSize < getSize(StorageType))
364e5dd7070Spatrick     StorageType = getByteArrayType(LayoutSize);
365e5dd7070Spatrick   FieldTypes.push_back(StorageType);
366e5dd7070Spatrick   appendPaddingBytes(LayoutSize - getSize(StorageType));
367e5dd7070Spatrick   // Set packed if we need it.
368e5dd7070Spatrick   if (LayoutSize % getAlignment(StorageType))
369e5dd7070Spatrick     Packed = true;
370e5dd7070Spatrick }
371e5dd7070Spatrick 
accumulateFields()372e5dd7070Spatrick void CGRecordLowering::accumulateFields() {
373e5dd7070Spatrick   for (RecordDecl::field_iterator Field = D->field_begin(),
374e5dd7070Spatrick                                   FieldEnd = D->field_end();
375e5dd7070Spatrick     Field != FieldEnd;) {
376e5dd7070Spatrick     if (Field->isBitField()) {
377e5dd7070Spatrick       RecordDecl::field_iterator Start = Field;
378e5dd7070Spatrick       // Iterate to gather the list of bitfields.
379e5dd7070Spatrick       for (++Field; Field != FieldEnd && Field->isBitField(); ++Field);
380e5dd7070Spatrick       accumulateBitFields(Start, Field);
381e5dd7070Spatrick     } else if (!Field->isZeroSize(Context)) {
382e5dd7070Spatrick       Members.push_back(MemberInfo(
383e5dd7070Spatrick           bitsToCharUnits(getFieldBitOffset(*Field)), MemberInfo::Field,
384e5dd7070Spatrick           getStorageType(*Field), *Field));
385e5dd7070Spatrick       ++Field;
386e5dd7070Spatrick     } else {
387e5dd7070Spatrick       ++Field;
388e5dd7070Spatrick     }
389e5dd7070Spatrick   }
390e5dd7070Spatrick }
391e5dd7070Spatrick 
392e5dd7070Spatrick void
accumulateBitFields(RecordDecl::field_iterator Field,RecordDecl::field_iterator FieldEnd)393e5dd7070Spatrick CGRecordLowering::accumulateBitFields(RecordDecl::field_iterator Field,
394e5dd7070Spatrick                                       RecordDecl::field_iterator FieldEnd) {
395e5dd7070Spatrick   // Run stores the first element of the current run of bitfields.  FieldEnd is
396e5dd7070Spatrick   // used as a special value to note that we don't have a current run.  A
397e5dd7070Spatrick   // bitfield run is a contiguous collection of bitfields that can be stored in
398e5dd7070Spatrick   // the same storage block.  Zero-sized bitfields and bitfields that would
399e5dd7070Spatrick   // cross an alignment boundary break a run and start a new one.
400e5dd7070Spatrick   RecordDecl::field_iterator Run = FieldEnd;
401e5dd7070Spatrick   // Tail is the offset of the first bit off the end of the current run.  It's
402e5dd7070Spatrick   // used to determine if the ASTRecordLayout is treating these two bitfields as
403e5dd7070Spatrick   // contiguous.  StartBitOffset is offset of the beginning of the Run.
404e5dd7070Spatrick   uint64_t StartBitOffset, Tail = 0;
405e5dd7070Spatrick   if (isDiscreteBitFieldABI()) {
406e5dd7070Spatrick     for (; Field != FieldEnd; ++Field) {
407e5dd7070Spatrick       uint64_t BitOffset = getFieldBitOffset(*Field);
408e5dd7070Spatrick       // Zero-width bitfields end runs.
409e5dd7070Spatrick       if (Field->isZeroLengthBitField(Context)) {
410e5dd7070Spatrick         Run = FieldEnd;
411e5dd7070Spatrick         continue;
412e5dd7070Spatrick       }
413ec727ea7Spatrick       llvm::Type *Type =
414*12c85518Srobert           Types.ConvertTypeForMem(Field->getType(), /*ForBitField=*/true);
415e5dd7070Spatrick       // If we don't have a run yet, or don't live within the previous run's
416e5dd7070Spatrick       // allocated storage then we allocate some storage and start a new run.
417e5dd7070Spatrick       if (Run == FieldEnd || BitOffset >= Tail) {
418e5dd7070Spatrick         Run = Field;
419e5dd7070Spatrick         StartBitOffset = BitOffset;
420e5dd7070Spatrick         Tail = StartBitOffset + DataLayout.getTypeAllocSizeInBits(Type);
421e5dd7070Spatrick         // Add the storage member to the record.  This must be added to the
422e5dd7070Spatrick         // record before the bitfield members so that it gets laid out before
423e5dd7070Spatrick         // the bitfields it contains get laid out.
424e5dd7070Spatrick         Members.push_back(StorageInfo(bitsToCharUnits(StartBitOffset), Type));
425e5dd7070Spatrick       }
426e5dd7070Spatrick       // Bitfields get the offset of their storage but come afterward and remain
427e5dd7070Spatrick       // there after a stable sort.
428e5dd7070Spatrick       Members.push_back(MemberInfo(bitsToCharUnits(StartBitOffset),
429e5dd7070Spatrick                                    MemberInfo::Field, nullptr, *Field));
430e5dd7070Spatrick     }
431e5dd7070Spatrick     return;
432e5dd7070Spatrick   }
433e5dd7070Spatrick 
434ec727ea7Spatrick   // Check if OffsetInRecord (the size in bits of the current run) is better
435ec727ea7Spatrick   // as a single field run. When OffsetInRecord has legal integer width, and
436ec727ea7Spatrick   // its bitfield offset is naturally aligned, it is better to make the
437ec727ea7Spatrick   // bitfield a separate storage component so as it can be accessed directly
438ec727ea7Spatrick   // with lower cost.
439e5dd7070Spatrick   auto IsBetterAsSingleFieldRun = [&](uint64_t OffsetInRecord,
440e5dd7070Spatrick                                       uint64_t StartBitOffset) {
441e5dd7070Spatrick     if (!Types.getCodeGenOpts().FineGrainedBitfieldAccesses)
442e5dd7070Spatrick       return false;
443ec727ea7Spatrick     if (OffsetInRecord < 8 || !llvm::isPowerOf2_64(OffsetInRecord) ||
444ec727ea7Spatrick         !DataLayout.fitsInLegalInteger(OffsetInRecord))
445e5dd7070Spatrick       return false;
446a9ac8606Spatrick     // Make sure StartBitOffset is naturally aligned if it is treated as an
447e5dd7070Spatrick     // IType integer.
448e5dd7070Spatrick     if (StartBitOffset %
449e5dd7070Spatrick             Context.toBits(getAlignment(getIntNType(OffsetInRecord))) !=
450e5dd7070Spatrick         0)
451e5dd7070Spatrick       return false;
452e5dd7070Spatrick     return true;
453e5dd7070Spatrick   };
454e5dd7070Spatrick 
455e5dd7070Spatrick   // The start field is better as a single field run.
456e5dd7070Spatrick   bool StartFieldAsSingleRun = false;
457e5dd7070Spatrick   for (;;) {
458e5dd7070Spatrick     // Check to see if we need to start a new run.
459e5dd7070Spatrick     if (Run == FieldEnd) {
460e5dd7070Spatrick       // If we're out of fields, return.
461e5dd7070Spatrick       if (Field == FieldEnd)
462e5dd7070Spatrick         break;
463e5dd7070Spatrick       // Any non-zero-length bitfield can start a new run.
464e5dd7070Spatrick       if (!Field->isZeroLengthBitField(Context)) {
465e5dd7070Spatrick         Run = Field;
466e5dd7070Spatrick         StartBitOffset = getFieldBitOffset(*Field);
467e5dd7070Spatrick         Tail = StartBitOffset + Field->getBitWidthValue(Context);
468e5dd7070Spatrick         StartFieldAsSingleRun = IsBetterAsSingleFieldRun(Tail - StartBitOffset,
469e5dd7070Spatrick                                                          StartBitOffset);
470e5dd7070Spatrick       }
471e5dd7070Spatrick       ++Field;
472e5dd7070Spatrick       continue;
473e5dd7070Spatrick     }
474e5dd7070Spatrick 
475e5dd7070Spatrick     // If the start field of a new run is better as a single run, or
476e5dd7070Spatrick     // if current field (or consecutive fields) is better as a single run, or
477e5dd7070Spatrick     // if current field has zero width bitfield and either
478e5dd7070Spatrick     // UseZeroLengthBitfieldAlignment or UseBitFieldTypeAlignment is set to
479e5dd7070Spatrick     // true, or
480e5dd7070Spatrick     // if the offset of current field is inconsistent with the offset of
481e5dd7070Spatrick     // previous field plus its offset,
482e5dd7070Spatrick     // skip the block below and go ahead to emit the storage.
483e5dd7070Spatrick     // Otherwise, try to add bitfields to the run.
484e5dd7070Spatrick     if (!StartFieldAsSingleRun && Field != FieldEnd &&
485e5dd7070Spatrick         !IsBetterAsSingleFieldRun(Tail - StartBitOffset, StartBitOffset) &&
486e5dd7070Spatrick         (!Field->isZeroLengthBitField(Context) ||
487e5dd7070Spatrick          (!Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
488e5dd7070Spatrick           !Context.getTargetInfo().useBitFieldTypeAlignment())) &&
489e5dd7070Spatrick         Tail == getFieldBitOffset(*Field)) {
490e5dd7070Spatrick       Tail += Field->getBitWidthValue(Context);
491e5dd7070Spatrick       ++Field;
492e5dd7070Spatrick       continue;
493e5dd7070Spatrick     }
494e5dd7070Spatrick 
495e5dd7070Spatrick     // We've hit a break-point in the run and need to emit a storage field.
496e5dd7070Spatrick     llvm::Type *Type = getIntNType(Tail - StartBitOffset);
497e5dd7070Spatrick     // Add the storage member to the record and set the bitfield info for all of
498e5dd7070Spatrick     // the bitfields in the run.  Bitfields get the offset of their storage but
499e5dd7070Spatrick     // come afterward and remain there after a stable sort.
500e5dd7070Spatrick     Members.push_back(StorageInfo(bitsToCharUnits(StartBitOffset), Type));
501e5dd7070Spatrick     for (; Run != Field; ++Run)
502e5dd7070Spatrick       Members.push_back(MemberInfo(bitsToCharUnits(StartBitOffset),
503e5dd7070Spatrick                                    MemberInfo::Field, nullptr, *Run));
504e5dd7070Spatrick     Run = FieldEnd;
505e5dd7070Spatrick     StartFieldAsSingleRun = false;
506e5dd7070Spatrick   }
507e5dd7070Spatrick }
508e5dd7070Spatrick 
accumulateBases()509e5dd7070Spatrick void CGRecordLowering::accumulateBases() {
510e5dd7070Spatrick   // If we've got a primary virtual base, we need to add it with the bases.
511e5dd7070Spatrick   if (Layout.isPrimaryBaseVirtual()) {
512e5dd7070Spatrick     const CXXRecordDecl *BaseDecl = Layout.getPrimaryBase();
513e5dd7070Spatrick     Members.push_back(MemberInfo(CharUnits::Zero(), MemberInfo::Base,
514e5dd7070Spatrick                                  getStorageType(BaseDecl), BaseDecl));
515e5dd7070Spatrick   }
516e5dd7070Spatrick   // Accumulate the non-virtual bases.
517e5dd7070Spatrick   for (const auto &Base : RD->bases()) {
518e5dd7070Spatrick     if (Base.isVirtual())
519e5dd7070Spatrick       continue;
520e5dd7070Spatrick 
521e5dd7070Spatrick     // Bases can be zero-sized even if not technically empty if they
522e5dd7070Spatrick     // contain only a trailing array member.
523e5dd7070Spatrick     const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
524e5dd7070Spatrick     if (!BaseDecl->isEmpty() &&
525e5dd7070Spatrick         !Context.getASTRecordLayout(BaseDecl).getNonVirtualSize().isZero())
526e5dd7070Spatrick       Members.push_back(MemberInfo(Layout.getBaseClassOffset(BaseDecl),
527e5dd7070Spatrick           MemberInfo::Base, getStorageType(BaseDecl), BaseDecl));
528e5dd7070Spatrick   }
529e5dd7070Spatrick }
530e5dd7070Spatrick 
531a9ac8606Spatrick /// The AAPCS that defines that, when possible, bit-fields should
532a9ac8606Spatrick /// be accessed using containers of the declared type width:
533a9ac8606Spatrick /// When a volatile bit-field is read, and its container does not overlap with
534a9ac8606Spatrick /// any non-bit-field member or any zero length bit-field member, its container
535a9ac8606Spatrick /// must be read exactly once using the access width appropriate to the type of
536a9ac8606Spatrick /// the container. When a volatile bit-field is written, and its container does
537a9ac8606Spatrick /// not overlap with any non-bit-field member or any zero-length bit-field
538a9ac8606Spatrick /// member, its container must be read exactly once and written exactly once
539a9ac8606Spatrick /// using the access width appropriate to the type of the container. The two
540a9ac8606Spatrick /// accesses are not atomic.
541a9ac8606Spatrick ///
542a9ac8606Spatrick /// Enforcing the width restriction can be disabled using
543a9ac8606Spatrick /// -fno-aapcs-bitfield-width.
computeVolatileBitfields()544a9ac8606Spatrick void CGRecordLowering::computeVolatileBitfields() {
545a9ac8606Spatrick   if (!isAAPCS() || !Types.getCodeGenOpts().AAPCSBitfieldWidth)
546a9ac8606Spatrick     return;
547a9ac8606Spatrick 
548a9ac8606Spatrick   for (auto &I : BitFields) {
549a9ac8606Spatrick     const FieldDecl *Field = I.first;
550a9ac8606Spatrick     CGBitFieldInfo &Info = I.second;
551a9ac8606Spatrick     llvm::Type *ResLTy = Types.ConvertTypeForMem(Field->getType());
552a9ac8606Spatrick     // If the record alignment is less than the type width, we can't enforce a
553a9ac8606Spatrick     // aligned load, bail out.
554a9ac8606Spatrick     if ((uint64_t)(Context.toBits(Layout.getAlignment())) <
555a9ac8606Spatrick         ResLTy->getPrimitiveSizeInBits())
556a9ac8606Spatrick       continue;
557a9ac8606Spatrick     // CGRecordLowering::setBitFieldInfo() pre-adjusts the bit-field offsets
558a9ac8606Spatrick     // for big-endian targets, but it assumes a container of width
559a9ac8606Spatrick     // Info.StorageSize. Since AAPCS uses a different container size (width
560a9ac8606Spatrick     // of the type), we first undo that calculation here and redo it once
561a9ac8606Spatrick     // the bit-field offset within the new container is calculated.
562a9ac8606Spatrick     const unsigned OldOffset =
563a9ac8606Spatrick         isBE() ? Info.StorageSize - (Info.Offset + Info.Size) : Info.Offset;
564a9ac8606Spatrick     // Offset to the bit-field from the beginning of the struct.
565a9ac8606Spatrick     const unsigned AbsoluteOffset =
566a9ac8606Spatrick         Context.toBits(Info.StorageOffset) + OldOffset;
567a9ac8606Spatrick 
568a9ac8606Spatrick     // Container size is the width of the bit-field type.
569a9ac8606Spatrick     const unsigned StorageSize = ResLTy->getPrimitiveSizeInBits();
570a9ac8606Spatrick     // Nothing to do if the access uses the desired
571a9ac8606Spatrick     // container width and is naturally aligned.
572a9ac8606Spatrick     if (Info.StorageSize == StorageSize && (OldOffset % StorageSize == 0))
573a9ac8606Spatrick       continue;
574a9ac8606Spatrick 
575a9ac8606Spatrick     // Offset within the container.
576a9ac8606Spatrick     unsigned Offset = AbsoluteOffset & (StorageSize - 1);
577a9ac8606Spatrick     // Bail out if an aligned load of the container cannot cover the entire
578a9ac8606Spatrick     // bit-field. This can happen for example, if the bit-field is part of a
579a9ac8606Spatrick     // packed struct. AAPCS does not define access rules for such cases, we let
580a9ac8606Spatrick     // clang to follow its own rules.
581a9ac8606Spatrick     if (Offset + Info.Size > StorageSize)
582a9ac8606Spatrick       continue;
583a9ac8606Spatrick 
584a9ac8606Spatrick     // Re-adjust offsets for big-endian targets.
585a9ac8606Spatrick     if (isBE())
586a9ac8606Spatrick       Offset = StorageSize - (Offset + Info.Size);
587a9ac8606Spatrick 
588a9ac8606Spatrick     const CharUnits StorageOffset =
589a9ac8606Spatrick         Context.toCharUnitsFromBits(AbsoluteOffset & ~(StorageSize - 1));
590a9ac8606Spatrick     const CharUnits End = StorageOffset +
591a9ac8606Spatrick                           Context.toCharUnitsFromBits(StorageSize) -
592a9ac8606Spatrick                           CharUnits::One();
593a9ac8606Spatrick 
594a9ac8606Spatrick     const ASTRecordLayout &Layout =
595a9ac8606Spatrick         Context.getASTRecordLayout(Field->getParent());
596a9ac8606Spatrick     // If we access outside memory outside the record, than bail out.
597a9ac8606Spatrick     const CharUnits RecordSize = Layout.getSize();
598a9ac8606Spatrick     if (End >= RecordSize)
599a9ac8606Spatrick       continue;
600a9ac8606Spatrick 
601a9ac8606Spatrick     // Bail out if performing this load would access non-bit-fields members.
602a9ac8606Spatrick     bool Conflict = false;
603a9ac8606Spatrick     for (const auto *F : D->fields()) {
604a9ac8606Spatrick       // Allow sized bit-fields overlaps.
605a9ac8606Spatrick       if (F->isBitField() && !F->isZeroLengthBitField(Context))
606a9ac8606Spatrick         continue;
607a9ac8606Spatrick 
608a9ac8606Spatrick       const CharUnits FOffset = Context.toCharUnitsFromBits(
609a9ac8606Spatrick           Layout.getFieldOffset(F->getFieldIndex()));
610a9ac8606Spatrick 
611a9ac8606Spatrick       // As C11 defines, a zero sized bit-field defines a barrier, so
612a9ac8606Spatrick       // fields after and before it should be race condition free.
613a9ac8606Spatrick       // The AAPCS acknowledges it and imposes no restritions when the
614a9ac8606Spatrick       // natural container overlaps a zero-length bit-field.
615a9ac8606Spatrick       if (F->isZeroLengthBitField(Context)) {
616a9ac8606Spatrick         if (End > FOffset && StorageOffset < FOffset) {
617a9ac8606Spatrick           Conflict = true;
618a9ac8606Spatrick           break;
619a9ac8606Spatrick         }
620a9ac8606Spatrick       }
621a9ac8606Spatrick 
622a9ac8606Spatrick       const CharUnits FEnd =
623a9ac8606Spatrick           FOffset +
624a9ac8606Spatrick           Context.toCharUnitsFromBits(
625a9ac8606Spatrick               Types.ConvertTypeForMem(F->getType())->getPrimitiveSizeInBits()) -
626a9ac8606Spatrick           CharUnits::One();
627a9ac8606Spatrick       // If no overlap, continue.
628a9ac8606Spatrick       if (End < FOffset || FEnd < StorageOffset)
629a9ac8606Spatrick         continue;
630a9ac8606Spatrick 
631a9ac8606Spatrick       // The desired load overlaps a non-bit-field member, bail out.
632a9ac8606Spatrick       Conflict = true;
633a9ac8606Spatrick       break;
634a9ac8606Spatrick     }
635a9ac8606Spatrick 
636a9ac8606Spatrick     if (Conflict)
637a9ac8606Spatrick       continue;
638a9ac8606Spatrick     // Write the new bit-field access parameters.
639a9ac8606Spatrick     // As the storage offset now is defined as the number of elements from the
640a9ac8606Spatrick     // start of the structure, we should divide the Offset by the element size.
641a9ac8606Spatrick     Info.VolatileStorageOffset =
642a9ac8606Spatrick         StorageOffset / Context.toCharUnitsFromBits(StorageSize).getQuantity();
643a9ac8606Spatrick     Info.VolatileStorageSize = StorageSize;
644a9ac8606Spatrick     Info.VolatileOffset = Offset;
645a9ac8606Spatrick   }
646a9ac8606Spatrick }
647a9ac8606Spatrick 
accumulateVPtrs()648e5dd7070Spatrick void CGRecordLowering::accumulateVPtrs() {
649e5dd7070Spatrick   if (Layout.hasOwnVFPtr())
650e5dd7070Spatrick     Members.push_back(MemberInfo(CharUnits::Zero(), MemberInfo::VFPtr,
651e5dd7070Spatrick         llvm::FunctionType::get(getIntNType(32), /*isVarArg=*/true)->
652e5dd7070Spatrick             getPointerTo()->getPointerTo()));
653e5dd7070Spatrick   if (Layout.hasOwnVBPtr())
654e5dd7070Spatrick     Members.push_back(MemberInfo(Layout.getVBPtrOffset(), MemberInfo::VBPtr,
655e5dd7070Spatrick         llvm::Type::getInt32PtrTy(Types.getLLVMContext())));
656e5dd7070Spatrick }
657e5dd7070Spatrick 
accumulateVBases()658e5dd7070Spatrick void CGRecordLowering::accumulateVBases() {
659e5dd7070Spatrick   CharUnits ScissorOffset = Layout.getNonVirtualSize();
660e5dd7070Spatrick   // In the itanium ABI, it's possible to place a vbase at a dsize that is
661e5dd7070Spatrick   // smaller than the nvsize.  Here we check to see if such a base is placed
662e5dd7070Spatrick   // before the nvsize and set the scissor offset to that, instead of the
663e5dd7070Spatrick   // nvsize.
664e5dd7070Spatrick   if (isOverlappingVBaseABI())
665e5dd7070Spatrick     for (const auto &Base : RD->vbases()) {
666e5dd7070Spatrick       const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
667e5dd7070Spatrick       if (BaseDecl->isEmpty())
668e5dd7070Spatrick         continue;
669e5dd7070Spatrick       // If the vbase is a primary virtual base of some base, then it doesn't
670e5dd7070Spatrick       // get its own storage location but instead lives inside of that base.
671e5dd7070Spatrick       if (Context.isNearlyEmpty(BaseDecl) && !hasOwnStorage(RD, BaseDecl))
672e5dd7070Spatrick         continue;
673e5dd7070Spatrick       ScissorOffset = std::min(ScissorOffset,
674e5dd7070Spatrick                                Layout.getVBaseClassOffset(BaseDecl));
675e5dd7070Spatrick     }
676e5dd7070Spatrick   Members.push_back(MemberInfo(ScissorOffset, MemberInfo::Scissor, nullptr,
677e5dd7070Spatrick                                RD));
678e5dd7070Spatrick   for (const auto &Base : RD->vbases()) {
679e5dd7070Spatrick     const CXXRecordDecl *BaseDecl = Base.getType()->getAsCXXRecordDecl();
680e5dd7070Spatrick     if (BaseDecl->isEmpty())
681e5dd7070Spatrick       continue;
682e5dd7070Spatrick     CharUnits Offset = Layout.getVBaseClassOffset(BaseDecl);
683e5dd7070Spatrick     // If the vbase is a primary virtual base of some base, then it doesn't
684e5dd7070Spatrick     // get its own storage location but instead lives inside of that base.
685e5dd7070Spatrick     if (isOverlappingVBaseABI() &&
686e5dd7070Spatrick         Context.isNearlyEmpty(BaseDecl) &&
687e5dd7070Spatrick         !hasOwnStorage(RD, BaseDecl)) {
688e5dd7070Spatrick       Members.push_back(MemberInfo(Offset, MemberInfo::VBase, nullptr,
689e5dd7070Spatrick                                    BaseDecl));
690e5dd7070Spatrick       continue;
691e5dd7070Spatrick     }
692e5dd7070Spatrick     // If we've got a vtordisp, add it as a storage type.
693e5dd7070Spatrick     if (Layout.getVBaseOffsetsMap().find(BaseDecl)->second.hasVtorDisp())
694e5dd7070Spatrick       Members.push_back(StorageInfo(Offset - CharUnits::fromQuantity(4),
695e5dd7070Spatrick                                     getIntNType(32)));
696e5dd7070Spatrick     Members.push_back(MemberInfo(Offset, MemberInfo::VBase,
697e5dd7070Spatrick                                  getStorageType(BaseDecl), BaseDecl));
698e5dd7070Spatrick   }
699e5dd7070Spatrick }
700e5dd7070Spatrick 
hasOwnStorage(const CXXRecordDecl * Decl,const CXXRecordDecl * Query)701e5dd7070Spatrick bool CGRecordLowering::hasOwnStorage(const CXXRecordDecl *Decl,
702e5dd7070Spatrick                                      const CXXRecordDecl *Query) {
703e5dd7070Spatrick   const ASTRecordLayout &DeclLayout = Context.getASTRecordLayout(Decl);
704e5dd7070Spatrick   if (DeclLayout.isPrimaryBaseVirtual() && DeclLayout.getPrimaryBase() == Query)
705e5dd7070Spatrick     return false;
706e5dd7070Spatrick   for (const auto &Base : Decl->bases())
707e5dd7070Spatrick     if (!hasOwnStorage(Base.getType()->getAsCXXRecordDecl(), Query))
708e5dd7070Spatrick       return false;
709e5dd7070Spatrick   return true;
710e5dd7070Spatrick }
711e5dd7070Spatrick 
calculateZeroInit()712e5dd7070Spatrick void CGRecordLowering::calculateZeroInit() {
713e5dd7070Spatrick   for (std::vector<MemberInfo>::const_iterator Member = Members.begin(),
714e5dd7070Spatrick                                                MemberEnd = Members.end();
715e5dd7070Spatrick        IsZeroInitializableAsBase && Member != MemberEnd; ++Member) {
716e5dd7070Spatrick     if (Member->Kind == MemberInfo::Field) {
717e5dd7070Spatrick       if (!Member->FD || isZeroInitializable(Member->FD))
718e5dd7070Spatrick         continue;
719e5dd7070Spatrick       IsZeroInitializable = IsZeroInitializableAsBase = false;
720e5dd7070Spatrick     } else if (Member->Kind == MemberInfo::Base ||
721e5dd7070Spatrick                Member->Kind == MemberInfo::VBase) {
722e5dd7070Spatrick       if (isZeroInitializable(Member->RD))
723e5dd7070Spatrick         continue;
724e5dd7070Spatrick       IsZeroInitializable = false;
725e5dd7070Spatrick       if (Member->Kind == MemberInfo::Base)
726e5dd7070Spatrick         IsZeroInitializableAsBase = false;
727e5dd7070Spatrick     }
728e5dd7070Spatrick   }
729e5dd7070Spatrick }
730e5dd7070Spatrick 
clipTailPadding()731e5dd7070Spatrick void CGRecordLowering::clipTailPadding() {
732e5dd7070Spatrick   std::vector<MemberInfo>::iterator Prior = Members.begin();
733e5dd7070Spatrick   CharUnits Tail = getSize(Prior->Data);
734e5dd7070Spatrick   for (std::vector<MemberInfo>::iterator Member = Prior + 1,
735e5dd7070Spatrick                                          MemberEnd = Members.end();
736e5dd7070Spatrick        Member != MemberEnd; ++Member) {
737e5dd7070Spatrick     // Only members with data and the scissor can cut into tail padding.
738e5dd7070Spatrick     if (!Member->Data && Member->Kind != MemberInfo::Scissor)
739e5dd7070Spatrick       continue;
740e5dd7070Spatrick     if (Member->Offset < Tail) {
741e5dd7070Spatrick       assert(Prior->Kind == MemberInfo::Field &&
742e5dd7070Spatrick              "Only storage fields have tail padding!");
743e5dd7070Spatrick       if (!Prior->FD || Prior->FD->isBitField())
744e5dd7070Spatrick         Prior->Data = getByteArrayType(bitsToCharUnits(llvm::alignTo(
745e5dd7070Spatrick             cast<llvm::IntegerType>(Prior->Data)->getIntegerBitWidth(), 8)));
746e5dd7070Spatrick       else {
747e5dd7070Spatrick         assert(Prior->FD->hasAttr<NoUniqueAddressAttr>() &&
748e5dd7070Spatrick                "should not have reused this field's tail padding");
749e5dd7070Spatrick         Prior->Data = getByteArrayType(
750a9ac8606Spatrick             Context.getTypeInfoDataSizeInChars(Prior->FD->getType()).Width);
751e5dd7070Spatrick       }
752e5dd7070Spatrick     }
753e5dd7070Spatrick     if (Member->Data)
754e5dd7070Spatrick       Prior = Member;
755e5dd7070Spatrick     Tail = Prior->Offset + getSize(Prior->Data);
756e5dd7070Spatrick   }
757e5dd7070Spatrick }
758e5dd7070Spatrick 
determinePacked(bool NVBaseType)759e5dd7070Spatrick void CGRecordLowering::determinePacked(bool NVBaseType) {
760e5dd7070Spatrick   if (Packed)
761e5dd7070Spatrick     return;
762e5dd7070Spatrick   CharUnits Alignment = CharUnits::One();
763e5dd7070Spatrick   CharUnits NVAlignment = CharUnits::One();
764e5dd7070Spatrick   CharUnits NVSize =
765e5dd7070Spatrick       !NVBaseType && RD ? Layout.getNonVirtualSize() : CharUnits::Zero();
766e5dd7070Spatrick   for (std::vector<MemberInfo>::const_iterator Member = Members.begin(),
767e5dd7070Spatrick                                                MemberEnd = Members.end();
768e5dd7070Spatrick        Member != MemberEnd; ++Member) {
769e5dd7070Spatrick     if (!Member->Data)
770e5dd7070Spatrick       continue;
771e5dd7070Spatrick     // If any member falls at an offset that it not a multiple of its alignment,
772e5dd7070Spatrick     // then the entire record must be packed.
773e5dd7070Spatrick     if (Member->Offset % getAlignment(Member->Data))
774e5dd7070Spatrick       Packed = true;
775e5dd7070Spatrick     if (Member->Offset < NVSize)
776e5dd7070Spatrick       NVAlignment = std::max(NVAlignment, getAlignment(Member->Data));
777e5dd7070Spatrick     Alignment = std::max(Alignment, getAlignment(Member->Data));
778e5dd7070Spatrick   }
779e5dd7070Spatrick   // If the size of the record (the capstone's offset) is not a multiple of the
780e5dd7070Spatrick   // record's alignment, it must be packed.
781e5dd7070Spatrick   if (Members.back().Offset % Alignment)
782e5dd7070Spatrick     Packed = true;
783e5dd7070Spatrick   // If the non-virtual sub-object is not a multiple of the non-virtual
784e5dd7070Spatrick   // sub-object's alignment, it must be packed.  We cannot have a packed
785e5dd7070Spatrick   // non-virtual sub-object and an unpacked complete object or vise versa.
786e5dd7070Spatrick   if (NVSize % NVAlignment)
787e5dd7070Spatrick     Packed = true;
788e5dd7070Spatrick   // Update the alignment of the sentinel.
789e5dd7070Spatrick   if (!Packed)
790e5dd7070Spatrick     Members.back().Data = getIntNType(Context.toBits(Alignment));
791e5dd7070Spatrick }
792e5dd7070Spatrick 
insertPadding()793e5dd7070Spatrick void CGRecordLowering::insertPadding() {
794e5dd7070Spatrick   std::vector<std::pair<CharUnits, CharUnits> > Padding;
795e5dd7070Spatrick   CharUnits Size = CharUnits::Zero();
796e5dd7070Spatrick   for (std::vector<MemberInfo>::const_iterator Member = Members.begin(),
797e5dd7070Spatrick                                                MemberEnd = Members.end();
798e5dd7070Spatrick        Member != MemberEnd; ++Member) {
799e5dd7070Spatrick     if (!Member->Data)
800e5dd7070Spatrick       continue;
801e5dd7070Spatrick     CharUnits Offset = Member->Offset;
802e5dd7070Spatrick     assert(Offset >= Size);
803e5dd7070Spatrick     // Insert padding if we need to.
804e5dd7070Spatrick     if (Offset !=
805e5dd7070Spatrick         Size.alignTo(Packed ? CharUnits::One() : getAlignment(Member->Data)))
806e5dd7070Spatrick       Padding.push_back(std::make_pair(Size, Offset - Size));
807e5dd7070Spatrick     Size = Offset + getSize(Member->Data);
808e5dd7070Spatrick   }
809e5dd7070Spatrick   if (Padding.empty())
810e5dd7070Spatrick     return;
811e5dd7070Spatrick   // Add the padding to the Members list and sort it.
812e5dd7070Spatrick   for (std::vector<std::pair<CharUnits, CharUnits> >::const_iterator
813e5dd7070Spatrick         Pad = Padding.begin(), PadEnd = Padding.end();
814e5dd7070Spatrick         Pad != PadEnd; ++Pad)
815e5dd7070Spatrick     Members.push_back(StorageInfo(Pad->first, getByteArrayType(Pad->second)));
816e5dd7070Spatrick   llvm::stable_sort(Members);
817e5dd7070Spatrick }
818e5dd7070Spatrick 
fillOutputFields()819e5dd7070Spatrick void CGRecordLowering::fillOutputFields() {
820e5dd7070Spatrick   for (std::vector<MemberInfo>::const_iterator Member = Members.begin(),
821e5dd7070Spatrick                                                MemberEnd = Members.end();
822e5dd7070Spatrick        Member != MemberEnd; ++Member) {
823e5dd7070Spatrick     if (Member->Data)
824e5dd7070Spatrick       FieldTypes.push_back(Member->Data);
825e5dd7070Spatrick     if (Member->Kind == MemberInfo::Field) {
826e5dd7070Spatrick       if (Member->FD)
827e5dd7070Spatrick         Fields[Member->FD->getCanonicalDecl()] = FieldTypes.size() - 1;
828e5dd7070Spatrick       // A field without storage must be a bitfield.
829e5dd7070Spatrick       if (!Member->Data)
830e5dd7070Spatrick         setBitFieldInfo(Member->FD, Member->Offset, FieldTypes.back());
831e5dd7070Spatrick     } else if (Member->Kind == MemberInfo::Base)
832e5dd7070Spatrick       NonVirtualBases[Member->RD] = FieldTypes.size() - 1;
833e5dd7070Spatrick     else if (Member->Kind == MemberInfo::VBase)
834e5dd7070Spatrick       VirtualBases[Member->RD] = FieldTypes.size() - 1;
835e5dd7070Spatrick   }
836e5dd7070Spatrick }
837e5dd7070Spatrick 
MakeInfo(CodeGenTypes & Types,const FieldDecl * FD,uint64_t Offset,uint64_t Size,uint64_t StorageSize,CharUnits StorageOffset)838e5dd7070Spatrick CGBitFieldInfo CGBitFieldInfo::MakeInfo(CodeGenTypes &Types,
839e5dd7070Spatrick                                         const FieldDecl *FD,
840e5dd7070Spatrick                                         uint64_t Offset, uint64_t Size,
841e5dd7070Spatrick                                         uint64_t StorageSize,
842e5dd7070Spatrick                                         CharUnits StorageOffset) {
843e5dd7070Spatrick   // This function is vestigial from CGRecordLayoutBuilder days but is still
844e5dd7070Spatrick   // used in GCObjCRuntime.cpp.  That usage has a "fixme" attached to it that
845e5dd7070Spatrick   // when addressed will allow for the removal of this function.
846e5dd7070Spatrick   llvm::Type *Ty = Types.ConvertTypeForMem(FD->getType());
847e5dd7070Spatrick   CharUnits TypeSizeInBytes =
848e5dd7070Spatrick     CharUnits::fromQuantity(Types.getDataLayout().getTypeAllocSize(Ty));
849e5dd7070Spatrick   uint64_t TypeSizeInBits = Types.getContext().toBits(TypeSizeInBytes);
850e5dd7070Spatrick 
851e5dd7070Spatrick   bool IsSigned = FD->getType()->isSignedIntegerOrEnumerationType();
852e5dd7070Spatrick 
853e5dd7070Spatrick   if (Size > TypeSizeInBits) {
854e5dd7070Spatrick     // We have a wide bit-field. The extra bits are only used for padding, so
855e5dd7070Spatrick     // if we have a bitfield of type T, with size N:
856e5dd7070Spatrick     //
857e5dd7070Spatrick     // T t : N;
858e5dd7070Spatrick     //
859e5dd7070Spatrick     // We can just assume that it's:
860e5dd7070Spatrick     //
861e5dd7070Spatrick     // T t : sizeof(T);
862e5dd7070Spatrick     //
863e5dd7070Spatrick     Size = TypeSizeInBits;
864e5dd7070Spatrick   }
865e5dd7070Spatrick 
866e5dd7070Spatrick   // Reverse the bit offsets for big endian machines. Because we represent
867e5dd7070Spatrick   // a bitfield as a single large integer load, we can imagine the bits
868e5dd7070Spatrick   // counting from the most-significant-bit instead of the
869e5dd7070Spatrick   // least-significant-bit.
870e5dd7070Spatrick   if (Types.getDataLayout().isBigEndian()) {
871e5dd7070Spatrick     Offset = StorageSize - (Offset + Size);
872e5dd7070Spatrick   }
873e5dd7070Spatrick 
874e5dd7070Spatrick   return CGBitFieldInfo(Offset, Size, IsSigned, StorageSize, StorageOffset);
875e5dd7070Spatrick }
876e5dd7070Spatrick 
877ec727ea7Spatrick std::unique_ptr<CGRecordLayout>
ComputeRecordLayout(const RecordDecl * D,llvm::StructType * Ty)878ec727ea7Spatrick CodeGenTypes::ComputeRecordLayout(const RecordDecl *D, llvm::StructType *Ty) {
879e5dd7070Spatrick   CGRecordLowering Builder(*this, D, /*Packed=*/false);
880e5dd7070Spatrick 
881e5dd7070Spatrick   Builder.lower(/*NonVirtualBaseType=*/false);
882e5dd7070Spatrick 
883e5dd7070Spatrick   // If we're in C++, compute the base subobject type.
884e5dd7070Spatrick   llvm::StructType *BaseTy = nullptr;
885e5dd7070Spatrick   if (isa<CXXRecordDecl>(D) && !D->isUnion() && !D->hasAttr<FinalAttr>()) {
886e5dd7070Spatrick     BaseTy = Ty;
887e5dd7070Spatrick     if (Builder.Layout.getNonVirtualSize() != Builder.Layout.getSize()) {
888e5dd7070Spatrick       CGRecordLowering BaseBuilder(*this, D, /*Packed=*/Builder.Packed);
889e5dd7070Spatrick       BaseBuilder.lower(/*NonVirtualBaseType=*/true);
890e5dd7070Spatrick       BaseTy = llvm::StructType::create(
891e5dd7070Spatrick           getLLVMContext(), BaseBuilder.FieldTypes, "", BaseBuilder.Packed);
892e5dd7070Spatrick       addRecordTypeName(D, BaseTy, ".base");
893e5dd7070Spatrick       // BaseTy and Ty must agree on their packedness for getLLVMFieldNo to work
894e5dd7070Spatrick       // on both of them with the same index.
895e5dd7070Spatrick       assert(Builder.Packed == BaseBuilder.Packed &&
896e5dd7070Spatrick              "Non-virtual and complete types must agree on packedness");
897e5dd7070Spatrick     }
898e5dd7070Spatrick   }
899e5dd7070Spatrick 
900e5dd7070Spatrick   // Fill in the struct *after* computing the base type.  Filling in the body
901e5dd7070Spatrick   // signifies that the type is no longer opaque and record layout is complete,
902e5dd7070Spatrick   // but we may need to recursively layout D while laying D out as a base type.
903e5dd7070Spatrick   Ty->setBody(Builder.FieldTypes, Builder.Packed);
904e5dd7070Spatrick 
905ec727ea7Spatrick   auto RL = std::make_unique<CGRecordLayout>(
906ec727ea7Spatrick       Ty, BaseTy, (bool)Builder.IsZeroInitializable,
907ec727ea7Spatrick       (bool)Builder.IsZeroInitializableAsBase);
908e5dd7070Spatrick 
909e5dd7070Spatrick   RL->NonVirtualBases.swap(Builder.NonVirtualBases);
910e5dd7070Spatrick   RL->CompleteObjectVirtualBases.swap(Builder.VirtualBases);
911e5dd7070Spatrick 
912e5dd7070Spatrick   // Add all the field numbers.
913e5dd7070Spatrick   RL->FieldInfo.swap(Builder.Fields);
914e5dd7070Spatrick 
915e5dd7070Spatrick   // Add bitfield info.
916e5dd7070Spatrick   RL->BitFields.swap(Builder.BitFields);
917e5dd7070Spatrick 
918e5dd7070Spatrick   // Dump the layout, if requested.
919e5dd7070Spatrick   if (getContext().getLangOpts().DumpRecordLayouts) {
920e5dd7070Spatrick     llvm::outs() << "\n*** Dumping IRgen Record Layout\n";
921e5dd7070Spatrick     llvm::outs() << "Record: ";
922e5dd7070Spatrick     D->dump(llvm::outs());
923e5dd7070Spatrick     llvm::outs() << "\nLayout: ";
924e5dd7070Spatrick     RL->print(llvm::outs());
925e5dd7070Spatrick   }
926e5dd7070Spatrick 
927e5dd7070Spatrick #ifndef NDEBUG
928e5dd7070Spatrick   // Verify that the computed LLVM struct size matches the AST layout size.
929e5dd7070Spatrick   const ASTRecordLayout &Layout = getContext().getASTRecordLayout(D);
930e5dd7070Spatrick 
931e5dd7070Spatrick   uint64_t TypeSizeInBits = getContext().toBits(Layout.getSize());
932e5dd7070Spatrick   assert(TypeSizeInBits == getDataLayout().getTypeAllocSizeInBits(Ty) &&
933e5dd7070Spatrick          "Type size mismatch!");
934e5dd7070Spatrick 
935e5dd7070Spatrick   if (BaseTy) {
936e5dd7070Spatrick     CharUnits NonVirtualSize  = Layout.getNonVirtualSize();
937e5dd7070Spatrick 
938e5dd7070Spatrick     uint64_t AlignedNonVirtualTypeSizeInBits =
939e5dd7070Spatrick       getContext().toBits(NonVirtualSize);
940e5dd7070Spatrick 
941e5dd7070Spatrick     assert(AlignedNonVirtualTypeSizeInBits ==
942e5dd7070Spatrick            getDataLayout().getTypeAllocSizeInBits(BaseTy) &&
943e5dd7070Spatrick            "Type size mismatch!");
944e5dd7070Spatrick   }
945e5dd7070Spatrick 
946e5dd7070Spatrick   // Verify that the LLVM and AST field offsets agree.
947e5dd7070Spatrick   llvm::StructType *ST = RL->getLLVMType();
948e5dd7070Spatrick   const llvm::StructLayout *SL = getDataLayout().getStructLayout(ST);
949e5dd7070Spatrick 
950e5dd7070Spatrick   const ASTRecordLayout &AST_RL = getContext().getASTRecordLayout(D);
951e5dd7070Spatrick   RecordDecl::field_iterator it = D->field_begin();
952e5dd7070Spatrick   for (unsigned i = 0, e = AST_RL.getFieldCount(); i != e; ++i, ++it) {
953e5dd7070Spatrick     const FieldDecl *FD = *it;
954e5dd7070Spatrick 
955e5dd7070Spatrick     // Ignore zero-sized fields.
956e5dd7070Spatrick     if (FD->isZeroSize(getContext()))
957e5dd7070Spatrick       continue;
958e5dd7070Spatrick 
959e5dd7070Spatrick     // For non-bit-fields, just check that the LLVM struct offset matches the
960e5dd7070Spatrick     // AST offset.
961e5dd7070Spatrick     if (!FD->isBitField()) {
962e5dd7070Spatrick       unsigned FieldNo = RL->getLLVMFieldNo(FD);
963e5dd7070Spatrick       assert(AST_RL.getFieldOffset(i) == SL->getElementOffsetInBits(FieldNo) &&
964e5dd7070Spatrick              "Invalid field offset!");
965e5dd7070Spatrick       continue;
966e5dd7070Spatrick     }
967e5dd7070Spatrick 
968e5dd7070Spatrick     // Ignore unnamed bit-fields.
969e5dd7070Spatrick     if (!FD->getDeclName())
970e5dd7070Spatrick       continue;
971e5dd7070Spatrick 
972e5dd7070Spatrick     const CGBitFieldInfo &Info = RL->getBitFieldInfo(FD);
973e5dd7070Spatrick     llvm::Type *ElementTy = ST->getTypeAtIndex(RL->getLLVMFieldNo(FD));
974e5dd7070Spatrick 
975e5dd7070Spatrick     // Unions have overlapping elements dictating their layout, but for
976e5dd7070Spatrick     // non-unions we can verify that this section of the layout is the exact
977e5dd7070Spatrick     // expected size.
978e5dd7070Spatrick     if (D->isUnion()) {
979e5dd7070Spatrick       // For unions we verify that the start is zero and the size
980e5dd7070Spatrick       // is in-bounds. However, on BE systems, the offset may be non-zero, but
981e5dd7070Spatrick       // the size + offset should match the storage size in that case as it
982e5dd7070Spatrick       // "starts" at the back.
983e5dd7070Spatrick       if (getDataLayout().isBigEndian())
984e5dd7070Spatrick         assert(static_cast<unsigned>(Info.Offset + Info.Size) ==
985e5dd7070Spatrick                Info.StorageSize &&
986e5dd7070Spatrick                "Big endian union bitfield does not end at the back");
987e5dd7070Spatrick       else
988e5dd7070Spatrick         assert(Info.Offset == 0 &&
989e5dd7070Spatrick                "Little endian union bitfield with a non-zero offset");
990e5dd7070Spatrick       assert(Info.StorageSize <= SL->getSizeInBits() &&
991e5dd7070Spatrick              "Union not large enough for bitfield storage");
992e5dd7070Spatrick     } else {
993a9ac8606Spatrick       assert((Info.StorageSize ==
994a9ac8606Spatrick                   getDataLayout().getTypeAllocSizeInBits(ElementTy) ||
995a9ac8606Spatrick               Info.VolatileStorageSize ==
996a9ac8606Spatrick                   getDataLayout().getTypeAllocSizeInBits(ElementTy)) &&
997e5dd7070Spatrick              "Storage size does not match the element type size");
998e5dd7070Spatrick     }
999e5dd7070Spatrick     assert(Info.Size > 0 && "Empty bitfield!");
1000e5dd7070Spatrick     assert(static_cast<unsigned>(Info.Offset) + Info.Size <= Info.StorageSize &&
1001e5dd7070Spatrick            "Bitfield outside of its allocated storage");
1002e5dd7070Spatrick   }
1003e5dd7070Spatrick #endif
1004e5dd7070Spatrick 
1005e5dd7070Spatrick   return RL;
1006e5dd7070Spatrick }
1007e5dd7070Spatrick 
print(raw_ostream & OS) const1008e5dd7070Spatrick void CGRecordLayout::print(raw_ostream &OS) const {
1009e5dd7070Spatrick   OS << "<CGRecordLayout\n";
1010e5dd7070Spatrick   OS << "  LLVMType:" << *CompleteObjectType << "\n";
1011e5dd7070Spatrick   if (BaseSubobjectType)
1012e5dd7070Spatrick     OS << "  NonVirtualBaseLLVMType:" << *BaseSubobjectType << "\n";
1013e5dd7070Spatrick   OS << "  IsZeroInitializable:" << IsZeroInitializable << "\n";
1014e5dd7070Spatrick   OS << "  BitFields:[\n";
1015e5dd7070Spatrick 
1016e5dd7070Spatrick   // Print bit-field infos in declaration order.
1017e5dd7070Spatrick   std::vector<std::pair<unsigned, const CGBitFieldInfo*> > BFIs;
1018e5dd7070Spatrick   for (llvm::DenseMap<const FieldDecl*, CGBitFieldInfo>::const_iterator
1019e5dd7070Spatrick          it = BitFields.begin(), ie = BitFields.end();
1020e5dd7070Spatrick        it != ie; ++it) {
1021e5dd7070Spatrick     const RecordDecl *RD = it->first->getParent();
1022e5dd7070Spatrick     unsigned Index = 0;
1023e5dd7070Spatrick     for (RecordDecl::field_iterator
1024e5dd7070Spatrick            it2 = RD->field_begin(); *it2 != it->first; ++it2)
1025e5dd7070Spatrick       ++Index;
1026e5dd7070Spatrick     BFIs.push_back(std::make_pair(Index, &it->second));
1027e5dd7070Spatrick   }
1028e5dd7070Spatrick   llvm::array_pod_sort(BFIs.begin(), BFIs.end());
1029e5dd7070Spatrick   for (unsigned i = 0, e = BFIs.size(); i != e; ++i) {
1030e5dd7070Spatrick     OS.indent(4);
1031e5dd7070Spatrick     BFIs[i].second->print(OS);
1032e5dd7070Spatrick     OS << "\n";
1033e5dd7070Spatrick   }
1034e5dd7070Spatrick 
1035e5dd7070Spatrick   OS << "]>\n";
1036e5dd7070Spatrick }
1037e5dd7070Spatrick 
dump() const1038e5dd7070Spatrick LLVM_DUMP_METHOD void CGRecordLayout::dump() const {
1039e5dd7070Spatrick   print(llvm::errs());
1040e5dd7070Spatrick }
1041e5dd7070Spatrick 
print(raw_ostream & OS) const1042e5dd7070Spatrick void CGBitFieldInfo::print(raw_ostream &OS) const {
1043e5dd7070Spatrick   OS << "<CGBitFieldInfo"
1044a9ac8606Spatrick      << " Offset:" << Offset << " Size:" << Size << " IsSigned:" << IsSigned
1045e5dd7070Spatrick      << " StorageSize:" << StorageSize
1046a9ac8606Spatrick      << " StorageOffset:" << StorageOffset.getQuantity()
1047a9ac8606Spatrick      << " VolatileOffset:" << VolatileOffset
1048a9ac8606Spatrick      << " VolatileStorageSize:" << VolatileStorageSize
1049a9ac8606Spatrick      << " VolatileStorageOffset:" << VolatileStorageOffset.getQuantity() << ">";
1050e5dd7070Spatrick }
1051e5dd7070Spatrick 
dump() const1052e5dd7070Spatrick LLVM_DUMP_METHOD void CGBitFieldInfo::dump() const {
1053e5dd7070Spatrick   print(llvm::errs());
1054e5dd7070Spatrick }
1055