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