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