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