1 //=== RecordLayoutBuilder.cpp - Helper class for building record layouts ---==//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "clang/AST/RecordLayout.h"
11 #include "clang/AST/ASTContext.h"
12 #include "clang/AST/Attr.h"
13 #include "clang/AST/CXXInheritance.h"
14 #include "clang/AST/Decl.h"
15 #include "clang/AST/DeclCXX.h"
16 #include "clang/AST/DeclObjC.h"
17 #include "clang/AST/Expr.h"
18 #include "clang/Basic/TargetInfo.h"
19 #include "clang/Sema/SemaDiagnostic.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/Support/CrashRecoveryContext.h"
22 #include "llvm/Support/Format.h"
23 #include "llvm/Support/MathExtras.h"
24 
25 using namespace clang;
26 
27 namespace {
28 
29 /// BaseSubobjectInfo - Represents a single base subobject in a complete class.
30 /// For a class hierarchy like
31 ///
32 /// class A { };
33 /// class B : A { };
34 /// class C : A, B { };
35 ///
36 /// The BaseSubobjectInfo graph for C will have three BaseSubobjectInfo
37 /// instances, one for B and two for A.
38 ///
39 /// If a base is virtual, it will only have one BaseSubobjectInfo allocated.
40 struct BaseSubobjectInfo {
41   /// Class - The class for this base info.
42   const CXXRecordDecl *Class;
43 
44   /// IsVirtual - Whether the BaseInfo represents a virtual base or not.
45   bool IsVirtual;
46 
47   /// Bases - Information about the base subobjects.
48   SmallVector<BaseSubobjectInfo*, 4> Bases;
49 
50   /// PrimaryVirtualBaseInfo - Holds the base info for the primary virtual base
51   /// of this base info (if one exists).
52   BaseSubobjectInfo *PrimaryVirtualBaseInfo;
53 
54   // FIXME: Document.
55   const BaseSubobjectInfo *Derived;
56 };
57 
58 /// EmptySubobjectMap - Keeps track of which empty subobjects exist at different
59 /// offsets while laying out a C++ class.
60 class EmptySubobjectMap {
61   const ASTContext &Context;
62   uint64_t CharWidth;
63 
64   /// Class - The class whose empty entries we're keeping track of.
65   const CXXRecordDecl *Class;
66 
67   /// EmptyClassOffsets - A map from offsets to empty record decls.
68   typedef SmallVector<const CXXRecordDecl *, 1> ClassVectorTy;
69   typedef llvm::DenseMap<CharUnits, ClassVectorTy> EmptyClassOffsetsMapTy;
70   EmptyClassOffsetsMapTy EmptyClassOffsets;
71 
72   /// MaxEmptyClassOffset - The highest offset known to contain an empty
73   /// base subobject.
74   CharUnits MaxEmptyClassOffset;
75 
76   /// ComputeEmptySubobjectSizes - Compute the size of the largest base or
77   /// member subobject that is empty.
78   void ComputeEmptySubobjectSizes();
79 
80   void AddSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset);
81 
82   void UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
83                                  CharUnits Offset, bool PlacingEmptyBase);
84 
85   void UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
86                                   const CXXRecordDecl *Class,
87                                   CharUnits Offset);
88   void UpdateEmptyFieldSubobjects(const FieldDecl *FD, CharUnits Offset);
89 
90   /// AnyEmptySubobjectsBeyondOffset - Returns whether there are any empty
91   /// subobjects beyond the given offset.
92   bool AnyEmptySubobjectsBeyondOffset(CharUnits Offset) const {
93     return Offset <= MaxEmptyClassOffset;
94   }
95 
96   CharUnits
97   getFieldOffset(const ASTRecordLayout &Layout, unsigned FieldNo) const {
98     uint64_t FieldOffset = Layout.getFieldOffset(FieldNo);
99     assert(FieldOffset % CharWidth == 0 &&
100            "Field offset not at char boundary!");
101 
102     return Context.toCharUnitsFromBits(FieldOffset);
103   }
104 
105 protected:
106   bool CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
107                                  CharUnits Offset) const;
108 
109   bool CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
110                                      CharUnits Offset);
111 
112   bool CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
113                                       const CXXRecordDecl *Class,
114                                       CharUnits Offset) const;
115   bool CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
116                                       CharUnits Offset) const;
117 
118 public:
119   /// This holds the size of the largest empty subobject (either a base
120   /// or a member). Will be zero if the record being built doesn't contain
121   /// any empty classes.
122   CharUnits SizeOfLargestEmptySubobject;
123 
124   EmptySubobjectMap(const ASTContext &Context, const CXXRecordDecl *Class)
125   : Context(Context), CharWidth(Context.getCharWidth()), Class(Class) {
126       ComputeEmptySubobjectSizes();
127   }
128 
129   /// CanPlaceBaseAtOffset - Return whether the given base class can be placed
130   /// at the given offset.
131   /// Returns false if placing the record will result in two components
132   /// (direct or indirect) of the same type having the same offset.
133   bool CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
134                             CharUnits Offset);
135 
136   /// CanPlaceFieldAtOffset - Return whether a field can be placed at the given
137   /// offset.
138   bool CanPlaceFieldAtOffset(const FieldDecl *FD, CharUnits Offset);
139 };
140 
141 void EmptySubobjectMap::ComputeEmptySubobjectSizes() {
142   // Check the bases.
143   for (const auto &I : Class->bases()) {
144     const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
145 
146     CharUnits EmptySize;
147     const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
148     if (BaseDecl->isEmpty()) {
149       // If the class decl is empty, get its size.
150       EmptySize = Layout.getSize();
151     } else {
152       // Otherwise, we get the largest empty subobject for the decl.
153       EmptySize = Layout.getSizeOfLargestEmptySubobject();
154     }
155 
156     if (EmptySize > SizeOfLargestEmptySubobject)
157       SizeOfLargestEmptySubobject = EmptySize;
158   }
159 
160   // Check the fields.
161   for (const auto *I : Class->fields()) {
162     const RecordType *RT =
163       Context.getBaseElementType(I->getType())->getAs<RecordType>();
164 
165     // We only care about record types.
166     if (!RT)
167       continue;
168 
169     CharUnits EmptySize;
170     const CXXRecordDecl *MemberDecl = RT->getAsCXXRecordDecl();
171     const ASTRecordLayout &Layout = Context.getASTRecordLayout(MemberDecl);
172     if (MemberDecl->isEmpty()) {
173       // If the class decl is empty, get its size.
174       EmptySize = Layout.getSize();
175     } else {
176       // Otherwise, we get the largest empty subobject for the decl.
177       EmptySize = Layout.getSizeOfLargestEmptySubobject();
178     }
179 
180     if (EmptySize > SizeOfLargestEmptySubobject)
181       SizeOfLargestEmptySubobject = EmptySize;
182   }
183 }
184 
185 bool
186 EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
187                                              CharUnits Offset) const {
188   // We only need to check empty bases.
189   if (!RD->isEmpty())
190     return true;
191 
192   EmptyClassOffsetsMapTy::const_iterator I = EmptyClassOffsets.find(Offset);
193   if (I == EmptyClassOffsets.end())
194     return true;
195 
196   const ClassVectorTy& Classes = I->second;
197   if (std::find(Classes.begin(), Classes.end(), RD) == Classes.end())
198     return true;
199 
200   // There is already an empty class of the same type at this offset.
201   return false;
202 }
203 
204 void EmptySubobjectMap::AddSubobjectAtOffset(const CXXRecordDecl *RD,
205                                              CharUnits Offset) {
206   // We only care about empty bases.
207   if (!RD->isEmpty())
208     return;
209 
210   // If we have empty structures inside a union, we can assign both
211   // the same offset. Just avoid pushing them twice in the list.
212   ClassVectorTy& Classes = EmptyClassOffsets[Offset];
213   if (std::find(Classes.begin(), Classes.end(), RD) != Classes.end())
214     return;
215 
216   Classes.push_back(RD);
217 
218   // Update the empty class offset.
219   if (Offset > MaxEmptyClassOffset)
220     MaxEmptyClassOffset = Offset;
221 }
222 
223 bool
224 EmptySubobjectMap::CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
225                                                  CharUnits Offset) {
226   // We don't have to keep looking past the maximum offset that's known to
227   // contain an empty class.
228   if (!AnyEmptySubobjectsBeyondOffset(Offset))
229     return true;
230 
231   if (!CanPlaceSubobjectAtOffset(Info->Class, Offset))
232     return false;
233 
234   // Traverse all non-virtual bases.
235   const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
236   for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
237     BaseSubobjectInfo* Base = Info->Bases[I];
238     if (Base->IsVirtual)
239       continue;
240 
241     CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
242 
243     if (!CanPlaceBaseSubobjectAtOffset(Base, BaseOffset))
244       return false;
245   }
246 
247   if (Info->PrimaryVirtualBaseInfo) {
248     BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
249 
250     if (Info == PrimaryVirtualBaseInfo->Derived) {
251       if (!CanPlaceBaseSubobjectAtOffset(PrimaryVirtualBaseInfo, Offset))
252         return false;
253     }
254   }
255 
256   // Traverse all member variables.
257   unsigned FieldNo = 0;
258   for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
259        E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
260     if (I->isBitField())
261       continue;
262 
263     CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
264     if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
265       return false;
266   }
267 
268   return true;
269 }
270 
271 void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
272                                                   CharUnits Offset,
273                                                   bool PlacingEmptyBase) {
274   if (!PlacingEmptyBase && Offset >= SizeOfLargestEmptySubobject) {
275     // We know that the only empty subobjects that can conflict with empty
276     // subobject of non-empty bases, are empty bases that can be placed at
277     // offset zero. Because of this, we only need to keep track of empty base
278     // subobjects with offsets less than the size of the largest empty
279     // subobject for our class.
280     return;
281   }
282 
283   AddSubobjectAtOffset(Info->Class, Offset);
284 
285   // Traverse all non-virtual bases.
286   const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
287   for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
288     BaseSubobjectInfo* Base = Info->Bases[I];
289     if (Base->IsVirtual)
290       continue;
291 
292     CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
293     UpdateEmptyBaseSubobjects(Base, BaseOffset, PlacingEmptyBase);
294   }
295 
296   if (Info->PrimaryVirtualBaseInfo) {
297     BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
298 
299     if (Info == PrimaryVirtualBaseInfo->Derived)
300       UpdateEmptyBaseSubobjects(PrimaryVirtualBaseInfo, Offset,
301                                 PlacingEmptyBase);
302   }
303 
304   // Traverse all member variables.
305   unsigned FieldNo = 0;
306   for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
307        E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
308     if (I->isBitField())
309       continue;
310 
311     CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
312     UpdateEmptyFieldSubobjects(*I, FieldOffset);
313   }
314 }
315 
316 bool EmptySubobjectMap::CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
317                                              CharUnits Offset) {
318   // If we know this class doesn't have any empty subobjects we don't need to
319   // bother checking.
320   if (SizeOfLargestEmptySubobject.isZero())
321     return true;
322 
323   if (!CanPlaceBaseSubobjectAtOffset(Info, Offset))
324     return false;
325 
326   // We are able to place the base at this offset. Make sure to update the
327   // empty base subobject map.
328   UpdateEmptyBaseSubobjects(Info, Offset, Info->Class->isEmpty());
329   return true;
330 }
331 
332 bool
333 EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
334                                                   const CXXRecordDecl *Class,
335                                                   CharUnits Offset) const {
336   // We don't have to keep looking past the maximum offset that's known to
337   // contain an empty class.
338   if (!AnyEmptySubobjectsBeyondOffset(Offset))
339     return true;
340 
341   if (!CanPlaceSubobjectAtOffset(RD, Offset))
342     return false;
343 
344   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
345 
346   // Traverse all non-virtual bases.
347   for (const auto &I : RD->bases()) {
348     if (I.isVirtual())
349       continue;
350 
351     const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
352 
353     CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
354     if (!CanPlaceFieldSubobjectAtOffset(BaseDecl, Class, BaseOffset))
355       return false;
356   }
357 
358   if (RD == Class) {
359     // This is the most derived class, traverse virtual bases as well.
360     for (const auto &I : RD->vbases()) {
361       const CXXRecordDecl *VBaseDecl = I.getType()->getAsCXXRecordDecl();
362 
363       CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
364       if (!CanPlaceFieldSubobjectAtOffset(VBaseDecl, Class, VBaseOffset))
365         return false;
366     }
367   }
368 
369   // Traverse all member variables.
370   unsigned FieldNo = 0;
371   for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
372        I != E; ++I, ++FieldNo) {
373     if (I->isBitField())
374       continue;
375 
376     CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
377 
378     if (!CanPlaceFieldSubobjectAtOffset(*I, FieldOffset))
379       return false;
380   }
381 
382   return true;
383 }
384 
385 bool
386 EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
387                                                   CharUnits Offset) const {
388   // We don't have to keep looking past the maximum offset that's known to
389   // contain an empty class.
390   if (!AnyEmptySubobjectsBeyondOffset(Offset))
391     return true;
392 
393   QualType T = FD->getType();
394   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
395     return CanPlaceFieldSubobjectAtOffset(RD, RD, Offset);
396 
397   // If we have an array type we need to look at every element.
398   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
399     QualType ElemTy = Context.getBaseElementType(AT);
400     const RecordType *RT = ElemTy->getAs<RecordType>();
401     if (!RT)
402       return true;
403 
404     const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
405     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
406 
407     uint64_t NumElements = Context.getConstantArrayElementCount(AT);
408     CharUnits ElementOffset = Offset;
409     for (uint64_t I = 0; I != NumElements; ++I) {
410       // We don't have to keep looking past the maximum offset that's known to
411       // contain an empty class.
412       if (!AnyEmptySubobjectsBeyondOffset(ElementOffset))
413         return true;
414 
415       if (!CanPlaceFieldSubobjectAtOffset(RD, RD, ElementOffset))
416         return false;
417 
418       ElementOffset += Layout.getSize();
419     }
420   }
421 
422   return true;
423 }
424 
425 bool
426 EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl *FD,
427                                          CharUnits Offset) {
428   if (!CanPlaceFieldSubobjectAtOffset(FD, Offset))
429     return false;
430 
431   // We are able to place the member variable at this offset.
432   // Make sure to update the empty base subobject map.
433   UpdateEmptyFieldSubobjects(FD, Offset);
434   return true;
435 }
436 
437 void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
438                                                    const CXXRecordDecl *Class,
439                                                    CharUnits Offset) {
440   // We know that the only empty subobjects that can conflict with empty
441   // field subobjects are subobjects of empty bases that can be placed at offset
442   // zero. Because of this, we only need to keep track of empty field
443   // subobjects with offsets less than the size of the largest empty
444   // subobject for our class.
445   if (Offset >= SizeOfLargestEmptySubobject)
446     return;
447 
448   AddSubobjectAtOffset(RD, Offset);
449 
450   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
451 
452   // Traverse all non-virtual bases.
453   for (const auto &I : RD->bases()) {
454     if (I.isVirtual())
455       continue;
456 
457     const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
458 
459     CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
460     UpdateEmptyFieldSubobjects(BaseDecl, Class, BaseOffset);
461   }
462 
463   if (RD == Class) {
464     // This is the most derived class, traverse virtual bases as well.
465     for (const auto &I : RD->vbases()) {
466       const CXXRecordDecl *VBaseDecl = I.getType()->getAsCXXRecordDecl();
467 
468       CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
469       UpdateEmptyFieldSubobjects(VBaseDecl, Class, VBaseOffset);
470     }
471   }
472 
473   // Traverse all member variables.
474   unsigned FieldNo = 0;
475   for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
476        I != E; ++I, ++FieldNo) {
477     if (I->isBitField())
478       continue;
479 
480     CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
481 
482     UpdateEmptyFieldSubobjects(*I, FieldOffset);
483   }
484 }
485 
486 void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const FieldDecl *FD,
487                                                    CharUnits Offset) {
488   QualType T = FD->getType();
489   if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl()) {
490     UpdateEmptyFieldSubobjects(RD, RD, Offset);
491     return;
492   }
493 
494   // If we have an array type we need to update every element.
495   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
496     QualType ElemTy = Context.getBaseElementType(AT);
497     const RecordType *RT = ElemTy->getAs<RecordType>();
498     if (!RT)
499       return;
500 
501     const CXXRecordDecl *RD = RT->getAsCXXRecordDecl();
502     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
503 
504     uint64_t NumElements = Context.getConstantArrayElementCount(AT);
505     CharUnits ElementOffset = Offset;
506 
507     for (uint64_t I = 0; I != NumElements; ++I) {
508       // We know that the only empty subobjects that can conflict with empty
509       // field subobjects are subobjects of empty bases that can be placed at
510       // offset zero. Because of this, we only need to keep track of empty field
511       // subobjects with offsets less than the size of the largest empty
512       // subobject for our class.
513       if (ElementOffset >= SizeOfLargestEmptySubobject)
514         return;
515 
516       UpdateEmptyFieldSubobjects(RD, RD, ElementOffset);
517       ElementOffset += Layout.getSize();
518     }
519   }
520 }
521 
522 typedef llvm::SmallPtrSet<const CXXRecordDecl*, 4> ClassSetTy;
523 
524 class RecordLayoutBuilder {
525 protected:
526   // FIXME: Remove this and make the appropriate fields public.
527   friend class clang::ASTContext;
528 
529   const ASTContext &Context;
530 
531   EmptySubobjectMap *EmptySubobjects;
532 
533   /// Size - The current size of the record layout.
534   uint64_t Size;
535 
536   /// Alignment - The current alignment of the record layout.
537   CharUnits Alignment;
538 
539   /// \brief The alignment if attribute packed is not used.
540   CharUnits UnpackedAlignment;
541 
542   SmallVector<uint64_t, 16> FieldOffsets;
543 
544   /// \brief Whether the external AST source has provided a layout for this
545   /// record.
546   unsigned ExternalLayout : 1;
547 
548   /// \brief Whether we need to infer alignment, even when we have an
549   /// externally-provided layout.
550   unsigned InferAlignment : 1;
551 
552   /// Packed - Whether the record is packed or not.
553   unsigned Packed : 1;
554 
555   unsigned IsUnion : 1;
556 
557   unsigned IsMac68kAlign : 1;
558 
559   unsigned IsMsStruct : 1;
560 
561   /// UnfilledBitsInLastUnit - If the last field laid out was a bitfield,
562   /// this contains the number of bits in the last unit that can be used for
563   /// an adjacent bitfield if necessary.  The unit in question is usually
564   /// a byte, but larger units are used if IsMsStruct.
565   unsigned char UnfilledBitsInLastUnit;
566   /// LastBitfieldTypeSize - If IsMsStruct, represents the size of the type
567   /// of the previous field if it was a bitfield.
568   unsigned char LastBitfieldTypeSize;
569 
570   /// MaxFieldAlignment - The maximum allowed field alignment. This is set by
571   /// #pragma pack.
572   CharUnits MaxFieldAlignment;
573 
574   /// DataSize - The data size of the record being laid out.
575   uint64_t DataSize;
576 
577   CharUnits NonVirtualSize;
578   CharUnits NonVirtualAlignment;
579 
580   /// PrimaryBase - the primary base class (if one exists) of the class
581   /// we're laying out.
582   const CXXRecordDecl *PrimaryBase;
583 
584   /// PrimaryBaseIsVirtual - Whether the primary base of the class we're laying
585   /// out is virtual.
586   bool PrimaryBaseIsVirtual;
587 
588   /// HasOwnVFPtr - Whether the class provides its own vtable/vftbl
589   /// pointer, as opposed to inheriting one from a primary base class.
590   bool HasOwnVFPtr;
591 
592   typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
593 
594   /// Bases - base classes and their offsets in the record.
595   BaseOffsetsMapTy Bases;
596 
597   // VBases - virtual base classes and their offsets in the record.
598   ASTRecordLayout::VBaseOffsetsMapTy VBases;
599 
600   /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are
601   /// primary base classes for some other direct or indirect base class.
602   CXXIndirectPrimaryBaseSet IndirectPrimaryBases;
603 
604   /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in
605   /// inheritance graph order. Used for determining the primary base class.
606   const CXXRecordDecl *FirstNearlyEmptyVBase;
607 
608   /// VisitedVirtualBases - A set of all the visited virtual bases, used to
609   /// avoid visiting virtual bases more than once.
610   llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
611 
612   /// \brief Externally-provided size.
613   uint64_t ExternalSize;
614 
615   /// \brief Externally-provided alignment.
616   uint64_t ExternalAlign;
617 
618   /// \brief Externally-provided field offsets.
619   llvm::DenseMap<const FieldDecl *, uint64_t> ExternalFieldOffsets;
620 
621   /// \brief Externally-provided direct, non-virtual base offsets.
622   llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalBaseOffsets;
623 
624   /// \brief Externally-provided virtual base offsets.
625   llvm::DenseMap<const CXXRecordDecl *, CharUnits> ExternalVirtualBaseOffsets;
626 
627   RecordLayoutBuilder(const ASTContext &Context,
628                       EmptySubobjectMap *EmptySubobjects)
629     : Context(Context), EmptySubobjects(EmptySubobjects), Size(0),
630       Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()),
631       ExternalLayout(false), InferAlignment(false),
632       Packed(false), IsUnion(false), IsMac68kAlign(false), IsMsStruct(false),
633       UnfilledBitsInLastUnit(0), LastBitfieldTypeSize(0),
634       MaxFieldAlignment(CharUnits::Zero()),
635       DataSize(0), NonVirtualSize(CharUnits::Zero()),
636       NonVirtualAlignment(CharUnits::One()),
637       PrimaryBase(0), PrimaryBaseIsVirtual(false),
638       HasOwnVFPtr(false),
639       FirstNearlyEmptyVBase(0) { }
640 
641   /// Reset this RecordLayoutBuilder to a fresh state, using the given
642   /// alignment as the initial alignment.  This is used for the
643   /// correct layout of vb-table pointers in MSVC.
644   void resetWithTargetAlignment(CharUnits TargetAlignment) {
645     const ASTContext &Context = this->Context;
646     EmptySubobjectMap *EmptySubobjects = this->EmptySubobjects;
647     this->~RecordLayoutBuilder();
648     new (this) RecordLayoutBuilder(Context, EmptySubobjects);
649     Alignment = UnpackedAlignment = TargetAlignment;
650   }
651 
652   void Layout(const RecordDecl *D);
653   void Layout(const CXXRecordDecl *D);
654   void Layout(const ObjCInterfaceDecl *D);
655 
656   void LayoutFields(const RecordDecl *D);
657   void LayoutField(const FieldDecl *D);
658   void LayoutWideBitField(uint64_t FieldSize, uint64_t TypeSize,
659                           bool FieldPacked, const FieldDecl *D);
660   void LayoutBitField(const FieldDecl *D);
661 
662   TargetCXXABI getCXXABI() const {
663     return Context.getTargetInfo().getCXXABI();
664   }
665 
666   /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects.
667   llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator;
668 
669   typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *>
670     BaseSubobjectInfoMapTy;
671 
672   /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases
673   /// of the class we're laying out to their base subobject info.
674   BaseSubobjectInfoMapTy VirtualBaseInfo;
675 
676   /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the
677   /// class we're laying out to their base subobject info.
678   BaseSubobjectInfoMapTy NonVirtualBaseInfo;
679 
680   /// ComputeBaseSubobjectInfo - Compute the base subobject information for the
681   /// bases of the given class.
682   void ComputeBaseSubobjectInfo(const CXXRecordDecl *RD);
683 
684   /// ComputeBaseSubobjectInfo - Compute the base subobject information for a
685   /// single class and all of its base classes.
686   BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
687                                               bool IsVirtual,
688                                               BaseSubobjectInfo *Derived);
689 
690   /// DeterminePrimaryBase - Determine the primary base of the given class.
691   void DeterminePrimaryBase(const CXXRecordDecl *RD);
692 
693   void SelectPrimaryVBase(const CXXRecordDecl *RD);
694 
695   void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign);
696 
697   /// LayoutNonVirtualBases - Determines the primary base class (if any) and
698   /// lays it out. Will then proceed to lay out all non-virtual base clasess.
699   void LayoutNonVirtualBases(const CXXRecordDecl *RD);
700 
701   /// LayoutNonVirtualBase - Lays out a single non-virtual base.
702   void LayoutNonVirtualBase(const BaseSubobjectInfo *Base);
703 
704   void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
705                                     CharUnits Offset);
706 
707   /// LayoutVirtualBases - Lays out all the virtual bases.
708   void LayoutVirtualBases(const CXXRecordDecl *RD,
709                           const CXXRecordDecl *MostDerivedClass);
710 
711   /// LayoutVirtualBase - Lays out a single virtual base.
712   void LayoutVirtualBase(const BaseSubobjectInfo *Base);
713 
714   /// LayoutBase - Will lay out a base and return the offset where it was
715   /// placed, in chars.
716   CharUnits LayoutBase(const BaseSubobjectInfo *Base);
717 
718   /// InitializeLayout - Initialize record layout for the given record decl.
719   void InitializeLayout(const Decl *D);
720 
721   /// FinishLayout - Finalize record layout. Adjust record size based on the
722   /// alignment.
723   void FinishLayout(const NamedDecl *D);
724 
725   void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment);
726   void UpdateAlignment(CharUnits NewAlignment) {
727     UpdateAlignment(NewAlignment, NewAlignment);
728   }
729 
730   /// \brief Retrieve the externally-supplied field offset for the given
731   /// field.
732   ///
733   /// \param Field The field whose offset is being queried.
734   /// \param ComputedOffset The offset that we've computed for this field.
735   uint64_t updateExternalFieldOffset(const FieldDecl *Field,
736                                      uint64_t ComputedOffset);
737 
738   void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset,
739                           uint64_t UnpackedOffset, unsigned UnpackedAlign,
740                           bool isPacked, const FieldDecl *D);
741 
742   DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
743 
744   CharUnits getSize() const {
745     assert(Size % Context.getCharWidth() == 0);
746     return Context.toCharUnitsFromBits(Size);
747   }
748   uint64_t getSizeInBits() const { return Size; }
749 
750   void setSize(CharUnits NewSize) { Size = Context.toBits(NewSize); }
751   void setSize(uint64_t NewSize) { Size = NewSize; }
752 
753   CharUnits getAligment() const { return Alignment; }
754 
755   CharUnits getDataSize() const {
756     assert(DataSize % Context.getCharWidth() == 0);
757     return Context.toCharUnitsFromBits(DataSize);
758   }
759   uint64_t getDataSizeInBits() const { return DataSize; }
760 
761   void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); }
762   void setDataSize(uint64_t NewSize) { DataSize = NewSize; }
763 
764   RecordLayoutBuilder(const RecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
765   void operator=(const RecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
766 };
767 } // end anonymous namespace
768 
769 void
770 RecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) {
771   for (const auto &I : RD->bases()) {
772     assert(!I.getType()->isDependentType() &&
773            "Cannot layout class with dependent bases.");
774 
775     const CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
776 
777     // Check if this is a nearly empty virtual base.
778     if (I.isVirtual() && Context.isNearlyEmpty(Base)) {
779       // If it's not an indirect primary base, then we've found our primary
780       // base.
781       if (!IndirectPrimaryBases.count(Base)) {
782         PrimaryBase = Base;
783         PrimaryBaseIsVirtual = true;
784         return;
785       }
786 
787       // Is this the first nearly empty virtual base?
788       if (!FirstNearlyEmptyVBase)
789         FirstNearlyEmptyVBase = Base;
790     }
791 
792     SelectPrimaryVBase(Base);
793     if (PrimaryBase)
794       return;
795   }
796 }
797 
798 /// DeterminePrimaryBase - Determine the primary base of the given class.
799 void RecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) {
800   // If the class isn't dynamic, it won't have a primary base.
801   if (!RD->isDynamicClass())
802     return;
803 
804   // Compute all the primary virtual bases for all of our direct and
805   // indirect bases, and record all their primary virtual base classes.
806   RD->getIndirectPrimaryBases(IndirectPrimaryBases);
807 
808   // If the record has a dynamic base class, attempt to choose a primary base
809   // class. It is the first (in direct base class order) non-virtual dynamic
810   // base class, if one exists.
811   for (const auto &I : RD->bases()) {
812     // Ignore virtual bases.
813     if (I.isVirtual())
814       continue;
815 
816     const CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
817 
818     if (Base->isDynamicClass()) {
819       // We found it.
820       PrimaryBase = Base;
821       PrimaryBaseIsVirtual = false;
822       return;
823     }
824   }
825 
826   // Under the Itanium ABI, if there is no non-virtual primary base class,
827   // try to compute the primary virtual base.  The primary virtual base is
828   // the first nearly empty virtual base that is not an indirect primary
829   // virtual base class, if one exists.
830   if (RD->getNumVBases() != 0) {
831     SelectPrimaryVBase(RD);
832     if (PrimaryBase)
833       return;
834   }
835 
836   // Otherwise, it is the first indirect primary base class, if one exists.
837   if (FirstNearlyEmptyVBase) {
838     PrimaryBase = FirstNearlyEmptyVBase;
839     PrimaryBaseIsVirtual = true;
840     return;
841   }
842 
843   assert(!PrimaryBase && "Should not get here with a primary base!");
844 }
845 
846 BaseSubobjectInfo *
847 RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
848                                               bool IsVirtual,
849                                               BaseSubobjectInfo *Derived) {
850   BaseSubobjectInfo *Info;
851 
852   if (IsVirtual) {
853     // Check if we already have info about this virtual base.
854     BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD];
855     if (InfoSlot) {
856       assert(InfoSlot->Class == RD && "Wrong class for virtual base info!");
857       return InfoSlot;
858     }
859 
860     // We don't, create it.
861     InfoSlot = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
862     Info = InfoSlot;
863   } else {
864     Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
865   }
866 
867   Info->Class = RD;
868   Info->IsVirtual = IsVirtual;
869   Info->Derived = 0;
870   Info->PrimaryVirtualBaseInfo = 0;
871 
872   const CXXRecordDecl *PrimaryVirtualBase = 0;
873   BaseSubobjectInfo *PrimaryVirtualBaseInfo = 0;
874 
875   // Check if this base has a primary virtual base.
876   if (RD->getNumVBases()) {
877     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
878     if (Layout.isPrimaryBaseVirtual()) {
879       // This base does have a primary virtual base.
880       PrimaryVirtualBase = Layout.getPrimaryBase();
881       assert(PrimaryVirtualBase && "Didn't have a primary virtual base!");
882 
883       // Now check if we have base subobject info about this primary base.
884       PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
885 
886       if (PrimaryVirtualBaseInfo) {
887         if (PrimaryVirtualBaseInfo->Derived) {
888           // We did have info about this primary base, and it turns out that it
889           // has already been claimed as a primary virtual base for another
890           // base.
891           PrimaryVirtualBase = 0;
892         } else {
893           // We can claim this base as our primary base.
894           Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
895           PrimaryVirtualBaseInfo->Derived = Info;
896         }
897       }
898     }
899   }
900 
901   // Now go through all direct bases.
902   for (const auto &I : RD->bases()) {
903     bool IsVirtual = I.isVirtual();
904 
905     const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
906 
907     Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info));
908   }
909 
910   if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) {
911     // Traversing the bases must have created the base info for our primary
912     // virtual base.
913     PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
914     assert(PrimaryVirtualBaseInfo &&
915            "Did not create a primary virtual base!");
916 
917     // Claim the primary virtual base as our primary virtual base.
918     Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
919     PrimaryVirtualBaseInfo->Derived = Info;
920   }
921 
922   return Info;
923 }
924 
925 void RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD) {
926   for (const auto &I : RD->bases()) {
927     bool IsVirtual = I.isVirtual();
928 
929     const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
930 
931     // Compute the base subobject info for this base.
932     BaseSubobjectInfo *Info = ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, 0);
933 
934     if (IsVirtual) {
935       // ComputeBaseInfo has already added this base for us.
936       assert(VirtualBaseInfo.count(BaseDecl) &&
937              "Did not add virtual base!");
938     } else {
939       // Add the base info to the map of non-virtual bases.
940       assert(!NonVirtualBaseInfo.count(BaseDecl) &&
941              "Non-virtual base already exists!");
942       NonVirtualBaseInfo.insert(std::make_pair(BaseDecl, Info));
943     }
944   }
945 }
946 
947 void
948 RecordLayoutBuilder::EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign) {
949   CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
950 
951   // The maximum field alignment overrides base align.
952   if (!MaxFieldAlignment.isZero()) {
953     BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
954     UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
955   }
956 
957   // Round up the current record size to pointer alignment.
958   setSize(getSize().RoundUpToAlignment(BaseAlign));
959   setDataSize(getSize());
960 
961   // Update the alignment.
962   UpdateAlignment(BaseAlign, UnpackedBaseAlign);
963 }
964 
965 void
966 RecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl *RD) {
967   // Then, determine the primary base class.
968   DeterminePrimaryBase(RD);
969 
970   // Compute base subobject info.
971   ComputeBaseSubobjectInfo(RD);
972 
973   // If we have a primary base class, lay it out.
974   if (PrimaryBase) {
975     if (PrimaryBaseIsVirtual) {
976       // If the primary virtual base was a primary virtual base of some other
977       // base class we'll have to steal it.
978       BaseSubobjectInfo *PrimaryBaseInfo = VirtualBaseInfo.lookup(PrimaryBase);
979       PrimaryBaseInfo->Derived = 0;
980 
981       // We have a virtual primary base, insert it as an indirect primary base.
982       IndirectPrimaryBases.insert(PrimaryBase);
983 
984       assert(!VisitedVirtualBases.count(PrimaryBase) &&
985              "vbase already visited!");
986       VisitedVirtualBases.insert(PrimaryBase);
987 
988       LayoutVirtualBase(PrimaryBaseInfo);
989     } else {
990       BaseSubobjectInfo *PrimaryBaseInfo =
991         NonVirtualBaseInfo.lookup(PrimaryBase);
992       assert(PrimaryBaseInfo &&
993              "Did not find base info for non-virtual primary base!");
994 
995       LayoutNonVirtualBase(PrimaryBaseInfo);
996     }
997 
998   // If this class needs a vtable/vf-table and didn't get one from a
999   // primary base, add it in now.
1000   } else if (RD->isDynamicClass()) {
1001     assert(DataSize == 0 && "Vtable pointer must be at offset zero!");
1002     CharUnits PtrWidth =
1003       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
1004     CharUnits PtrAlign =
1005       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
1006     EnsureVTablePointerAlignment(PtrAlign);
1007     HasOwnVFPtr = true;
1008     setSize(getSize() + PtrWidth);
1009     setDataSize(getSize());
1010   }
1011 
1012   // Now lay out the non-virtual bases.
1013   for (const auto &I : RD->bases()) {
1014 
1015     // Ignore virtual bases.
1016     if (I.isVirtual())
1017       continue;
1018 
1019     const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
1020 
1021     // Skip the primary base, because we've already laid it out.  The
1022     // !PrimaryBaseIsVirtual check is required because we might have a
1023     // non-virtual base of the same type as a primary virtual base.
1024     if (BaseDecl == PrimaryBase && !PrimaryBaseIsVirtual)
1025       continue;
1026 
1027     // Lay out the base.
1028     BaseSubobjectInfo *BaseInfo = NonVirtualBaseInfo.lookup(BaseDecl);
1029     assert(BaseInfo && "Did not find base info for non-virtual base!");
1030 
1031     LayoutNonVirtualBase(BaseInfo);
1032   }
1033 }
1034 
1035 void RecordLayoutBuilder::LayoutNonVirtualBase(const BaseSubobjectInfo *Base) {
1036   // Layout the base.
1037   CharUnits Offset = LayoutBase(Base);
1038 
1039   // Add its base class offset.
1040   assert(!Bases.count(Base->Class) && "base offset already exists!");
1041   Bases.insert(std::make_pair(Base->Class, Offset));
1042 
1043   AddPrimaryVirtualBaseOffsets(Base, Offset);
1044 }
1045 
1046 void
1047 RecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
1048                                                   CharUnits Offset) {
1049   // This base isn't interesting, it has no virtual bases.
1050   if (!Info->Class->getNumVBases())
1051     return;
1052 
1053   // First, check if we have a virtual primary base to add offsets for.
1054   if (Info->PrimaryVirtualBaseInfo) {
1055     assert(Info->PrimaryVirtualBaseInfo->IsVirtual &&
1056            "Primary virtual base is not virtual!");
1057     if (Info->PrimaryVirtualBaseInfo->Derived == Info) {
1058       // Add the offset.
1059       assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) &&
1060              "primary vbase offset already exists!");
1061       VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class,
1062                                    ASTRecordLayout::VBaseInfo(Offset, false)));
1063 
1064       // Traverse the primary virtual base.
1065       AddPrimaryVirtualBaseOffsets(Info->PrimaryVirtualBaseInfo, Offset);
1066     }
1067   }
1068 
1069   // Now go through all direct non-virtual bases.
1070   const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
1071   for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
1072     const BaseSubobjectInfo *Base = Info->Bases[I];
1073     if (Base->IsVirtual)
1074       continue;
1075 
1076     CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
1077     AddPrimaryVirtualBaseOffsets(Base, BaseOffset);
1078   }
1079 }
1080 
1081 void
1082 RecordLayoutBuilder::LayoutVirtualBases(const CXXRecordDecl *RD,
1083                                         const CXXRecordDecl *MostDerivedClass) {
1084   const CXXRecordDecl *PrimaryBase;
1085   bool PrimaryBaseIsVirtual;
1086 
1087   if (MostDerivedClass == RD) {
1088     PrimaryBase = this->PrimaryBase;
1089     PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual;
1090   } else {
1091     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1092     PrimaryBase = Layout.getPrimaryBase();
1093     PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
1094   }
1095 
1096   for (const auto &I : RD->bases()) {
1097     assert(!I.getType()->isDependentType() &&
1098            "Cannot layout class with dependent bases.");
1099 
1100     const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
1101 
1102     if (I.isVirtual()) {
1103       if (PrimaryBase != BaseDecl || !PrimaryBaseIsVirtual) {
1104         bool IndirectPrimaryBase = IndirectPrimaryBases.count(BaseDecl);
1105 
1106         // Only lay out the virtual base if it's not an indirect primary base.
1107         if (!IndirectPrimaryBase) {
1108           // Only visit virtual bases once.
1109           if (!VisitedVirtualBases.insert(BaseDecl))
1110             continue;
1111 
1112           const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1113           assert(BaseInfo && "Did not find virtual base info!");
1114           LayoutVirtualBase(BaseInfo);
1115         }
1116       }
1117     }
1118 
1119     if (!BaseDecl->getNumVBases()) {
1120       // This base isn't interesting since it doesn't have any virtual bases.
1121       continue;
1122     }
1123 
1124     LayoutVirtualBases(BaseDecl, MostDerivedClass);
1125   }
1126 }
1127 
1128 void RecordLayoutBuilder::LayoutVirtualBase(const BaseSubobjectInfo *Base) {
1129   assert(!Base->Derived && "Trying to lay out a primary virtual base!");
1130 
1131   // Layout the base.
1132   CharUnits Offset = LayoutBase(Base);
1133 
1134   // Add its base class offset.
1135   assert(!VBases.count(Base->Class) && "vbase offset already exists!");
1136   VBases.insert(std::make_pair(Base->Class,
1137                        ASTRecordLayout::VBaseInfo(Offset, false)));
1138 
1139   AddPrimaryVirtualBaseOffsets(Base, Offset);
1140 }
1141 
1142 CharUnits RecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) {
1143   const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class);
1144 
1145 
1146   CharUnits Offset;
1147 
1148   // Query the external layout to see if it provides an offset.
1149   bool HasExternalLayout = false;
1150   if (ExternalLayout) {
1151     llvm::DenseMap<const CXXRecordDecl *, CharUnits>::iterator Known;
1152     if (Base->IsVirtual) {
1153       Known = ExternalVirtualBaseOffsets.find(Base->Class);
1154       if (Known != ExternalVirtualBaseOffsets.end()) {
1155         Offset = Known->second;
1156         HasExternalLayout = true;
1157       }
1158     } else {
1159       Known = ExternalBaseOffsets.find(Base->Class);
1160       if (Known != ExternalBaseOffsets.end()) {
1161         Offset = Known->second;
1162         HasExternalLayout = true;
1163       }
1164     }
1165   }
1166 
1167   CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlignment();
1168   CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
1169 
1170   // If we have an empty base class, try to place it at offset 0.
1171   if (Base->Class->isEmpty() &&
1172       (!HasExternalLayout || Offset == CharUnits::Zero()) &&
1173       EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) {
1174     setSize(std::max(getSize(), Layout.getSize()));
1175     UpdateAlignment(BaseAlign, UnpackedBaseAlign);
1176 
1177     return CharUnits::Zero();
1178   }
1179 
1180   // The maximum field alignment overrides base align.
1181   if (!MaxFieldAlignment.isZero()) {
1182     BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1183     UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
1184   }
1185 
1186   if (!HasExternalLayout) {
1187     // Round up the current record size to the base's alignment boundary.
1188     Offset = getDataSize().RoundUpToAlignment(BaseAlign);
1189 
1190     // Try to place the base.
1191     while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset))
1192       Offset += BaseAlign;
1193   } else {
1194     bool Allowed = EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset);
1195     (void)Allowed;
1196     assert(Allowed && "Base subobject externally placed at overlapping offset");
1197 
1198     if (InferAlignment && Offset < getDataSize().RoundUpToAlignment(BaseAlign)){
1199       // The externally-supplied base offset is before the base offset we
1200       // computed. Assume that the structure is packed.
1201       Alignment = CharUnits::One();
1202       InferAlignment = false;
1203     }
1204   }
1205 
1206   if (!Base->Class->isEmpty()) {
1207     // Update the data size.
1208     setDataSize(Offset + Layout.getNonVirtualSize());
1209 
1210     setSize(std::max(getSize(), getDataSize()));
1211   } else
1212     setSize(std::max(getSize(), Offset + Layout.getSize()));
1213 
1214   // Remember max struct/class alignment.
1215   UpdateAlignment(BaseAlign, UnpackedBaseAlign);
1216 
1217   return Offset;
1218 }
1219 
1220 void RecordLayoutBuilder::InitializeLayout(const Decl *D) {
1221   if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1222     IsUnion = RD->isUnion();
1223     IsMsStruct = RD->isMsStruct(Context);
1224   }
1225 
1226   Packed = D->hasAttr<PackedAttr>();
1227 
1228   // Honor the default struct packing maximum alignment flag.
1229   if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) {
1230     MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
1231   }
1232 
1233   // mac68k alignment supersedes maximum field alignment and attribute aligned,
1234   // and forces all structures to have 2-byte alignment. The IBM docs on it
1235   // allude to additional (more complicated) semantics, especially with regard
1236   // to bit-fields, but gcc appears not to follow that.
1237   if (D->hasAttr<AlignMac68kAttr>()) {
1238     IsMac68kAlign = true;
1239     MaxFieldAlignment = CharUnits::fromQuantity(2);
1240     Alignment = CharUnits::fromQuantity(2);
1241   } else {
1242     if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>())
1243       MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment());
1244 
1245     if (unsigned MaxAlign = D->getMaxAlignment())
1246       UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign));
1247   }
1248 
1249   // If there is an external AST source, ask it for the various offsets.
1250   if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
1251     if (ExternalASTSource *External = Context.getExternalSource()) {
1252       ExternalLayout = External->layoutRecordType(RD,
1253                                                   ExternalSize,
1254                                                   ExternalAlign,
1255                                                   ExternalFieldOffsets,
1256                                                   ExternalBaseOffsets,
1257                                                   ExternalVirtualBaseOffsets);
1258 
1259       // Update based on external alignment.
1260       if (ExternalLayout) {
1261         if (ExternalAlign > 0) {
1262           Alignment = Context.toCharUnitsFromBits(ExternalAlign);
1263         } else {
1264           // The external source didn't have alignment information; infer it.
1265           InferAlignment = true;
1266         }
1267       }
1268     }
1269 }
1270 
1271 void RecordLayoutBuilder::Layout(const RecordDecl *D) {
1272   InitializeLayout(D);
1273   LayoutFields(D);
1274 
1275   // Finally, round the size of the total struct up to the alignment of the
1276   // struct itself.
1277   FinishLayout(D);
1278 }
1279 
1280 void RecordLayoutBuilder::Layout(const CXXRecordDecl *RD) {
1281   InitializeLayout(RD);
1282 
1283   // Lay out the vtable and the non-virtual bases.
1284   LayoutNonVirtualBases(RD);
1285 
1286   LayoutFields(RD);
1287 
1288   NonVirtualSize = Context.toCharUnitsFromBits(
1289         llvm::RoundUpToAlignment(getSizeInBits(),
1290                                  Context.getTargetInfo().getCharAlign()));
1291   NonVirtualAlignment = Alignment;
1292 
1293   // Lay out the virtual bases and add the primary virtual base offsets.
1294   LayoutVirtualBases(RD, RD);
1295 
1296   // Finally, round the size of the total struct up to the alignment
1297   // of the struct itself.
1298   FinishLayout(RD);
1299 
1300 #ifndef NDEBUG
1301   // Check that we have base offsets for all bases.
1302   for (const auto &I : RD->bases()) {
1303     if (I.isVirtual())
1304       continue;
1305 
1306     const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
1307 
1308     assert(Bases.count(BaseDecl) && "Did not find base offset!");
1309   }
1310 
1311   // And all virtual bases.
1312   for (const auto &I : RD->vbases()) {
1313     const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
1314 
1315     assert(VBases.count(BaseDecl) && "Did not find base offset!");
1316   }
1317 #endif
1318 }
1319 
1320 void RecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) {
1321   if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
1322     const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD);
1323 
1324     UpdateAlignment(SL.getAlignment());
1325 
1326     // We start laying out ivars not at the end of the superclass
1327     // structure, but at the next byte following the last field.
1328     setSize(SL.getDataSize());
1329     setDataSize(getSize());
1330   }
1331 
1332   InitializeLayout(D);
1333   // Layout each ivar sequentially.
1334   for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD;
1335        IVD = IVD->getNextIvar())
1336     LayoutField(IVD);
1337 
1338   // Finally, round the size of the total struct up to the alignment of the
1339   // struct itself.
1340   FinishLayout(D);
1341 }
1342 
1343 void RecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
1344   // Layout each field, for now, just sequentially, respecting alignment.  In
1345   // the future, this will need to be tweakable by targets.
1346   for (const auto *Field : D->fields())
1347     LayoutField(Field);
1348 }
1349 
1350 void RecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize,
1351                                              uint64_t TypeSize,
1352                                              bool FieldPacked,
1353                                              const FieldDecl *D) {
1354   assert(Context.getLangOpts().CPlusPlus &&
1355          "Can only have wide bit-fields in C++!");
1356 
1357   // Itanium C++ ABI 2.4:
1358   //   If sizeof(T)*8 < n, let T' be the largest integral POD type with
1359   //   sizeof(T')*8 <= n.
1360 
1361   QualType IntegralPODTypes[] = {
1362     Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy,
1363     Context.UnsignedLongTy, Context.UnsignedLongLongTy
1364   };
1365 
1366   QualType Type;
1367   for (unsigned I = 0, E = llvm::array_lengthof(IntegralPODTypes);
1368        I != E; ++I) {
1369     uint64_t Size = Context.getTypeSize(IntegralPODTypes[I]);
1370 
1371     if (Size > FieldSize)
1372       break;
1373 
1374     Type = IntegralPODTypes[I];
1375   }
1376   assert(!Type.isNull() && "Did not find a type!");
1377 
1378   CharUnits TypeAlign = Context.getTypeAlignInChars(Type);
1379 
1380   // We're not going to use any of the unfilled bits in the last byte.
1381   UnfilledBitsInLastUnit = 0;
1382   LastBitfieldTypeSize = 0;
1383 
1384   uint64_t FieldOffset;
1385   uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
1386 
1387   if (IsUnion) {
1388     setDataSize(std::max(getDataSizeInBits(), FieldSize));
1389     FieldOffset = 0;
1390   } else {
1391     // The bitfield is allocated starting at the next offset aligned
1392     // appropriately for T', with length n bits.
1393     FieldOffset = llvm::RoundUpToAlignment(getDataSizeInBits(),
1394                                            Context.toBits(TypeAlign));
1395 
1396     uint64_t NewSizeInBits = FieldOffset + FieldSize;
1397 
1398     setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
1399                                          Context.getTargetInfo().getCharAlign()));
1400     UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
1401   }
1402 
1403   // Place this field at the current location.
1404   FieldOffsets.push_back(FieldOffset);
1405 
1406   CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset,
1407                     Context.toBits(TypeAlign), FieldPacked, D);
1408 
1409   // Update the size.
1410   setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1411 
1412   // Remember max struct/class alignment.
1413   UpdateAlignment(TypeAlign);
1414 }
1415 
1416 void RecordLayoutBuilder::LayoutBitField(const FieldDecl *D) {
1417   bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
1418   uint64_t FieldSize = D->getBitWidthValue(Context);
1419   std::pair<uint64_t, unsigned> FieldInfo = Context.getTypeInfo(D->getType());
1420   uint64_t TypeSize = FieldInfo.first;
1421   unsigned FieldAlign = FieldInfo.second;
1422 
1423   // UnfilledBitsInLastUnit is the difference between the end of the
1424   // last allocated bitfield (i.e. the first bit offset available for
1425   // bitfields) and the end of the current data size in bits (i.e. the
1426   // first bit offset available for non-bitfields).  The current data
1427   // size in bits is always a multiple of the char size; additionally,
1428   // for ms_struct records it's also a multiple of the
1429   // LastBitfieldTypeSize (if set).
1430 
1431   // The struct-layout algorithm is dictated by the platform ABI,
1432   // which in principle could use almost any rules it likes.  In
1433   // practice, UNIXy targets tend to inherit the algorithm described
1434   // in the System V generic ABI.  The basic bitfield layout rule in
1435   // System V is to place bitfields at the next available bit offset
1436   // where the entire bitfield would fit in an aligned storage unit of
1437   // the declared type; it's okay if an earlier or later non-bitfield
1438   // is allocated in the same storage unit.  However, some targets
1439   // (those that !useBitFieldTypeAlignment(), e.g. ARM APCS) don't
1440   // require this storage unit to be aligned, and therefore always put
1441   // the bitfield at the next available bit offset.
1442 
1443   // ms_struct basically requests a complete replacement of the
1444   // platform ABI's struct-layout algorithm, with the high-level goal
1445   // of duplicating MSVC's layout.  For non-bitfields, this follows
1446   // the the standard algorithm.  The basic bitfield layout rule is to
1447   // allocate an entire unit of the bitfield's declared type
1448   // (e.g. 'unsigned long'), then parcel it up among successive
1449   // bitfields whose declared types have the same size, making a new
1450   // unit as soon as the last can no longer store the whole value.
1451   // Since it completely replaces the platform ABI's algorithm,
1452   // settings like !useBitFieldTypeAlignment() do not apply.
1453 
1454   // A zero-width bitfield forces the use of a new storage unit for
1455   // later bitfields.  In general, this occurs by rounding up the
1456   // current size of the struct as if the algorithm were about to
1457   // place a non-bitfield of the field's formal type.  Usually this
1458   // does not change the alignment of the struct itself, but it does
1459   // on some targets (those that useZeroLengthBitfieldAlignment(),
1460   // e.g. ARM).  In ms_struct layout, zero-width bitfields are
1461   // ignored unless they follow a non-zero-width bitfield.
1462 
1463   // A field alignment restriction (e.g. from #pragma pack) or
1464   // specification (e.g. from __attribute__((aligned))) changes the
1465   // formal alignment of the field.  For System V, this alters the
1466   // required alignment of the notional storage unit that must contain
1467   // the bitfield.  For ms_struct, this only affects the placement of
1468   // new storage units.  In both cases, the effect of #pragma pack is
1469   // ignored on zero-width bitfields.
1470 
1471   // On System V, a packed field (e.g. from #pragma pack or
1472   // __attribute__((packed))) always uses the next available bit
1473   // offset.
1474 
1475   // In an ms_struct struct, the alignment of a fundamental type is
1476   // always equal to its size.  This is necessary in order to mimic
1477   // the i386 alignment rules on targets which might not fully align
1478   // all types (e.g. Darwin PPC32, where alignof(long long) == 4).
1479 
1480   // First, some simple bookkeeping to perform for ms_struct structs.
1481   if (IsMsStruct) {
1482     // The field alignment for integer types is always the size.
1483     FieldAlign = TypeSize;
1484 
1485     // If the previous field was not a bitfield, or was a bitfield
1486     // with a different storage unit size, we're done with that
1487     // storage unit.
1488     if (LastBitfieldTypeSize != TypeSize) {
1489       // Also, ignore zero-length bitfields after non-bitfields.
1490       if (!LastBitfieldTypeSize && !FieldSize)
1491         FieldAlign = 1;
1492 
1493       UnfilledBitsInLastUnit = 0;
1494       LastBitfieldTypeSize = 0;
1495     }
1496   }
1497 
1498   // If the field is wider than its declared type, it follows
1499   // different rules in all cases.
1500   if (FieldSize > TypeSize) {
1501     LayoutWideBitField(FieldSize, TypeSize, FieldPacked, D);
1502     return;
1503   }
1504 
1505   // Compute the next available bit offset.
1506   uint64_t FieldOffset =
1507     IsUnion ? 0 : (getDataSizeInBits() - UnfilledBitsInLastUnit);
1508 
1509   // Handle targets that don't honor bitfield type alignment.
1510   if (!IsMsStruct && !Context.getTargetInfo().useBitFieldTypeAlignment()) {
1511     // Some such targets do honor it on zero-width bitfields.
1512     if (FieldSize == 0 &&
1513         Context.getTargetInfo().useZeroLengthBitfieldAlignment()) {
1514       // The alignment to round up to is the max of the field's natural
1515       // alignment and a target-specific fixed value (sometimes zero).
1516       unsigned ZeroLengthBitfieldBoundary =
1517         Context.getTargetInfo().getZeroLengthBitfieldBoundary();
1518       FieldAlign = std::max(FieldAlign, ZeroLengthBitfieldBoundary);
1519 
1520     // If that doesn't apply, just ignore the field alignment.
1521     } else {
1522       FieldAlign = 1;
1523     }
1524   }
1525 
1526   // Remember the alignment we would have used if the field were not packed.
1527   unsigned UnpackedFieldAlign = FieldAlign;
1528 
1529   // Ignore the field alignment if the field is packed unless it has zero-size.
1530   if (!IsMsStruct && FieldPacked && FieldSize != 0)
1531     FieldAlign = 1;
1532 
1533   // But, if there's an 'aligned' attribute on the field, honor that.
1534   if (unsigned ExplicitFieldAlign = D->getMaxAlignment()) {
1535     FieldAlign = std::max(FieldAlign, ExplicitFieldAlign);
1536     UnpackedFieldAlign = std::max(UnpackedFieldAlign, ExplicitFieldAlign);
1537   }
1538 
1539   // But, if there's a #pragma pack in play, that takes precedent over
1540   // even the 'aligned' attribute, for non-zero-width bitfields.
1541   if (!MaxFieldAlignment.isZero() && FieldSize) {
1542     unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment);
1543     FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1544     UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
1545   }
1546 
1547   // For purposes of diagnostics, we're going to simultaneously
1548   // compute the field offsets that we would have used if we weren't
1549   // adding any alignment padding or if the field weren't packed.
1550   uint64_t UnpaddedFieldOffset = FieldOffset;
1551   uint64_t UnpackedFieldOffset = FieldOffset;
1552 
1553   // Check if we need to add padding to fit the bitfield within an
1554   // allocation unit with the right size and alignment.  The rules are
1555   // somewhat different here for ms_struct structs.
1556   if (IsMsStruct) {
1557     // If it's not a zero-width bitfield, and we can fit the bitfield
1558     // into the active storage unit (and we haven't already decided to
1559     // start a new storage unit), just do so, regardless of any other
1560     // other consideration.  Otherwise, round up to the right alignment.
1561     if (FieldSize == 0 || FieldSize > UnfilledBitsInLastUnit) {
1562       FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
1563       UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1564                                                      UnpackedFieldAlign);
1565       UnfilledBitsInLastUnit = 0;
1566     }
1567 
1568   } else {
1569     // #pragma pack, with any value, suppresses the insertion of padding.
1570     bool AllowPadding = MaxFieldAlignment.isZero();
1571 
1572     // Compute the real offset.
1573     if (FieldSize == 0 ||
1574         (AllowPadding &&
1575          (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)) {
1576       FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
1577     }
1578 
1579     // Repeat the computation for diagnostic purposes.
1580     if (FieldSize == 0 ||
1581         (AllowPadding &&
1582          (UnpackedFieldOffset & (UnpackedFieldAlign-1)) + FieldSize > TypeSize))
1583       UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1584                                                      UnpackedFieldAlign);
1585   }
1586 
1587   // If we're using external layout, give the external layout a chance
1588   // to override this information.
1589   if (ExternalLayout)
1590     FieldOffset = updateExternalFieldOffset(D, FieldOffset);
1591 
1592   // Okay, place the bitfield at the calculated offset.
1593   FieldOffsets.push_back(FieldOffset);
1594 
1595   // Bookkeeping:
1596 
1597   // Anonymous members don't affect the overall record alignment,
1598   // except on targets where they do.
1599   if (!IsMsStruct &&
1600       !Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
1601       !D->getIdentifier())
1602     FieldAlign = UnpackedFieldAlign = 1;
1603 
1604   // Diagnose differences in layout due to padding or packing.
1605   if (!ExternalLayout)
1606     CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset,
1607                       UnpackedFieldAlign, FieldPacked, D);
1608 
1609   // Update DataSize to include the last byte containing (part of) the bitfield.
1610 
1611   // For unions, this is just a max operation, as usual.
1612   if (IsUnion) {
1613     // FIXME: I think FieldSize should be TypeSize here.
1614     setDataSize(std::max(getDataSizeInBits(), FieldSize));
1615 
1616   // For non-zero-width bitfields in ms_struct structs, allocate a new
1617   // storage unit if necessary.
1618   } else if (IsMsStruct && FieldSize) {
1619     // We should have cleared UnfilledBitsInLastUnit in every case
1620     // where we changed storage units.
1621     if (!UnfilledBitsInLastUnit) {
1622       setDataSize(FieldOffset + TypeSize);
1623       UnfilledBitsInLastUnit = TypeSize;
1624     }
1625     UnfilledBitsInLastUnit -= FieldSize;
1626     LastBitfieldTypeSize = TypeSize;
1627 
1628   // Otherwise, bump the data size up to include the bitfield,
1629   // including padding up to char alignment, and then remember how
1630   // bits we didn't use.
1631   } else {
1632     uint64_t NewSizeInBits = FieldOffset + FieldSize;
1633     uint64_t CharAlignment = Context.getTargetInfo().getCharAlign();
1634     setDataSize(llvm::RoundUpToAlignment(NewSizeInBits, CharAlignment));
1635     UnfilledBitsInLastUnit = getDataSizeInBits() - NewSizeInBits;
1636 
1637     // The only time we can get here for an ms_struct is if this is a
1638     // zero-width bitfield, which doesn't count as anything for the
1639     // purposes of unfilled bits.
1640     LastBitfieldTypeSize = 0;
1641   }
1642 
1643   // Update the size.
1644   setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1645 
1646   // Remember max struct/class alignment.
1647   UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign),
1648                   Context.toCharUnitsFromBits(UnpackedFieldAlign));
1649 }
1650 
1651 void RecordLayoutBuilder::LayoutField(const FieldDecl *D) {
1652   if (D->isBitField()) {
1653     LayoutBitField(D);
1654     return;
1655   }
1656 
1657   uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastUnit;
1658 
1659   // Reset the unfilled bits.
1660   UnfilledBitsInLastUnit = 0;
1661   LastBitfieldTypeSize = 0;
1662 
1663   bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
1664   CharUnits FieldOffset =
1665     IsUnion ? CharUnits::Zero() : getDataSize();
1666   CharUnits FieldSize;
1667   CharUnits FieldAlign;
1668 
1669   if (D->getType()->isIncompleteArrayType()) {
1670     // This is a flexible array member; we can't directly
1671     // query getTypeInfo about these, so we figure it out here.
1672     // Flexible array members don't have any size, but they
1673     // have to be aligned appropriately for their element type.
1674     FieldSize = CharUnits::Zero();
1675     const ArrayType* ATy = Context.getAsArrayType(D->getType());
1676     FieldAlign = Context.getTypeAlignInChars(ATy->getElementType());
1677   } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) {
1678     unsigned AS = RT->getPointeeType().getAddressSpace();
1679     FieldSize =
1680       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(AS));
1681     FieldAlign =
1682       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(AS));
1683   } else {
1684     std::pair<CharUnits, CharUnits> FieldInfo =
1685       Context.getTypeInfoInChars(D->getType());
1686     FieldSize = FieldInfo.first;
1687     FieldAlign = FieldInfo.second;
1688 
1689     if (IsMsStruct) {
1690       // If MS bitfield layout is required, figure out what type is being
1691       // laid out and align the field to the width of that type.
1692 
1693       // Resolve all typedefs down to their base type and round up the field
1694       // alignment if necessary.
1695       QualType T = Context.getBaseElementType(D->getType());
1696       if (const BuiltinType *BTy = T->getAs<BuiltinType>()) {
1697         CharUnits TypeSize = Context.getTypeSizeInChars(BTy);
1698         if (TypeSize > FieldAlign)
1699           FieldAlign = TypeSize;
1700       }
1701     }
1702   }
1703 
1704   // The align if the field is not packed. This is to check if the attribute
1705   // was unnecessary (-Wpacked).
1706   CharUnits UnpackedFieldAlign = FieldAlign;
1707   CharUnits UnpackedFieldOffset = FieldOffset;
1708 
1709   if (FieldPacked)
1710     FieldAlign = CharUnits::One();
1711   CharUnits MaxAlignmentInChars =
1712     Context.toCharUnitsFromBits(D->getMaxAlignment());
1713   FieldAlign = std::max(FieldAlign, MaxAlignmentInChars);
1714   UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars);
1715 
1716   // The maximum field alignment overrides the aligned attribute.
1717   if (!MaxFieldAlignment.isZero()) {
1718     FieldAlign = std::min(FieldAlign, MaxFieldAlignment);
1719     UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment);
1720   }
1721 
1722   // Round up the current record size to the field's alignment boundary.
1723   FieldOffset = FieldOffset.RoundUpToAlignment(FieldAlign);
1724   UnpackedFieldOffset =
1725     UnpackedFieldOffset.RoundUpToAlignment(UnpackedFieldAlign);
1726 
1727   if (ExternalLayout) {
1728     FieldOffset = Context.toCharUnitsFromBits(
1729                     updateExternalFieldOffset(D, Context.toBits(FieldOffset)));
1730 
1731     if (!IsUnion && EmptySubobjects) {
1732       // Record the fact that we're placing a field at this offset.
1733       bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset);
1734       (void)Allowed;
1735       assert(Allowed && "Externally-placed field cannot be placed here");
1736     }
1737   } else {
1738     if (!IsUnion && EmptySubobjects) {
1739       // Check if we can place the field at this offset.
1740       while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) {
1741         // We couldn't place the field at the offset. Try again at a new offset.
1742         FieldOffset += FieldAlign;
1743       }
1744     }
1745   }
1746 
1747   // Place this field at the current location.
1748   FieldOffsets.push_back(Context.toBits(FieldOffset));
1749 
1750   if (!ExternalLayout)
1751     CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset,
1752                       Context.toBits(UnpackedFieldOffset),
1753                       Context.toBits(UnpackedFieldAlign), FieldPacked, D);
1754 
1755   // Reserve space for this field.
1756   uint64_t FieldSizeInBits = Context.toBits(FieldSize);
1757   if (IsUnion)
1758     setDataSize(std::max(getDataSizeInBits(), FieldSizeInBits));
1759   else
1760     setDataSize(FieldOffset + FieldSize);
1761 
1762   // Update the size.
1763   setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1764 
1765   // Remember max struct/class alignment.
1766   UpdateAlignment(FieldAlign, UnpackedFieldAlign);
1767 }
1768 
1769 void RecordLayoutBuilder::FinishLayout(const NamedDecl *D) {
1770   // In C++, records cannot be of size 0.
1771   if (Context.getLangOpts().CPlusPlus && getSizeInBits() == 0) {
1772     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
1773       // Compatibility with gcc requires a class (pod or non-pod)
1774       // which is not empty but of size 0; such as having fields of
1775       // array of zero-length, remains of Size 0
1776       if (RD->isEmpty())
1777         setSize(CharUnits::One());
1778     }
1779     else
1780       setSize(CharUnits::One());
1781   }
1782 
1783   // Finally, round the size of the record up to the alignment of the
1784   // record itself.
1785   uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastUnit;
1786   uint64_t UnpackedSizeInBits =
1787   llvm::RoundUpToAlignment(getSizeInBits(),
1788                            Context.toBits(UnpackedAlignment));
1789   CharUnits UnpackedSize = Context.toCharUnitsFromBits(UnpackedSizeInBits);
1790   uint64_t RoundedSize
1791     = llvm::RoundUpToAlignment(getSizeInBits(), Context.toBits(Alignment));
1792 
1793   if (ExternalLayout) {
1794     // If we're inferring alignment, and the external size is smaller than
1795     // our size after we've rounded up to alignment, conservatively set the
1796     // alignment to 1.
1797     if (InferAlignment && ExternalSize < RoundedSize) {
1798       Alignment = CharUnits::One();
1799       InferAlignment = false;
1800     }
1801     setSize(ExternalSize);
1802     return;
1803   }
1804 
1805   // Set the size to the final size.
1806   setSize(RoundedSize);
1807 
1808   unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
1809   if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1810     // Warn if padding was introduced to the struct/class/union.
1811     if (getSizeInBits() > UnpaddedSize) {
1812       unsigned PadSize = getSizeInBits() - UnpaddedSize;
1813       bool InBits = true;
1814       if (PadSize % CharBitNum == 0) {
1815         PadSize = PadSize / CharBitNum;
1816         InBits = false;
1817       }
1818       Diag(RD->getLocation(), diag::warn_padded_struct_size)
1819           << Context.getTypeDeclType(RD)
1820           << PadSize
1821           << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
1822     }
1823 
1824     // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
1825     // bother since there won't be alignment issues.
1826     if (Packed && UnpackedAlignment > CharUnits::One() &&
1827         getSize() == UnpackedSize)
1828       Diag(D->getLocation(), diag::warn_unnecessary_packed)
1829           << Context.getTypeDeclType(RD);
1830   }
1831 }
1832 
1833 void RecordLayoutBuilder::UpdateAlignment(CharUnits NewAlignment,
1834                                           CharUnits UnpackedNewAlignment) {
1835   // The alignment is not modified when using 'mac68k' alignment or when
1836   // we have an externally-supplied layout that also provides overall alignment.
1837   if (IsMac68kAlign || (ExternalLayout && !InferAlignment))
1838     return;
1839 
1840   if (NewAlignment > Alignment) {
1841     assert(llvm::isPowerOf2_32(NewAlignment.getQuantity() &&
1842            "Alignment not a power of 2"));
1843     Alignment = NewAlignment;
1844   }
1845 
1846   if (UnpackedNewAlignment > UnpackedAlignment) {
1847     assert(llvm::isPowerOf2_32(UnpackedNewAlignment.getQuantity() &&
1848            "Alignment not a power of 2"));
1849     UnpackedAlignment = UnpackedNewAlignment;
1850   }
1851 }
1852 
1853 uint64_t
1854 RecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field,
1855                                                uint64_t ComputedOffset) {
1856   assert(ExternalFieldOffsets.find(Field) != ExternalFieldOffsets.end() &&
1857          "Field does not have an external offset");
1858 
1859   uint64_t ExternalFieldOffset = ExternalFieldOffsets[Field];
1860 
1861   if (InferAlignment && ExternalFieldOffset < ComputedOffset) {
1862     // The externally-supplied field offset is before the field offset we
1863     // computed. Assume that the structure is packed.
1864     Alignment = CharUnits::One();
1865     InferAlignment = false;
1866   }
1867 
1868   // Use the externally-supplied field offset.
1869   return ExternalFieldOffset;
1870 }
1871 
1872 /// \brief Get diagnostic %select index for tag kind for
1873 /// field padding diagnostic message.
1874 /// WARNING: Indexes apply to particular diagnostics only!
1875 ///
1876 /// \returns diagnostic %select index.
1877 static unsigned getPaddingDiagFromTagKind(TagTypeKind Tag) {
1878   switch (Tag) {
1879   case TTK_Struct: return 0;
1880   case TTK_Interface: return 1;
1881   case TTK_Class: return 2;
1882   default: llvm_unreachable("Invalid tag kind for field padding diagnostic!");
1883   }
1884 }
1885 
1886 void RecordLayoutBuilder::CheckFieldPadding(uint64_t Offset,
1887                                             uint64_t UnpaddedOffset,
1888                                             uint64_t UnpackedOffset,
1889                                             unsigned UnpackedAlign,
1890                                             bool isPacked,
1891                                             const FieldDecl *D) {
1892   // We let objc ivars without warning, objc interfaces generally are not used
1893   // for padding tricks.
1894   if (isa<ObjCIvarDecl>(D))
1895     return;
1896 
1897   // Don't warn about structs created without a SourceLocation.  This can
1898   // be done by clients of the AST, such as codegen.
1899   if (D->getLocation().isInvalid())
1900     return;
1901 
1902   unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
1903 
1904   // Warn if padding was introduced to the struct/class.
1905   if (!IsUnion && Offset > UnpaddedOffset) {
1906     unsigned PadSize = Offset - UnpaddedOffset;
1907     bool InBits = true;
1908     if (PadSize % CharBitNum == 0) {
1909       PadSize = PadSize / CharBitNum;
1910       InBits = false;
1911     }
1912     if (D->getIdentifier())
1913       Diag(D->getLocation(), diag::warn_padded_struct_field)
1914           << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
1915           << Context.getTypeDeclType(D->getParent())
1916           << PadSize
1917           << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1) // plural or not
1918           << D->getIdentifier();
1919     else
1920       Diag(D->getLocation(), diag::warn_padded_struct_anon_field)
1921           << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
1922           << Context.getTypeDeclType(D->getParent())
1923           << PadSize
1924           << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
1925   }
1926 
1927   // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
1928   // bother since there won't be alignment issues.
1929   if (isPacked && UnpackedAlign > CharBitNum && Offset == UnpackedOffset)
1930     Diag(D->getLocation(), diag::warn_unnecessary_packed)
1931         << D->getIdentifier();
1932 }
1933 
1934 static const CXXMethodDecl *computeKeyFunction(ASTContext &Context,
1935                                                const CXXRecordDecl *RD) {
1936   // If a class isn't polymorphic it doesn't have a key function.
1937   if (!RD->isPolymorphic())
1938     return 0;
1939 
1940   // A class that is not externally visible doesn't have a key function. (Or
1941   // at least, there's no point to assigning a key function to such a class;
1942   // this doesn't affect the ABI.)
1943   if (!RD->isExternallyVisible())
1944     return 0;
1945 
1946   // Template instantiations don't have key functions per Itanium C++ ABI 5.2.6.
1947   // Same behavior as GCC.
1948   TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
1949   if (TSK == TSK_ImplicitInstantiation ||
1950       TSK == TSK_ExplicitInstantiationDeclaration ||
1951       TSK == TSK_ExplicitInstantiationDefinition)
1952     return 0;
1953 
1954   bool allowInlineFunctions =
1955     Context.getTargetInfo().getCXXABI().canKeyFunctionBeInline();
1956 
1957   for (const auto *MD : RD->methods()) {
1958     if (!MD->isVirtual())
1959       continue;
1960 
1961     if (MD->isPure())
1962       continue;
1963 
1964     // Ignore implicit member functions, they are always marked as inline, but
1965     // they don't have a body until they're defined.
1966     if (MD->isImplicit())
1967       continue;
1968 
1969     if (MD->isInlineSpecified())
1970       continue;
1971 
1972     if (MD->hasInlineBody())
1973       continue;
1974 
1975     // Ignore inline deleted or defaulted functions.
1976     if (!MD->isUserProvided())
1977       continue;
1978 
1979     // In certain ABIs, ignore functions with out-of-line inline definitions.
1980     if (!allowInlineFunctions) {
1981       const FunctionDecl *Def;
1982       if (MD->hasBody(Def) && Def->isInlineSpecified())
1983         continue;
1984     }
1985 
1986     // We found it.
1987     return MD;
1988   }
1989 
1990   return 0;
1991 }
1992 
1993 DiagnosticBuilder
1994 RecordLayoutBuilder::Diag(SourceLocation Loc, unsigned DiagID) {
1995   return Context.getDiagnostics().Report(Loc, DiagID);
1996 }
1997 
1998 /// Does the target C++ ABI require us to skip over the tail-padding
1999 /// of the given class (considering it as a base class) when allocating
2000 /// objects?
2001 static bool mustSkipTailPadding(TargetCXXABI ABI, const CXXRecordDecl *RD) {
2002   switch (ABI.getTailPaddingUseRules()) {
2003   case TargetCXXABI::AlwaysUseTailPadding:
2004     return false;
2005 
2006   case TargetCXXABI::UseTailPaddingUnlessPOD03:
2007     // FIXME: To the extent that this is meant to cover the Itanium ABI
2008     // rules, we should implement the restrictions about over-sized
2009     // bitfields:
2010     //
2011     // http://mentorembedded.github.com/cxx-abi/abi.html#POD :
2012     //   In general, a type is considered a POD for the purposes of
2013     //   layout if it is a POD type (in the sense of ISO C++
2014     //   [basic.types]). However, a POD-struct or POD-union (in the
2015     //   sense of ISO C++ [class]) with a bitfield member whose
2016     //   declared width is wider than the declared type of the
2017     //   bitfield is not a POD for the purpose of layout.  Similarly,
2018     //   an array type is not a POD for the purpose of layout if the
2019     //   element type of the array is not a POD for the purpose of
2020     //   layout.
2021     //
2022     //   Where references to the ISO C++ are made in this paragraph,
2023     //   the Technical Corrigendum 1 version of the standard is
2024     //   intended.
2025     return RD->isPOD();
2026 
2027   case TargetCXXABI::UseTailPaddingUnlessPOD11:
2028     // This is equivalent to RD->getTypeForDecl().isCXX11PODType(),
2029     // but with a lot of abstraction penalty stripped off.  This does
2030     // assume that these properties are set correctly even in C++98
2031     // mode; fortunately, that is true because we want to assign
2032     // consistently semantics to the type-traits intrinsics (or at
2033     // least as many of them as possible).
2034     return RD->isTrivial() && RD->isStandardLayout();
2035   }
2036 
2037   llvm_unreachable("bad tail-padding use kind");
2038 }
2039 
2040 static bool isMsLayout(const RecordDecl* D) {
2041   return D->getASTContext().getTargetInfo().getCXXABI().isMicrosoft();
2042 }
2043 
2044 // This section contains an implementation of struct layout that is, up to the
2045 // included tests, compatible with cl.exe (2013).  The layout produced is
2046 // significantly different than those produced by the Itanium ABI.  Here we note
2047 // the most important differences.
2048 //
2049 // * The alignment of bitfields in unions is ignored when computing the
2050 //   alignment of the union.
2051 // * The existence of zero-width bitfield that occurs after anything other than
2052 //   a non-zero length bitfield is ignored.
2053 // * There is no explicit primary base for the purposes of layout.  All bases
2054 //   with vfptrs are laid out first, followed by all bases without vfptrs.
2055 // * The Itanium equivalent vtable pointers are split into a vfptr (virtual
2056 //   function pointer) and a vbptr (virtual base pointer).  They can each be
2057 //   shared with a, non-virtual bases. These bases need not be the same.  vfptrs
2058 //   always occur at offset 0.  vbptrs can occur at an arbitrary offset and are
2059 //   placed after the lexiographically last non-virtual base.  This placement
2060 //   is always before fields but can be in the middle of the non-virtual bases
2061 //   due to the two-pass layout scheme for non-virtual-bases.
2062 // * Virtual bases sometimes require a 'vtordisp' field that is laid out before
2063 //   the virtual base and is used in conjunction with virtual overrides during
2064 //   construction and destruction.  This is always a 4 byte value and is used as
2065 //   an alternative to constructor vtables.
2066 // * vtordisps are allocated in a block of memory with size and alignment equal
2067 //   to the alignment of the completed structure (before applying __declspec(
2068 //   align())).  The vtordisp always occur at the end of the allocation block,
2069 //   immediately prior to the virtual base.
2070 // * vfptrs are injected after all bases and fields have been laid out.  In
2071 //   order to guarantee proper alignment of all fields, the vfptr injection
2072 //   pushes all bases and fields back by the alignment imposed by those bases
2073 //   and fields.  This can potentially add a significant amount of padding.
2074 //   vfptrs are always injected at offset 0.
2075 // * vbptrs are injected after all bases and fields have been laid out.  In
2076 //   order to guarantee proper alignment of all fields, the vfptr injection
2077 //   pushes all bases and fields back by the alignment imposed by those bases
2078 //   and fields.  This can potentially add a significant amount of padding.
2079 //   vbptrs are injected immediately after the last non-virtual base as
2080 //   lexiographically ordered in the code.  If this site isn't pointer aligned
2081 //   the vbptr is placed at the next properly aligned location.  Enough padding
2082 //   is added to guarantee a fit.
2083 // * The last zero sized non-virtual base can be placed at the end of the
2084 //   struct (potentially aliasing another object), or may alias with the first
2085 //   field, even if they are of the same type.
2086 // * The last zero size virtual base may be placed at the end of the struct
2087 //   potentially aliasing another object.
2088 // * The ABI attempts to avoid aliasing of zero sized bases by adding padding
2089 //   between bases or vbases with specific properties.  The criteria for
2090 //   additional padding between two bases is that the first base is zero sized
2091 //   or ends with a zero sized subobject and the second base is zero sized or
2092 //   trails with a zero sized base or field (sharing of vfptrs can reorder the
2093 //   layout of the so the leading base is not always the first one declared).
2094 //   This rule does take into account fields that are not records, so padding
2095 //   will occur even if the last field is, e.g. an int. The padding added for
2096 //   bases is 1 byte.  The padding added between vbases depends on the alignment
2097 //   of the object but is at least 4 bytes (in both 32 and 64 bit modes).
2098 // * There is no concept of non-virtual alignment, non-virtual alignment and
2099 //   alignment are always identical.
2100 // * There is a distinction between alignment and required alignment.
2101 //   __declspec(align) changes the required alignment of a struct.  This
2102 //   alignment is _always_ obeyed, even in the presence of #pragma pack. A
2103 //   record inherites required alignment from all of its fields an bases.
2104 // * __declspec(align) on bitfields has the effect of changing the bitfield's
2105 //   alignment instead of its required alignment.  This is the only known way
2106 //   to make the alignment of a struct bigger than 8.  Interestingly enough
2107 //   this alignment is also immune to the effects of #pragma pack and can be
2108 //   used to create structures with large alignment under #pragma pack.
2109 //   However, because it does not impact required alignment, such a structure,
2110 //   when used as a field or base, will not be aligned if #pragma pack is
2111 //   still active at the time of use.
2112 //
2113 // Known incompatiblities:
2114 // * all: #pragma pack between fields in a record
2115 // * 2010 and back: If the last field in a record is a bitfield, every object
2116 //   laid out after the record will have extra padding inserted before it.  The
2117 //   extra padding will have size equal to the size of the storage class of the
2118 //   bitfield.  0 sized bitfields don't exhibit this behavior and the extra
2119 //   padding can be avoided by adding a 0 sized bitfield after the non-zero-
2120 //   sized bitfield.
2121 // * 2012 and back: In 64-bit mode, if the alignment of a record is 16 or
2122 //   greater due to __declspec(align()) then a second layout phase occurs after
2123 //   The locations of the vf and vb pointers are known.  This layout phase
2124 //   suffers from the "last field is a bitfield" bug in 2010 and results in
2125 //   _every_ field getting padding put in front of it, potentially including the
2126 //   vfptr, leaving the vfprt at a non-zero location which results in a fault if
2127 //   anything tries to read the vftbl.  The second layout phase also treats
2128 //   bitfields as seperate entities and gives them each storage rather than
2129 //   packing them.  Additionally, because this phase appears to perform a
2130 //   (an unstable) sort on the members before laying them out and because merged
2131 //   bitfields have the same address, the bitfields end up in whatever order
2132 //   the sort left them in, a behavior we could never hope to replicate.
2133 
2134 namespace {
2135 struct MicrosoftRecordLayoutBuilder {
2136   struct ElementInfo {
2137     CharUnits Size;
2138     CharUnits Alignment;
2139   };
2140   typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
2141   MicrosoftRecordLayoutBuilder(const ASTContext &Context) : Context(Context) {}
2142 private:
2143   MicrosoftRecordLayoutBuilder(const MicrosoftRecordLayoutBuilder &)
2144   LLVM_DELETED_FUNCTION;
2145   void operator=(const MicrosoftRecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
2146 public:
2147   void layout(const RecordDecl *RD);
2148   void cxxLayout(const CXXRecordDecl *RD);
2149   /// \brief Initializes size and alignment and honors some flags.
2150   void initializeLayout(const RecordDecl *RD);
2151   /// \brief Initialized C++ layout, compute alignment and virtual alignment and
2152   /// existence of vfptrs and vbptrs.  Alignment is needed before the vfptr is
2153   /// laid out.
2154   void initializeCXXLayout(const CXXRecordDecl *RD);
2155   void layoutNonVirtualBases(const CXXRecordDecl *RD);
2156   void layoutNonVirtualBase(const CXXRecordDecl *BaseDecl,
2157                             const ASTRecordLayout &BaseLayout,
2158                             const ASTRecordLayout *&PreviousBaseLayout);
2159   void injectVFPtr(const CXXRecordDecl *RD);
2160   void injectVBPtr(const CXXRecordDecl *RD);
2161   /// \brief Lays out the fields of the record.  Also rounds size up to
2162   /// alignment.
2163   void layoutFields(const RecordDecl *RD);
2164   void layoutField(const FieldDecl *FD);
2165   void layoutBitField(const FieldDecl *FD);
2166   /// \brief Lays out a single zero-width bit-field in the record and handles
2167   /// special cases associated with zero-width bit-fields.
2168   void layoutZeroWidthBitField(const FieldDecl *FD);
2169   void layoutVirtualBases(const CXXRecordDecl *RD);
2170   void finalizeLayout(const RecordDecl *RD);
2171   /// \brief Gets the size and alignment of a base taking pragma pack and
2172   /// __declspec(align) into account.
2173   ElementInfo getAdjustedElementInfo(const ASTRecordLayout &Layout);
2174   /// \brief Gets the size and alignment of a field taking pragma  pack and
2175   /// __declspec(align) into account.  It also updates RequiredAlignment as a
2176   /// side effect because it is most convenient to do so here.
2177   ElementInfo getAdjustedElementInfo(const FieldDecl *FD);
2178   /// \brief Places a field at an offset in CharUnits.
2179   void placeFieldAtOffset(CharUnits FieldOffset) {
2180     FieldOffsets.push_back(Context.toBits(FieldOffset));
2181   }
2182   /// \brief Places a bitfield at a bit offset.
2183   void placeFieldAtBitOffset(uint64_t FieldOffset) {
2184     FieldOffsets.push_back(FieldOffset);
2185   }
2186   /// \brief Compute the set of virtual bases for which vtordisps are required.
2187   llvm::SmallPtrSet<const CXXRecordDecl *, 2>
2188   computeVtorDispSet(const CXXRecordDecl *RD);
2189   const ASTContext &Context;
2190   /// \brief The size of the record being laid out.
2191   CharUnits Size;
2192   /// \brief The non-virtual size of the record layout.
2193   CharUnits NonVirtualSize;
2194   /// \brief The data size of the record layout.
2195   CharUnits DataSize;
2196   /// \brief The current alignment of the record layout.
2197   CharUnits Alignment;
2198   /// \brief The maximum allowed field alignment. This is set by #pragma pack.
2199   CharUnits MaxFieldAlignment;
2200   /// \brief The alignment that this record must obey.  This is imposed by
2201   /// __declspec(align()) on the record itself or one of its fields or bases.
2202   CharUnits RequiredAlignment;
2203   /// \brief The size of the allocation of the currently active bitfield.
2204   /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield
2205   /// is true.
2206   CharUnits CurrentBitfieldSize;
2207   /// \brief Offset to the virtual base table pointer (if one exists).
2208   CharUnits VBPtrOffset;
2209   /// \brief The size and alignment info of a pointer.
2210   ElementInfo PointerInfo;
2211   /// \brief The primary base class (if one exists).
2212   const CXXRecordDecl *PrimaryBase;
2213   /// \brief The class we share our vb-pointer with.
2214   const CXXRecordDecl *SharedVBPtrBase;
2215   /// \brief The collection of field offsets.
2216   SmallVector<uint64_t, 16> FieldOffsets;
2217   /// \brief Base classes and their offsets in the record.
2218   BaseOffsetsMapTy Bases;
2219   /// \brief virtual base classes and their offsets in the record.
2220   ASTRecordLayout::VBaseOffsetsMapTy VBases;
2221   /// \brief The number of remaining bits in our last bitfield allocation.
2222   /// This value isn't meaningful unless LastFieldIsNonZeroWidthBitfield is
2223   /// true.
2224   unsigned RemainingBitsInField;
2225   bool IsUnion : 1;
2226   /// \brief True if the last field laid out was a bitfield and was not 0
2227   /// width.
2228   bool LastFieldIsNonZeroWidthBitfield : 1;
2229   /// \brief True if the class has its own vftable pointer.
2230   bool HasOwnVFPtr : 1;
2231   /// \brief True if the class has a vbtable pointer.
2232   bool HasVBPtr : 1;
2233   /// \brief True if the last sub-object within the type is zero sized or the
2234   /// object itself is zero sized.  This *does not* count members that are not
2235   /// records.  Only used for MS-ABI.
2236   bool EndsWithZeroSizedObject : 1;
2237   /// \brief True if this class is zero sized or first base is zero sized or
2238   /// has this property.  Only used for MS-ABI.
2239   bool LeadsWithZeroSizedBase : 1;
2240 };
2241 } // namespace
2242 
2243 MicrosoftRecordLayoutBuilder::ElementInfo
2244 MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
2245     const ASTRecordLayout &Layout) {
2246   ElementInfo Info;
2247   Info.Alignment = Layout.getAlignment();
2248   // Respect pragma pack.
2249   if (!MaxFieldAlignment.isZero())
2250     Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
2251   // Track zero-sized subobjects here where it's already available.
2252   EndsWithZeroSizedObject = Layout.hasZeroSizedSubObject();
2253   // Respect required alignment, this is necessary because we may have adjusted
2254   // the alignment in the case of pragam pack.  Note that the required alignment
2255   // doesn't actually apply to the struct alignment at this point.
2256   Alignment = std::max(Alignment, Info.Alignment);
2257   RequiredAlignment = std::max(RequiredAlignment, Layout.getRequiredAlignment());
2258   Info.Alignment = std::max(Info.Alignment, Layout.getRequiredAlignment());
2259   Info.Size = Layout.getNonVirtualSize();
2260   return Info;
2261 }
2262 
2263 MicrosoftRecordLayoutBuilder::ElementInfo
2264 MicrosoftRecordLayoutBuilder::getAdjustedElementInfo(
2265     const FieldDecl *FD) {
2266   ElementInfo Info;
2267   std::tie(Info.Size, Info.Alignment) =
2268       Context.getTypeInfoInChars(FD->getType());
2269   // Respect align attributes.
2270   CharUnits FieldRequiredAlignment =
2271       Context.toCharUnitsFromBits(FD->getMaxAlignment());
2272   // Respect attributes applied to subobjects of the field.
2273   if (FD->isBitField())
2274     // For some reason __declspec align impacts alignment rather than required
2275     // alignment when it is applied to bitfields.
2276     Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
2277   else {
2278     if (auto RT =
2279             FD->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
2280       auto const &Layout = Context.getASTRecordLayout(RT->getDecl());
2281       EndsWithZeroSizedObject = Layout.hasZeroSizedSubObject();
2282       FieldRequiredAlignment = std::max(FieldRequiredAlignment,
2283                                         Layout.getRequiredAlignment());
2284     }
2285     // Capture required alignment as a side-effect.
2286     RequiredAlignment = std::max(RequiredAlignment, FieldRequiredAlignment);
2287   }
2288   // Respect pragma pack, attribute pack and declspec align
2289   if (!MaxFieldAlignment.isZero())
2290     Info.Alignment = std::min(Info.Alignment, MaxFieldAlignment);
2291   if (FD->hasAttr<PackedAttr>())
2292     Info.Alignment = CharUnits::One();
2293   Info.Alignment = std::max(Info.Alignment, FieldRequiredAlignment);
2294   return Info;
2295 }
2296 
2297 void MicrosoftRecordLayoutBuilder::layout(const RecordDecl *RD) {
2298   initializeLayout(RD);
2299   layoutFields(RD);
2300   DataSize = Size = Size.RoundUpToAlignment(Alignment);
2301   RequiredAlignment = std::max(
2302       RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
2303   finalizeLayout(RD);
2304 }
2305 
2306 void MicrosoftRecordLayoutBuilder::cxxLayout(const CXXRecordDecl *RD) {
2307   initializeLayout(RD);
2308   initializeCXXLayout(RD);
2309   layoutNonVirtualBases(RD);
2310   layoutFields(RD);
2311   injectVBPtr(RD);
2312   injectVFPtr(RD);
2313   if (HasOwnVFPtr || (HasVBPtr && !SharedVBPtrBase))
2314     Alignment = std::max(Alignment, PointerInfo.Alignment);
2315   auto RoundingAlignment = Alignment;
2316   if (!MaxFieldAlignment.isZero())
2317     RoundingAlignment = std::min(RoundingAlignment, MaxFieldAlignment);
2318   NonVirtualSize = Size = Size.RoundUpToAlignment(RoundingAlignment);
2319   RequiredAlignment = std::max(
2320       RequiredAlignment, Context.toCharUnitsFromBits(RD->getMaxAlignment()));
2321   layoutVirtualBases(RD);
2322   finalizeLayout(RD);
2323 }
2324 
2325 void MicrosoftRecordLayoutBuilder::initializeLayout(const RecordDecl *RD) {
2326   IsUnion = RD->isUnion();
2327   Size = CharUnits::Zero();
2328   Alignment = CharUnits::One();
2329   // In 64-bit mode we always perform an alignment step after laying out vbases.
2330   // In 32-bit mode we do not.  The check to see if we need to perform alignment
2331   // checks the RequiredAlignment field and performs alignment if it isn't 0.
2332   RequiredAlignment = Context.getTargetInfo().getPointerWidth(0) == 64 ?
2333                       CharUnits::One() : CharUnits::Zero();
2334   // Compute the maximum field alignment.
2335   MaxFieldAlignment = CharUnits::Zero();
2336   // Honor the default struct packing maximum alignment flag.
2337   if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct)
2338       MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
2339   // Honor the packing attribute.  The MS-ABI ignores pragma pack if its larger
2340   // than the pointer size.
2341   if (const MaxFieldAlignmentAttr *MFAA = RD->getAttr<MaxFieldAlignmentAttr>()){
2342     unsigned PackedAlignment = MFAA->getAlignment();
2343     if (PackedAlignment <= Context.getTargetInfo().getPointerWidth(0))
2344       MaxFieldAlignment = Context.toCharUnitsFromBits(PackedAlignment);
2345   }
2346   // Packed attribute forces max field alignment to be 1.
2347   if (RD->hasAttr<PackedAttr>())
2348     MaxFieldAlignment = CharUnits::One();
2349 }
2350 
2351 void
2352 MicrosoftRecordLayoutBuilder::initializeCXXLayout(const CXXRecordDecl *RD) {
2353   EndsWithZeroSizedObject = false;
2354   LeadsWithZeroSizedBase = false;
2355   HasOwnVFPtr = false;
2356   HasVBPtr = false;
2357   PrimaryBase = 0;
2358   SharedVBPtrBase = 0;
2359   // Calculate pointer size and alignment.  These are used for vfptr and vbprt
2360   // injection.
2361   PointerInfo.Size =
2362       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
2363   PointerInfo.Alignment = PointerInfo.Size;
2364   // Respect pragma pack.
2365   if (!MaxFieldAlignment.isZero())
2366     PointerInfo.Alignment = std::min(PointerInfo.Alignment, MaxFieldAlignment);
2367 }
2368 
2369 void
2370 MicrosoftRecordLayoutBuilder::layoutNonVirtualBases(const CXXRecordDecl *RD) {
2371   // The MS-ABI lays out all bases that contain leading vfptrs before it lays
2372   // out any bases that do not contain vfptrs.  We implement this as two passes
2373   // over the bases.  This approach guarantees that the primary base is laid out
2374   // first.  We use these passes to calculate some additional aggregated
2375   // information about the bases, such as reqruied alignment and the presence of
2376   // zero sized members.
2377   const ASTRecordLayout* PreviousBaseLayout = 0;
2378   // Iterate through the bases and lay out the non-virtual ones.
2379   for (const auto &I : RD->bases()) {
2380     const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
2381     const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2382     // Mark and skip virtual bases.
2383     if (I.isVirtual()) {
2384       HasVBPtr = true;
2385       continue;
2386     }
2387     // Check fo a base to share a VBPtr with.
2388     if (!SharedVBPtrBase && BaseLayout.hasVBPtr()) {
2389       SharedVBPtrBase = BaseDecl;
2390       HasVBPtr = true;
2391     }
2392     // Only lay out bases with extendable VFPtrs on the first pass.
2393     if (!BaseLayout.hasExtendableVFPtr())
2394       continue;
2395     // If we don't have a primary base, this one qualifies.
2396     if (!PrimaryBase) {
2397       PrimaryBase = BaseDecl;
2398       LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
2399     }
2400     // Lay out the base.
2401     layoutNonVirtualBase(BaseDecl, BaseLayout, PreviousBaseLayout);
2402   }
2403   // Figure out if we need a fresh VFPtr for this class.
2404   if (!PrimaryBase && RD->isDynamicClass())
2405     for (CXXRecordDecl::method_iterator i = RD->method_begin(),
2406                                         e = RD->method_end();
2407          !HasOwnVFPtr && i != e; ++i)
2408       HasOwnVFPtr = i->isVirtual() && i->size_overridden_methods() == 0;
2409   // If we don't have a primary base then we have a leading object that could
2410   // itself lead with a zero-sized object, something we track.
2411   bool CheckLeadingLayout = !PrimaryBase;
2412   // Iterate through the bases and lay out the non-virtual ones.
2413   for (const auto &I : RD->bases()) {
2414     if (I.isVirtual())
2415       continue;
2416     const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
2417     const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2418     // Only lay out bases without extendable VFPtrs on the second pass.
2419     if (BaseLayout.hasExtendableVFPtr()) {
2420       VBPtrOffset = Bases[BaseDecl] + BaseLayout.getNonVirtualSize();
2421       continue;
2422     }
2423     // If this is the first layout, check to see if it leads with a zero sized
2424     // object.  If it does, so do we.
2425     if (CheckLeadingLayout) {
2426       CheckLeadingLayout = false;
2427       LeadsWithZeroSizedBase = BaseLayout.leadsWithZeroSizedBase();
2428     }
2429     // Lay out the base.
2430     layoutNonVirtualBase(BaseDecl, BaseLayout, PreviousBaseLayout);
2431     VBPtrOffset = Bases[BaseDecl] + BaseLayout.getNonVirtualSize();
2432   }
2433   // Set our VBPtroffset if we know it at this point.
2434   if (!HasVBPtr)
2435     VBPtrOffset = CharUnits::fromQuantity(-1);
2436   else if (SharedVBPtrBase) {
2437     const ASTRecordLayout &Layout = Context.getASTRecordLayout(SharedVBPtrBase);
2438     VBPtrOffset = Bases[SharedVBPtrBase] + Layout.getVBPtrOffset();
2439   }
2440 }
2441 
2442 void MicrosoftRecordLayoutBuilder::layoutNonVirtualBase(
2443     const CXXRecordDecl *BaseDecl,
2444     const ASTRecordLayout &BaseLayout,
2445     const ASTRecordLayout *&PreviousBaseLayout) {
2446   // Insert padding between two bases if the left first one is zero sized or
2447   // contains a zero sized subobject and the right is zero sized or one leads
2448   // with a zero sized base.
2449   if (PreviousBaseLayout && PreviousBaseLayout->hasZeroSizedSubObject() &&
2450       BaseLayout.leadsWithZeroSizedBase())
2451     Size++;
2452   ElementInfo Info = getAdjustedElementInfo(BaseLayout);
2453   CharUnits BaseOffset = Size.RoundUpToAlignment(Info.Alignment);
2454   Bases.insert(std::make_pair(BaseDecl, BaseOffset));
2455   Size = BaseOffset + BaseLayout.getNonVirtualSize();
2456   PreviousBaseLayout = &BaseLayout;
2457 }
2458 
2459 void MicrosoftRecordLayoutBuilder::layoutFields(const RecordDecl *RD) {
2460   LastFieldIsNonZeroWidthBitfield = false;
2461   for (const auto *Field : RD->fields())
2462     layoutField(Field);
2463 }
2464 
2465 void MicrosoftRecordLayoutBuilder::layoutField(const FieldDecl *FD) {
2466   if (FD->isBitField()) {
2467     layoutBitField(FD);
2468     return;
2469   }
2470   LastFieldIsNonZeroWidthBitfield = false;
2471   ElementInfo Info = getAdjustedElementInfo(FD);
2472   Alignment = std::max(Alignment, Info.Alignment);
2473   if (IsUnion) {
2474     placeFieldAtOffset(CharUnits::Zero());
2475     Size = std::max(Size, Info.Size);
2476   } else {
2477     CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
2478     placeFieldAtOffset(FieldOffset);
2479     Size = FieldOffset + Info.Size;
2480   }
2481 }
2482 
2483 void MicrosoftRecordLayoutBuilder::layoutBitField(const FieldDecl *FD) {
2484   unsigned Width = FD->getBitWidthValue(Context);
2485   if (Width == 0) {
2486     layoutZeroWidthBitField(FD);
2487     return;
2488   }
2489   ElementInfo Info = getAdjustedElementInfo(FD);
2490   // Clamp the bitfield to a containable size for the sake of being able
2491   // to lay them out.  Sema will throw an error.
2492   if (Width > Context.toBits(Info.Size))
2493     Width = Context.toBits(Info.Size);
2494   // Check to see if this bitfield fits into an existing allocation.  Note:
2495   // MSVC refuses to pack bitfields of formal types with different sizes
2496   // into the same allocation.
2497   if (!IsUnion && LastFieldIsNonZeroWidthBitfield &&
2498       CurrentBitfieldSize == Info.Size && Width <= RemainingBitsInField) {
2499     placeFieldAtBitOffset(Context.toBits(Size) - RemainingBitsInField);
2500     RemainingBitsInField -= Width;
2501     return;
2502   }
2503   LastFieldIsNonZeroWidthBitfield = true;
2504   CurrentBitfieldSize = Info.Size;
2505   if (IsUnion) {
2506     placeFieldAtOffset(CharUnits::Zero());
2507     Size = std::max(Size, Info.Size);
2508     // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
2509   } else {
2510     // Allocate a new block of memory and place the bitfield in it.
2511     CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
2512     placeFieldAtOffset(FieldOffset);
2513     Size = FieldOffset + Info.Size;
2514     Alignment = std::max(Alignment, Info.Alignment);
2515     RemainingBitsInField = Context.toBits(Info.Size) - Width;
2516   }
2517 }
2518 
2519 void
2520 MicrosoftRecordLayoutBuilder::layoutZeroWidthBitField(const FieldDecl *FD) {
2521   // Zero-width bitfields are ignored unless they follow a non-zero-width
2522   // bitfield.
2523   if (!LastFieldIsNonZeroWidthBitfield) {
2524     placeFieldAtOffset(IsUnion ? CharUnits::Zero() : Size);
2525     // TODO: Add a Sema warning that MS ignores alignment for zero
2526     // sized bitfields that occur after zero-size bitfields or non-bitfields.
2527     return;
2528   }
2529   LastFieldIsNonZeroWidthBitfield = false;
2530   ElementInfo Info = getAdjustedElementInfo(FD);
2531   if (IsUnion) {
2532     placeFieldAtOffset(CharUnits::Zero());
2533     Size = std::max(Size, Info.Size);
2534     // TODO: Add a Sema warning that MS ignores bitfield alignment in unions.
2535   } else {
2536     // Round up the current record size to the field's alignment boundary.
2537     CharUnits FieldOffset = Size.RoundUpToAlignment(Info.Alignment);
2538     placeFieldAtOffset(FieldOffset);
2539     Size = FieldOffset;
2540     Alignment = std::max(Alignment, Info.Alignment);
2541   }
2542 }
2543 
2544 void MicrosoftRecordLayoutBuilder::injectVBPtr(const CXXRecordDecl *RD) {
2545   if (!HasVBPtr || SharedVBPtrBase)
2546     return;
2547   // Inject the VBPointer at the injection site.
2548   CharUnits InjectionSite = VBPtrOffset;
2549   // But before we do, make sure it's properly aligned.
2550   VBPtrOffset = VBPtrOffset.RoundUpToAlignment(PointerInfo.Alignment);
2551   // Determine where the first field should be laid out after the vbptr.
2552   CharUnits FieldStart = VBPtrOffset + PointerInfo.Size;
2553   // Make sure that the amount we push the fields back by is a multiple of the
2554   // alignment.
2555   CharUnits Offset = (FieldStart - InjectionSite).RoundUpToAlignment(
2556       std::max(RequiredAlignment, Alignment));
2557   // Increase the size of the object and push back all fields by the offset
2558   // amount.
2559   Size += Offset;
2560   for (SmallVector<uint64_t, 16>::iterator i = FieldOffsets.begin(),
2561                                            e = FieldOffsets.end();
2562        i != e; ++i)
2563     *i += Context.toBits(Offset);
2564   for (BaseOffsetsMapTy::iterator i = Bases.begin(), e = Bases.end();
2565        i != e; ++i)
2566     if (i->second >= InjectionSite)
2567       i->second += Offset;
2568 }
2569 
2570 void MicrosoftRecordLayoutBuilder::injectVFPtr(const CXXRecordDecl *RD) {
2571   if (!HasOwnVFPtr)
2572     return;
2573   // Make sure that the amount we push the struct back by is a multiple of the
2574   // alignment.
2575   CharUnits Offset = PointerInfo.Size.RoundUpToAlignment(
2576       std::max(RequiredAlignment, Alignment));
2577   // Increase the size of the object and push back all fields, the vbptr and all
2578   // bases by the offset amount.
2579   Size += Offset;
2580   for (SmallVectorImpl<uint64_t>::iterator i = FieldOffsets.begin(),
2581                                            e = FieldOffsets.end();
2582        i != e; ++i)
2583     *i += Context.toBits(Offset);
2584   if (HasVBPtr)
2585     VBPtrOffset += Offset;
2586   for (BaseOffsetsMapTy::iterator i = Bases.begin(), e = Bases.end();
2587        i != e; ++i)
2588     i->second += Offset;
2589 }
2590 
2591 void MicrosoftRecordLayoutBuilder::layoutVirtualBases(const CXXRecordDecl *RD) {
2592   if (!HasVBPtr)
2593     return;
2594   // Vtordisps are always 4 bytes (even in 64-bit mode)
2595   CharUnits VtorDispSize = CharUnits::fromQuantity(4);
2596   CharUnits VtorDispAlignment = VtorDispSize;
2597   // vtordisps respect pragma pack.
2598   if (!MaxFieldAlignment.isZero())
2599     VtorDispAlignment = std::min(VtorDispAlignment, MaxFieldAlignment);
2600   // The alignment of the vtordisp is at least the required alignment of the
2601   // entire record.  This requirement may be present to support vtordisp
2602   // injection.
2603   for (const auto &I : RD->vbases()) {
2604     const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
2605     const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2606     RequiredAlignment =
2607         std::max(RequiredAlignment, BaseLayout.getRequiredAlignment());
2608   }
2609   VtorDispAlignment = std::max(VtorDispAlignment, RequiredAlignment);
2610   // Compute the vtordisp set.
2611   llvm::SmallPtrSet<const CXXRecordDecl *, 2> HasVtordispSet =
2612       computeVtorDispSet(RD);
2613   // Iterate through the virtual bases and lay them out.
2614   const ASTRecordLayout* PreviousBaseLayout = 0;
2615   for (const auto &I : RD->vbases()) {
2616     const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
2617     const ASTRecordLayout &BaseLayout = Context.getASTRecordLayout(BaseDecl);
2618     bool HasVtordisp = HasVtordispSet.count(BaseDecl);
2619     // Insert padding between two bases if the left first one is zero sized or
2620     // contains a zero sized subobject and the right is zero sized or one leads
2621     // with a zero sized base.  The padding between virtual bases is 4
2622     // bytes (in both 32 and 64 bits modes) and always involves rounding up to
2623     // the required alignment, we don't know why.
2624     if ((PreviousBaseLayout && PreviousBaseLayout->hasZeroSizedSubObject() &&
2625         BaseLayout.leadsWithZeroSizedBase()) || HasVtordisp)
2626       Size = Size.RoundUpToAlignment(VtorDispAlignment) + VtorDispSize;
2627     // Insert the virtual base.
2628     ElementInfo Info = getAdjustedElementInfo(BaseLayout);
2629     CharUnits BaseOffset = Size.RoundUpToAlignment(Info.Alignment);
2630     VBases.insert(std::make_pair(BaseDecl,
2631         ASTRecordLayout::VBaseInfo(BaseOffset, HasVtordisp)));
2632     Size = BaseOffset + BaseLayout.getNonVirtualSize();
2633     PreviousBaseLayout = &BaseLayout;
2634   }
2635 }
2636 
2637 void MicrosoftRecordLayoutBuilder::finalizeLayout(const RecordDecl *RD) {
2638   // Respect required alignment.  Note that in 32-bit mode Required alignment
2639   // may be 0 nad cause size not to be updated.
2640   DataSize = Size;
2641   if (!RequiredAlignment.isZero()) {
2642     Alignment = std::max(Alignment, RequiredAlignment);
2643     auto RoundingAlignment = Alignment;
2644     if (!MaxFieldAlignment.isZero())
2645       RoundingAlignment = std::min(RoundingAlignment, MaxFieldAlignment);
2646     RoundingAlignment = std::max(RoundingAlignment, RequiredAlignment);
2647     Size = Size.RoundUpToAlignment(RoundingAlignment);
2648   }
2649   // Zero-sized structures have size equal to their alignment.
2650   if (Size.isZero()) {
2651     EndsWithZeroSizedObject = true;
2652     LeadsWithZeroSizedBase = true;
2653     Size = Alignment;
2654   }
2655 }
2656 
2657 // Recursively walks the non-virtual bases of a class and determines if any of
2658 // them are in the bases with overridden methods set.
2659 static bool RequiresVtordisp(
2660     const llvm::SmallPtrSet<const CXXRecordDecl *, 2> &
2661         BasesWithOverriddenMethods,
2662     const CXXRecordDecl *RD) {
2663   if (BasesWithOverriddenMethods.count(RD))
2664     return true;
2665   // If any of a virtual bases non-virtual bases (recursively) requires a
2666   // vtordisp than so does this virtual base.
2667   for (const auto &I : RD->bases())
2668     if (!I.isVirtual() &&
2669         RequiresVtordisp(BasesWithOverriddenMethods,
2670                          I.getType()->getAsCXXRecordDecl()))
2671       return true;
2672   return false;
2673 }
2674 
2675 llvm::SmallPtrSet<const CXXRecordDecl *, 2>
2676 MicrosoftRecordLayoutBuilder::computeVtorDispSet(const CXXRecordDecl *RD) {
2677   llvm::SmallPtrSet<const CXXRecordDecl *, 2> HasVtordispSet;
2678 
2679   // /vd2 or #pragma vtordisp(2): Always use vtordisps for virtual bases with
2680   // vftables.
2681   if (RD->getMSVtorDispMode() == MSVtorDispAttr::ForVFTable) {
2682     for (const auto &I : RD->vbases()) {
2683       const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
2684       const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
2685       if (Layout.hasExtendableVFPtr())
2686         HasVtordispSet.insert(BaseDecl);
2687     }
2688     return HasVtordispSet;
2689   }
2690 
2691   // If any of our bases need a vtordisp for this type, so do we.  Check our
2692   // direct bases for vtordisp requirements.
2693   for (const auto &I : RD->bases()) {
2694     const CXXRecordDecl *BaseDecl = I.getType()->getAsCXXRecordDecl();
2695     const ASTRecordLayout &Layout = Context.getASTRecordLayout(BaseDecl);
2696     for (const auto &bi : Layout.getVBaseOffsetsMap())
2697       if (bi.second.hasVtorDisp())
2698         HasVtordispSet.insert(bi.first);
2699   }
2700   // We don't introduce any additional vtordisps if either:
2701   // * A user declared constructor or destructor aren't declared.
2702   // * #pragma vtordisp(0) or the /vd0 flag are in use.
2703   if ((!RD->hasUserDeclaredConstructor() && !RD->hasUserDeclaredDestructor()) ||
2704       RD->getMSVtorDispMode() == MSVtorDispAttr::Never)
2705     return HasVtordispSet;
2706   // /vd1 or #pragma vtordisp(1): Try to guess based on whether we think it's
2707   // possible for a partially constructed object with virtual base overrides to
2708   // escape a non-trivial constructor.
2709   assert(RD->getMSVtorDispMode() == MSVtorDispAttr::ForVBaseOverride);
2710   // Compute a set of base classes which define methods we override.  A virtual
2711   // base in this set will require a vtordisp.  A virtual base that transitively
2712   // contains one of these bases as a non-virtual base will also require a
2713   // vtordisp.
2714   llvm::SmallPtrSet<const CXXMethodDecl *, 8> Work;
2715   llvm::SmallPtrSet<const CXXRecordDecl *, 2> BasesWithOverriddenMethods;
2716   // Seed the working set with our non-destructor virtual methods.
2717   for (const auto *I : RD->methods())
2718     if (I->isVirtual() && !isa<CXXDestructorDecl>(I))
2719       Work.insert(I);
2720   while (!Work.empty()) {
2721     const CXXMethodDecl *MD = *Work.begin();
2722     CXXMethodDecl::method_iterator i = MD->begin_overridden_methods(),
2723                                    e = MD->end_overridden_methods();
2724     // If a virtual method has no-overrides it lives in its parent's vtable.
2725     if (i == e)
2726       BasesWithOverriddenMethods.insert(MD->getParent());
2727     else
2728       Work.insert(i, e);
2729     // We've finished processing this element, remove it from the working set.
2730     Work.erase(MD);
2731   }
2732   // For each of our virtual bases, check if it is in the set of overridden
2733   // bases or if it transitively contains a non-virtual base that is.
2734   for (const auto &I : RD->vbases()) {
2735     const CXXRecordDecl *BaseDecl =  I.getType()->getAsCXXRecordDecl();
2736     if (!HasVtordispSet.count(BaseDecl) &&
2737         RequiresVtordisp(BasesWithOverriddenMethods, BaseDecl))
2738       HasVtordispSet.insert(BaseDecl);
2739   }
2740   return HasVtordispSet;
2741 }
2742 
2743 /// \brief Get or compute information about the layout of the specified record
2744 /// (struct/union/class), which indicates its size and field position
2745 /// information.
2746 const ASTRecordLayout *
2747 ASTContext::BuildMicrosoftASTRecordLayout(const RecordDecl *D) const {
2748   MicrosoftRecordLayoutBuilder Builder(*this);
2749   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2750     Builder.cxxLayout(RD);
2751     return new (*this) ASTRecordLayout(
2752         *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment,
2753         Builder.HasOwnVFPtr,
2754         Builder.HasOwnVFPtr || Builder.PrimaryBase,
2755         Builder.VBPtrOffset, Builder.NonVirtualSize, Builder.FieldOffsets.data(),
2756         Builder.FieldOffsets.size(), Builder.NonVirtualSize,
2757         Builder.Alignment, CharUnits::Zero(), Builder.PrimaryBase,
2758         false, Builder.SharedVBPtrBase,
2759         Builder.EndsWithZeroSizedObject, Builder.LeadsWithZeroSizedBase,
2760         Builder.Bases, Builder.VBases);
2761   } else {
2762     Builder.layout(D);
2763     return new (*this) ASTRecordLayout(
2764         *this, Builder.Size, Builder.Alignment, Builder.RequiredAlignment,
2765         Builder.Size, Builder.FieldOffsets.data(), Builder.FieldOffsets.size());
2766   }
2767 }
2768 
2769 /// getASTRecordLayout - Get or compute information about the layout of the
2770 /// specified record (struct/union/class), which indicates its size and field
2771 /// position information.
2772 const ASTRecordLayout &
2773 ASTContext::getASTRecordLayout(const RecordDecl *D) const {
2774   // These asserts test different things.  A record has a definition
2775   // as soon as we begin to parse the definition.  That definition is
2776   // not a complete definition (which is what isDefinition() tests)
2777   // until we *finish* parsing the definition.
2778 
2779   if (D->hasExternalLexicalStorage() && !D->getDefinition())
2780     getExternalSource()->CompleteType(const_cast<RecordDecl*>(D));
2781 
2782   D = D->getDefinition();
2783   assert(D && "Cannot get layout of forward declarations!");
2784   assert(!D->isInvalidDecl() && "Cannot get layout of invalid decl!");
2785   assert(D->isCompleteDefinition() && "Cannot layout type before complete!");
2786 
2787   // Look up this layout, if already laid out, return what we have.
2788   // Note that we can't save a reference to the entry because this function
2789   // is recursive.
2790   const ASTRecordLayout *Entry = ASTRecordLayouts[D];
2791   if (Entry) return *Entry;
2792 
2793   const ASTRecordLayout *NewEntry = 0;
2794 
2795   if (isMsLayout(D) && !D->getASTContext().getExternalSource()) {
2796     NewEntry = BuildMicrosoftASTRecordLayout(D);
2797   } else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2798     EmptySubobjectMap EmptySubobjects(*this, RD);
2799     RecordLayoutBuilder Builder(*this, &EmptySubobjects);
2800     Builder.Layout(RD);
2801 
2802     // In certain situations, we are allowed to lay out objects in the
2803     // tail-padding of base classes.  This is ABI-dependent.
2804     // FIXME: this should be stored in the record layout.
2805     bool skipTailPadding =
2806       mustSkipTailPadding(getTargetInfo().getCXXABI(), cast<CXXRecordDecl>(D));
2807 
2808     // FIXME: This should be done in FinalizeLayout.
2809     CharUnits DataSize =
2810       skipTailPadding ? Builder.getSize() : Builder.getDataSize();
2811     CharUnits NonVirtualSize =
2812       skipTailPadding ? DataSize : Builder.NonVirtualSize;
2813     NewEntry =
2814       new (*this) ASTRecordLayout(*this, Builder.getSize(),
2815                                   Builder.Alignment,
2816                                   /*RequiredAlignment : used by MS-ABI)*/
2817                                   Builder.Alignment,
2818                                   Builder.HasOwnVFPtr,
2819                                   RD->isDynamicClass(),
2820                                   CharUnits::fromQuantity(-1),
2821                                   DataSize,
2822                                   Builder.FieldOffsets.data(),
2823                                   Builder.FieldOffsets.size(),
2824                                   NonVirtualSize,
2825                                   Builder.NonVirtualAlignment,
2826                                   EmptySubobjects.SizeOfLargestEmptySubobject,
2827                                   Builder.PrimaryBase,
2828                                   Builder.PrimaryBaseIsVirtual,
2829                                   0, false, false,
2830                                   Builder.Bases, Builder.VBases);
2831   } else {
2832     RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
2833     Builder.Layout(D);
2834 
2835     NewEntry =
2836       new (*this) ASTRecordLayout(*this, Builder.getSize(),
2837                                   Builder.Alignment,
2838                                   /*RequiredAlignment : used by MS-ABI)*/
2839                                   Builder.Alignment,
2840                                   Builder.getSize(),
2841                                   Builder.FieldOffsets.data(),
2842                                   Builder.FieldOffsets.size());
2843   }
2844 
2845   ASTRecordLayouts[D] = NewEntry;
2846 
2847   if (getLangOpts().DumpRecordLayouts) {
2848     llvm::outs() << "\n*** Dumping AST Record Layout\n";
2849     DumpRecordLayout(D, llvm::outs(), getLangOpts().DumpRecordLayoutsSimple);
2850   }
2851 
2852   return *NewEntry;
2853 }
2854 
2855 const CXXMethodDecl *ASTContext::getCurrentKeyFunction(const CXXRecordDecl *RD) {
2856   if (!getTargetInfo().getCXXABI().hasKeyFunctions())
2857     return 0;
2858 
2859   assert(RD->getDefinition() && "Cannot get key function for forward decl!");
2860   RD = cast<CXXRecordDecl>(RD->getDefinition());
2861 
2862   LazyDeclPtr &Entry = KeyFunctions[RD];
2863   if (!Entry)
2864     Entry = const_cast<CXXMethodDecl*>(computeKeyFunction(*this, RD));
2865 
2866   return cast_or_null<CXXMethodDecl>(Entry.get(getExternalSource()));
2867 }
2868 
2869 void ASTContext::setNonKeyFunction(const CXXMethodDecl *Method) {
2870   assert(Method == Method->getFirstDecl() &&
2871          "not working with method declaration from class definition");
2872 
2873   // Look up the cache entry.  Since we're working with the first
2874   // declaration, its parent must be the class definition, which is
2875   // the correct key for the KeyFunctions hash.
2876   llvm::DenseMap<const CXXRecordDecl*, LazyDeclPtr>::iterator
2877     I = KeyFunctions.find(Method->getParent());
2878 
2879   // If it's not cached, there's nothing to do.
2880   if (I == KeyFunctions.end()) return;
2881 
2882   // If it is cached, check whether it's the target method, and if so,
2883   // remove it from the cache.
2884   if (I->second.get(getExternalSource()) == Method) {
2885     // FIXME: remember that we did this for module / chained PCH state?
2886     KeyFunctions.erase(I);
2887   }
2888 }
2889 
2890 static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) {
2891   const ASTRecordLayout &Layout = C.getASTRecordLayout(FD->getParent());
2892   return Layout.getFieldOffset(FD->getFieldIndex());
2893 }
2894 
2895 uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const {
2896   uint64_t OffsetInBits;
2897   if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
2898     OffsetInBits = ::getFieldOffset(*this, FD);
2899   } else {
2900     const IndirectFieldDecl *IFD = cast<IndirectFieldDecl>(VD);
2901 
2902     OffsetInBits = 0;
2903     for (const auto *CI : IFD->chain())
2904       OffsetInBits += ::getFieldOffset(*this, cast<FieldDecl>(CI));
2905   }
2906 
2907   return OffsetInBits;
2908 }
2909 
2910 /// getObjCLayout - Get or compute information about the layout of the
2911 /// given interface.
2912 ///
2913 /// \param Impl - If given, also include the layout of the interface's
2914 /// implementation. This may differ by including synthesized ivars.
2915 const ASTRecordLayout &
2916 ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
2917                           const ObjCImplementationDecl *Impl) const {
2918   // Retrieve the definition
2919   if (D->hasExternalLexicalStorage() && !D->getDefinition())
2920     getExternalSource()->CompleteType(const_cast<ObjCInterfaceDecl*>(D));
2921   D = D->getDefinition();
2922   assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!");
2923 
2924   // Look up this layout, if already laid out, return what we have.
2925   const ObjCContainerDecl *Key =
2926     Impl ? (const ObjCContainerDecl*) Impl : (const ObjCContainerDecl*) D;
2927   if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
2928     return *Entry;
2929 
2930   // Add in synthesized ivar count if laying out an implementation.
2931   if (Impl) {
2932     unsigned SynthCount = CountNonClassIvars(D);
2933     // If there aren't any sythesized ivars then reuse the interface
2934     // entry. Note we can't cache this because we simply free all
2935     // entries later; however we shouldn't look up implementations
2936     // frequently.
2937     if (SynthCount == 0)
2938       return getObjCLayout(D, 0);
2939   }
2940 
2941   RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
2942   Builder.Layout(D);
2943 
2944   const ASTRecordLayout *NewEntry =
2945     new (*this) ASTRecordLayout(*this, Builder.getSize(),
2946                                 Builder.Alignment,
2947                                 /*RequiredAlignment : used by MS-ABI)*/
2948                                 Builder.Alignment,
2949                                 Builder.getDataSize(),
2950                                 Builder.FieldOffsets.data(),
2951                                 Builder.FieldOffsets.size());
2952 
2953   ObjCLayouts[Key] = NewEntry;
2954 
2955   return *NewEntry;
2956 }
2957 
2958 static void PrintOffset(raw_ostream &OS,
2959                         CharUnits Offset, unsigned IndentLevel) {
2960   OS << llvm::format("%4" PRId64 " | ", (int64_t)Offset.getQuantity());
2961   OS.indent(IndentLevel * 2);
2962 }
2963 
2964 static void PrintIndentNoOffset(raw_ostream &OS, unsigned IndentLevel) {
2965   OS << "     | ";
2966   OS.indent(IndentLevel * 2);
2967 }
2968 
2969 static void DumpCXXRecordLayout(raw_ostream &OS,
2970                                 const CXXRecordDecl *RD, const ASTContext &C,
2971                                 CharUnits Offset,
2972                                 unsigned IndentLevel,
2973                                 const char* Description,
2974                                 bool IncludeVirtualBases) {
2975   const ASTRecordLayout &Layout = C.getASTRecordLayout(RD);
2976 
2977   PrintOffset(OS, Offset, IndentLevel);
2978   OS << C.getTypeDeclType(const_cast<CXXRecordDecl *>(RD)).getAsString();
2979   if (Description)
2980     OS << ' ' << Description;
2981   if (RD->isEmpty())
2982     OS << " (empty)";
2983   OS << '\n';
2984 
2985   IndentLevel++;
2986 
2987   const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
2988   bool HasOwnVFPtr = Layout.hasOwnVFPtr();
2989   bool HasOwnVBPtr = Layout.hasOwnVBPtr();
2990 
2991   // Vtable pointer.
2992   if (RD->isDynamicClass() && !PrimaryBase && !isMsLayout(RD)) {
2993     PrintOffset(OS, Offset, IndentLevel);
2994     OS << '(' << *RD << " vtable pointer)\n";
2995   } else if (HasOwnVFPtr) {
2996     PrintOffset(OS, Offset, IndentLevel);
2997     // vfptr (for Microsoft C++ ABI)
2998     OS << '(' << *RD << " vftable pointer)\n";
2999   }
3000 
3001   // Collect nvbases.
3002   SmallVector<const CXXRecordDecl *, 4> Bases;
3003   for (const auto &I : RD->bases()) {
3004     assert(!I.getType()->isDependentType() &&
3005            "Cannot layout class with dependent bases.");
3006     if (!I.isVirtual())
3007       Bases.push_back(I.getType()->getAsCXXRecordDecl());
3008   }
3009 
3010   // Sort nvbases by offset.
3011   std::stable_sort(Bases.begin(), Bases.end(),
3012                    [&](const CXXRecordDecl *L, const CXXRecordDecl *R) {
3013     return Layout.getBaseClassOffset(L) < Layout.getBaseClassOffset(R);
3014   });
3015 
3016   // Dump (non-virtual) bases
3017   for (SmallVectorImpl<const CXXRecordDecl *>::iterator I = Bases.begin(),
3018                                                         E = Bases.end();
3019        I != E; ++I) {
3020     const CXXRecordDecl *Base = *I;
3021     CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
3022     DumpCXXRecordLayout(OS, Base, C, BaseOffset, IndentLevel,
3023                         Base == PrimaryBase ? "(primary base)" : "(base)",
3024                         /*IncludeVirtualBases=*/false);
3025   }
3026 
3027   // vbptr (for Microsoft C++ ABI)
3028   if (HasOwnVBPtr) {
3029     PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel);
3030     OS << '(' << *RD << " vbtable pointer)\n";
3031   }
3032 
3033   // Dump fields.
3034   uint64_t FieldNo = 0;
3035   for (CXXRecordDecl::field_iterator I = RD->field_begin(),
3036          E = RD->field_end(); I != E; ++I, ++FieldNo) {
3037     const FieldDecl &Field = **I;
3038     CharUnits FieldOffset = Offset +
3039       C.toCharUnitsFromBits(Layout.getFieldOffset(FieldNo));
3040 
3041     if (const CXXRecordDecl *D = Field.getType()->getAsCXXRecordDecl()) {
3042       DumpCXXRecordLayout(OS, D, C, FieldOffset, IndentLevel,
3043                           Field.getName().data(),
3044                           /*IncludeVirtualBases=*/true);
3045       continue;
3046     }
3047 
3048     PrintOffset(OS, FieldOffset, IndentLevel);
3049     OS << Field.getType().getAsString() << ' ' << Field << '\n';
3050   }
3051 
3052   if (!IncludeVirtualBases)
3053     return;
3054 
3055   // Dump virtual bases.
3056   const ASTRecordLayout::VBaseOffsetsMapTy &vtordisps =
3057     Layout.getVBaseOffsetsMap();
3058   for (const auto &I : RD->vbases()) {
3059     assert(I.isVirtual() && "Found non-virtual class!");
3060     const CXXRecordDecl *VBase = I.getType()->getAsCXXRecordDecl();
3061 
3062     CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
3063 
3064     if (vtordisps.find(VBase)->second.hasVtorDisp()) {
3065       PrintOffset(OS, VBaseOffset - CharUnits::fromQuantity(4), IndentLevel);
3066       OS << "(vtordisp for vbase " << *VBase << ")\n";
3067     }
3068 
3069     DumpCXXRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel,
3070                         VBase == PrimaryBase ?
3071                         "(primary virtual base)" : "(virtual base)",
3072                         /*IncludeVirtualBases=*/false);
3073   }
3074 
3075   PrintIndentNoOffset(OS, IndentLevel - 1);
3076   OS << "[sizeof=" << Layout.getSize().getQuantity();
3077   if (!isMsLayout(RD))
3078     OS << ", dsize=" << Layout.getDataSize().getQuantity();
3079   OS << ", align=" << Layout.getAlignment().getQuantity() << '\n';
3080 
3081   PrintIndentNoOffset(OS, IndentLevel - 1);
3082   OS << " nvsize=" << Layout.getNonVirtualSize().getQuantity();
3083   OS << ", nvalign=" << Layout.getNonVirtualAlignment().getQuantity() << "]\n";
3084 }
3085 
3086 void ASTContext::DumpRecordLayout(const RecordDecl *RD,
3087                                   raw_ostream &OS,
3088                                   bool Simple) const {
3089   const ASTRecordLayout &Info = getASTRecordLayout(RD);
3090 
3091   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
3092     if (!Simple)
3093       return DumpCXXRecordLayout(OS, CXXRD, *this, CharUnits(), 0, 0,
3094                                  /*IncludeVirtualBases=*/true);
3095 
3096   OS << "Type: " << getTypeDeclType(RD).getAsString() << "\n";
3097   if (!Simple) {
3098     OS << "Record: ";
3099     RD->dump();
3100   }
3101   OS << "\nLayout: ";
3102   OS << "<ASTRecordLayout\n";
3103   OS << "  Size:" << toBits(Info.getSize()) << "\n";
3104   if (!isMsLayout(RD))
3105     OS << "  DataSize:" << toBits(Info.getDataSize()) << "\n";
3106   OS << "  Alignment:" << toBits(Info.getAlignment()) << "\n";
3107   OS << "  FieldOffsets: [";
3108   for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) {
3109     if (i) OS << ", ";
3110     OS << Info.getFieldOffset(i);
3111   }
3112   OS << "]>\n";
3113 }
3114