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