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