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