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/Attr.h"
11 #include "clang/AST/CXXInheritance.h"
12 #include "clang/AST/Decl.h"
13 #include "clang/AST/DeclCXX.h"
14 #include "clang/AST/DeclObjC.h"
15 #include "clang/AST/Expr.h"
16 #include "clang/AST/RecordLayout.h"
17 #include "clang/Basic/TargetInfo.h"
18 #include "clang/Sema/SemaDiagnostic.h"
19 #include "llvm/Support/Format.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/Support/MathExtras.h"
22 #include "llvm/Support/CrashRecoveryContext.h"
23 
24 using namespace clang;
25 
26 namespace {
27 
28 /// BaseSubobjectInfo - Represents a single base subobject in a complete class.
29 /// For a class hierarchy like
30 ///
31 /// class A { };
32 /// class B : A { };
33 /// class C : A, B { };
34 ///
35 /// The BaseSubobjectInfo graph for C will have three BaseSubobjectInfo
36 /// instances, one for B and two for A.
37 ///
38 /// If a base is virtual, it will only have one BaseSubobjectInfo allocated.
39 struct BaseSubobjectInfo {
40   /// Class - The class for this base info.
41   const CXXRecordDecl *Class;
42 
43   /// IsVirtual - Whether the BaseInfo represents a virtual base or not.
44   bool IsVirtual;
45 
46   /// Bases - Information about the base subobjects.
47   SmallVector<BaseSubobjectInfo*, 4> Bases;
48 
49   /// PrimaryVirtualBaseInfo - Holds the base info for the primary virtual base
50   /// of this base info (if one exists).
51   BaseSubobjectInfo *PrimaryVirtualBaseInfo;
52 
53   // FIXME: Document.
54   const BaseSubobjectInfo *Derived;
55 };
56 
57 /// EmptySubobjectMap - Keeps track of which empty subobjects exist at different
58 /// offsets while laying out a C++ class.
59 class EmptySubobjectMap {
60   const ASTContext &Context;
61   uint64_t CharWidth;
62 
63   /// Class - The class whose empty entries we're keeping track of.
64   const CXXRecordDecl *Class;
65 
66   /// EmptyClassOffsets - A map from offsets to empty record decls.
67   typedef SmallVector<const CXXRecordDecl *, 1> ClassVectorTy;
68   typedef llvm::DenseMap<CharUnits, ClassVectorTy> EmptyClassOffsetsMapTy;
69   EmptyClassOffsetsMapTy EmptyClassOffsets;
70 
71   /// MaxEmptyClassOffset - The highest offset known to contain an empty
72   /// base subobject.
73   CharUnits MaxEmptyClassOffset;
74 
75   /// ComputeEmptySubobjectSizes - Compute the size of the largest base or
76   /// member subobject that is empty.
77   void ComputeEmptySubobjectSizes();
78 
79   void AddSubobjectAtOffset(const CXXRecordDecl *RD, CharUnits Offset);
80 
81   void UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
82                                  CharUnits Offset, bool PlacingEmptyBase);
83 
84   void UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
85                                   const CXXRecordDecl *Class,
86                                   CharUnits Offset);
87   void UpdateEmptyFieldSubobjects(const FieldDecl *FD, CharUnits Offset);
88 
89   /// AnyEmptySubobjectsBeyondOffset - Returns whether there are any empty
90   /// subobjects beyond the given offset.
91   bool AnyEmptySubobjectsBeyondOffset(CharUnits Offset) const {
92     return Offset <= MaxEmptyClassOffset;
93   }
94 
95   CharUnits
96   getFieldOffset(const ASTRecordLayout &Layout, unsigned FieldNo) const {
97     uint64_t FieldOffset = Layout.getFieldOffset(FieldNo);
98     assert(FieldOffset % CharWidth == 0 &&
99            "Field offset not at char boundary!");
100 
101     return Context.toCharUnitsFromBits(FieldOffset);
102   }
103 
104 protected:
105   bool CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
106                                  CharUnits Offset) const;
107 
108   bool CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
109                                      CharUnits Offset);
110 
111   bool CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
112                                       const CXXRecordDecl *Class,
113                                       CharUnits Offset) const;
114   bool CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
115                                       CharUnits Offset) const;
116 
117 public:
118   /// This holds the size of the largest empty subobject (either a base
119   /// or a member). Will be zero if the record being built doesn't contain
120   /// any empty classes.
121   CharUnits SizeOfLargestEmptySubobject;
122 
123   EmptySubobjectMap(const ASTContext &Context, const CXXRecordDecl *Class)
124   : Context(Context), CharWidth(Context.getCharWidth()), Class(Class) {
125       ComputeEmptySubobjectSizes();
126   }
127 
128   /// CanPlaceBaseAtOffset - Return whether the given base class can be placed
129   /// at the given offset.
130   /// Returns false if placing the record will result in two components
131   /// (direct or indirect) of the same type having the same offset.
132   bool CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
133                             CharUnits Offset);
134 
135   /// CanPlaceFieldAtOffset - Return whether a field can be placed at the given
136   /// offset.
137   bool CanPlaceFieldAtOffset(const FieldDecl *FD, CharUnits Offset);
138 };
139 
140 void EmptySubobjectMap::ComputeEmptySubobjectSizes() {
141   // Check the bases.
142   for (CXXRecordDecl::base_class_const_iterator I = Class->bases_begin(),
143        E = Class->bases_end(); I != E; ++I) {
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 (CXXRecordDecl::field_iterator I = Class->field_begin(),
163        E = Class->field_end(); I != E; ++I) {
164     const FieldDecl *FD = *I;
165 
166     const RecordType *RT =
167       Context.getBaseElementType(FD->getType())->getAs<RecordType>();
168 
169     // We only care about record types.
170     if (!RT)
171       continue;
172 
173     CharUnits EmptySize;
174     const CXXRecordDecl *MemberDecl = cast<CXXRecordDecl>(RT->getDecl());
175     const ASTRecordLayout &Layout = Context.getASTRecordLayout(MemberDecl);
176     if (MemberDecl->isEmpty()) {
177       // If the class decl is empty, get its size.
178       EmptySize = Layout.getSize();
179     } else {
180       // Otherwise, we get the largest empty subobject for the decl.
181       EmptySize = Layout.getSizeOfLargestEmptySubobject();
182     }
183 
184     if (EmptySize > SizeOfLargestEmptySubobject)
185       SizeOfLargestEmptySubobject = EmptySize;
186   }
187 }
188 
189 bool
190 EmptySubobjectMap::CanPlaceSubobjectAtOffset(const CXXRecordDecl *RD,
191                                              CharUnits Offset) const {
192   // We only need to check empty bases.
193   if (!RD->isEmpty())
194     return true;
195 
196   EmptyClassOffsetsMapTy::const_iterator I = EmptyClassOffsets.find(Offset);
197   if (I == EmptyClassOffsets.end())
198     return true;
199 
200   const ClassVectorTy& Classes = I->second;
201   if (std::find(Classes.begin(), Classes.end(), RD) == Classes.end())
202     return true;
203 
204   // There is already an empty class of the same type at this offset.
205   return false;
206 }
207 
208 void EmptySubobjectMap::AddSubobjectAtOffset(const CXXRecordDecl *RD,
209                                              CharUnits Offset) {
210   // We only care about empty bases.
211   if (!RD->isEmpty())
212     return;
213 
214   // If we have empty structures inside an union, we can assign both
215   // the same offset. Just avoid pushing them twice in the list.
216   ClassVectorTy& Classes = EmptyClassOffsets[Offset];
217   if (std::find(Classes.begin(), Classes.end(), RD) != Classes.end())
218     return;
219 
220   Classes.push_back(RD);
221 
222   // Update the empty class offset.
223   if (Offset > MaxEmptyClassOffset)
224     MaxEmptyClassOffset = Offset;
225 }
226 
227 bool
228 EmptySubobjectMap::CanPlaceBaseSubobjectAtOffset(const BaseSubobjectInfo *Info,
229                                                  CharUnits Offset) {
230   // We don't have to keep looking past the maximum offset that's known to
231   // contain an empty class.
232   if (!AnyEmptySubobjectsBeyondOffset(Offset))
233     return true;
234 
235   if (!CanPlaceSubobjectAtOffset(Info->Class, Offset))
236     return false;
237 
238   // Traverse all non-virtual bases.
239   const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
240   for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
241     BaseSubobjectInfo* Base = Info->Bases[I];
242     if (Base->IsVirtual)
243       continue;
244 
245     CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
246 
247     if (!CanPlaceBaseSubobjectAtOffset(Base, BaseOffset))
248       return false;
249   }
250 
251   if (Info->PrimaryVirtualBaseInfo) {
252     BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
253 
254     if (Info == PrimaryVirtualBaseInfo->Derived) {
255       if (!CanPlaceBaseSubobjectAtOffset(PrimaryVirtualBaseInfo, Offset))
256         return false;
257     }
258   }
259 
260   // Traverse all member variables.
261   unsigned FieldNo = 0;
262   for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
263        E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
264     const FieldDecl *FD = *I;
265     if (FD->isBitField())
266       continue;
267 
268     CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
269     if (!CanPlaceFieldSubobjectAtOffset(FD, FieldOffset))
270       return false;
271   }
272 
273   return true;
274 }
275 
276 void EmptySubobjectMap::UpdateEmptyBaseSubobjects(const BaseSubobjectInfo *Info,
277                                                   CharUnits Offset,
278                                                   bool PlacingEmptyBase) {
279   if (!PlacingEmptyBase && Offset >= SizeOfLargestEmptySubobject) {
280     // We know that the only empty subobjects that can conflict with empty
281     // subobject of non-empty bases, are empty bases that can be placed at
282     // offset zero. Because of this, we only need to keep track of empty base
283     // subobjects with offsets less than the size of the largest empty
284     // subobject for our class.
285     return;
286   }
287 
288   AddSubobjectAtOffset(Info->Class, Offset);
289 
290   // Traverse all non-virtual bases.
291   const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
292   for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
293     BaseSubobjectInfo* Base = Info->Bases[I];
294     if (Base->IsVirtual)
295       continue;
296 
297     CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
298     UpdateEmptyBaseSubobjects(Base, BaseOffset, PlacingEmptyBase);
299   }
300 
301   if (Info->PrimaryVirtualBaseInfo) {
302     BaseSubobjectInfo *PrimaryVirtualBaseInfo = Info->PrimaryVirtualBaseInfo;
303 
304     if (Info == PrimaryVirtualBaseInfo->Derived)
305       UpdateEmptyBaseSubobjects(PrimaryVirtualBaseInfo, Offset,
306                                 PlacingEmptyBase);
307   }
308 
309   // Traverse all member variables.
310   unsigned FieldNo = 0;
311   for (CXXRecordDecl::field_iterator I = Info->Class->field_begin(),
312        E = Info->Class->field_end(); I != E; ++I, ++FieldNo) {
313     const FieldDecl *FD = *I;
314     if (FD->isBitField())
315       continue;
316 
317     CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
318     UpdateEmptyFieldSubobjects(FD, FieldOffset);
319   }
320 }
321 
322 bool EmptySubobjectMap::CanPlaceBaseAtOffset(const BaseSubobjectInfo *Info,
323                                              CharUnits Offset) {
324   // If we know this class doesn't have any empty subobjects we don't need to
325   // bother checking.
326   if (SizeOfLargestEmptySubobject.isZero())
327     return true;
328 
329   if (!CanPlaceBaseSubobjectAtOffset(Info, Offset))
330     return false;
331 
332   // We are able to place the base at this offset. Make sure to update the
333   // empty base subobject map.
334   UpdateEmptyBaseSubobjects(Info, Offset, Info->Class->isEmpty());
335   return true;
336 }
337 
338 bool
339 EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const CXXRecordDecl *RD,
340                                                   const CXXRecordDecl *Class,
341                                                   CharUnits Offset) const {
342   // We don't have to keep looking past the maximum offset that's known to
343   // contain an empty class.
344   if (!AnyEmptySubobjectsBeyondOffset(Offset))
345     return true;
346 
347   if (!CanPlaceSubobjectAtOffset(RD, Offset))
348     return false;
349 
350   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
351 
352   // Traverse all non-virtual bases.
353   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
354        E = RD->bases_end(); I != E; ++I) {
355     if (I->isVirtual())
356       continue;
357 
358     const CXXRecordDecl *BaseDecl =
359       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
360 
361     CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
362     if (!CanPlaceFieldSubobjectAtOffset(BaseDecl, Class, BaseOffset))
363       return false;
364   }
365 
366   if (RD == Class) {
367     // This is the most derived class, traverse virtual bases as well.
368     for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
369          E = RD->vbases_end(); I != E; ++I) {
370       const CXXRecordDecl *VBaseDecl =
371         cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
372 
373       CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
374       if (!CanPlaceFieldSubobjectAtOffset(VBaseDecl, Class, VBaseOffset))
375         return false;
376     }
377   }
378 
379   // Traverse all member variables.
380   unsigned FieldNo = 0;
381   for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
382        I != E; ++I, ++FieldNo) {
383     const FieldDecl *FD = *I;
384     if (FD->isBitField())
385       continue;
386 
387     CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
388 
389     if (!CanPlaceFieldSubobjectAtOffset(FD, FieldOffset))
390       return false;
391   }
392 
393   return true;
394 }
395 
396 bool
397 EmptySubobjectMap::CanPlaceFieldSubobjectAtOffset(const FieldDecl *FD,
398                                                   CharUnits Offset) const {
399   // We don't have to keep looking past the maximum offset that's known to
400   // contain an empty class.
401   if (!AnyEmptySubobjectsBeyondOffset(Offset))
402     return true;
403 
404   QualType T = FD->getType();
405   if (const RecordType *RT = T->getAs<RecordType>()) {
406     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
407     return CanPlaceFieldSubobjectAtOffset(RD, RD, Offset);
408   }
409 
410   // If we have an array type we need to look at every element.
411   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
412     QualType ElemTy = Context.getBaseElementType(AT);
413     const RecordType *RT = ElemTy->getAs<RecordType>();
414     if (!RT)
415       return true;
416 
417     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
418     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
419 
420     uint64_t NumElements = Context.getConstantArrayElementCount(AT);
421     CharUnits ElementOffset = Offset;
422     for (uint64_t I = 0; I != NumElements; ++I) {
423       // We don't have to keep looking past the maximum offset that's known to
424       // contain an empty class.
425       if (!AnyEmptySubobjectsBeyondOffset(ElementOffset))
426         return true;
427 
428       if (!CanPlaceFieldSubobjectAtOffset(RD, RD, ElementOffset))
429         return false;
430 
431       ElementOffset += Layout.getSize();
432     }
433   }
434 
435   return true;
436 }
437 
438 bool
439 EmptySubobjectMap::CanPlaceFieldAtOffset(const FieldDecl *FD,
440                                          CharUnits Offset) {
441   if (!CanPlaceFieldSubobjectAtOffset(FD, Offset))
442     return false;
443 
444   // We are able to place the member variable at this offset.
445   // Make sure to update the empty base subobject map.
446   UpdateEmptyFieldSubobjects(FD, Offset);
447   return true;
448 }
449 
450 void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const CXXRecordDecl *RD,
451                                                    const CXXRecordDecl *Class,
452                                                    CharUnits Offset) {
453   // We know that the only empty subobjects that can conflict with empty
454   // field subobjects are subobjects of empty bases that can be placed at offset
455   // zero. Because of this, we only need to keep track of empty field
456   // subobjects with offsets less than the size of the largest empty
457   // subobject for our class.
458   if (Offset >= SizeOfLargestEmptySubobject)
459     return;
460 
461   AddSubobjectAtOffset(RD, Offset);
462 
463   const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
464 
465   // Traverse all non-virtual bases.
466   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
467        E = RD->bases_end(); I != E; ++I) {
468     if (I->isVirtual())
469       continue;
470 
471     const CXXRecordDecl *BaseDecl =
472       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
473 
474     CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(BaseDecl);
475     UpdateEmptyFieldSubobjects(BaseDecl, Class, BaseOffset);
476   }
477 
478   if (RD == Class) {
479     // This is the most derived class, traverse virtual bases as well.
480     for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
481          E = RD->vbases_end(); I != E; ++I) {
482       const CXXRecordDecl *VBaseDecl =
483       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
484 
485       CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBaseDecl);
486       UpdateEmptyFieldSubobjects(VBaseDecl, Class, VBaseOffset);
487     }
488   }
489 
490   // Traverse all member variables.
491   unsigned FieldNo = 0;
492   for (CXXRecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
493        I != E; ++I, ++FieldNo) {
494     const FieldDecl *FD = *I;
495     if (FD->isBitField())
496       continue;
497 
498     CharUnits FieldOffset = Offset + getFieldOffset(Layout, FieldNo);
499 
500     UpdateEmptyFieldSubobjects(FD, FieldOffset);
501   }
502 }
503 
504 void EmptySubobjectMap::UpdateEmptyFieldSubobjects(const FieldDecl *FD,
505                                                    CharUnits Offset) {
506   QualType T = FD->getType();
507   if (const RecordType *RT = T->getAs<RecordType>()) {
508     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
509     UpdateEmptyFieldSubobjects(RD, RD, Offset);
510     return;
511   }
512 
513   // If we have an array type we need to update every element.
514   if (const ConstantArrayType *AT = Context.getAsConstantArrayType(T)) {
515     QualType ElemTy = Context.getBaseElementType(AT);
516     const RecordType *RT = ElemTy->getAs<RecordType>();
517     if (!RT)
518       return;
519 
520     const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
521     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
522 
523     uint64_t NumElements = Context.getConstantArrayElementCount(AT);
524     CharUnits ElementOffset = Offset;
525 
526     for (uint64_t I = 0; I != NumElements; ++I) {
527       // We know that the only empty subobjects that can conflict with empty
528       // field subobjects are subobjects of empty bases that can be placed at
529       // offset zero. Because of this, we only need to keep track of empty field
530       // subobjects with offsets less than the size of the largest empty
531       // subobject for our class.
532       if (ElementOffset >= SizeOfLargestEmptySubobject)
533         return;
534 
535       UpdateEmptyFieldSubobjects(RD, RD, ElementOffset);
536       ElementOffset += Layout.getSize();
537     }
538   }
539 }
540 
541 class RecordLayoutBuilder {
542 protected:
543   // FIXME: Remove this and make the appropriate fields public.
544   friend class clang::ASTContext;
545 
546   const ASTContext &Context;
547 
548   EmptySubobjectMap *EmptySubobjects;
549 
550   /// Size - The current size of the record layout.
551   uint64_t Size;
552 
553   /// Alignment - The current alignment of the record layout.
554   CharUnits Alignment;
555 
556   /// \brief The alignment if attribute packed is not used.
557   CharUnits UnpackedAlignment;
558 
559   SmallVector<uint64_t, 16> FieldOffsets;
560 
561   /// Packed - Whether the record is packed or not.
562   unsigned Packed : 1;
563 
564   unsigned IsUnion : 1;
565 
566   unsigned IsMac68kAlign : 1;
567 
568   unsigned IsMsStruct : 1;
569 
570   /// UnfilledBitsInLastByte - If the last field laid out was a bitfield,
571   /// this contains the number of bits in the last byte that can be used for
572   /// an adjacent bitfield if necessary.
573   unsigned char UnfilledBitsInLastByte;
574 
575   /// MaxFieldAlignment - The maximum allowed field alignment. This is set by
576   /// #pragma pack.
577   CharUnits MaxFieldAlignment;
578 
579   /// DataSize - The data size of the record being laid out.
580   uint64_t DataSize;
581 
582   CharUnits NonVirtualSize;
583   CharUnits NonVirtualAlignment;
584 
585   FieldDecl *ZeroLengthBitfield;
586 
587   /// PrimaryBase - the primary base class (if one exists) of the class
588   /// we're laying out.
589   const CXXRecordDecl *PrimaryBase;
590 
591   /// PrimaryBaseIsVirtual - Whether the primary base of the class we're laying
592   /// out is virtual.
593   bool PrimaryBaseIsVirtual;
594 
595   /// VFPtrOffset - Virtual function table offset. Only for MS layout.
596   CharUnits VFPtrOffset;
597 
598   /// VBPtrOffset - Virtual base table offset. Only for MS layout.
599   CharUnits VBPtrOffset;
600 
601   typedef llvm::DenseMap<const CXXRecordDecl *, CharUnits> BaseOffsetsMapTy;
602 
603   /// Bases - base classes and their offsets in the record.
604   BaseOffsetsMapTy Bases;
605 
606   // VBases - virtual base classes and their offsets in the record.
607   BaseOffsetsMapTy VBases;
608 
609   /// IndirectPrimaryBases - Virtual base classes, direct or indirect, that are
610   /// primary base classes for some other direct or indirect base class.
611   CXXIndirectPrimaryBaseSet IndirectPrimaryBases;
612 
613   /// FirstNearlyEmptyVBase - The first nearly empty virtual base class in
614   /// inheritance graph order. Used for determining the primary base class.
615   const CXXRecordDecl *FirstNearlyEmptyVBase;
616 
617   /// VisitedVirtualBases - A set of all the visited virtual bases, used to
618   /// avoid visiting virtual bases more than once.
619   llvm::SmallPtrSet<const CXXRecordDecl *, 4> VisitedVirtualBases;
620 
621   RecordLayoutBuilder(const ASTContext &Context,
622                       EmptySubobjectMap *EmptySubobjects)
623     : Context(Context), EmptySubobjects(EmptySubobjects), Size(0),
624       Alignment(CharUnits::One()), UnpackedAlignment(CharUnits::One()),
625       Packed(false), IsUnion(false),
626       IsMac68kAlign(false), IsMsStruct(false),
627       UnfilledBitsInLastByte(0), MaxFieldAlignment(CharUnits::Zero()),
628       DataSize(0), NonVirtualSize(CharUnits::Zero()),
629       NonVirtualAlignment(CharUnits::One()),
630       ZeroLengthBitfield(0), PrimaryBase(0),
631       PrimaryBaseIsVirtual(false),
632       VFPtrOffset(CharUnits::fromQuantity(-1)),
633       VBPtrOffset(CharUnits::fromQuantity(-1)),
634       FirstNearlyEmptyVBase(0) { }
635 
636   /// Reset this RecordLayoutBuilder to a fresh state, using the given
637   /// alignment as the initial alignment.  This is used for the
638   /// correct layout of vb-table pointers in MSVC.
639   void resetWithTargetAlignment(CharUnits TargetAlignment) {
640     const ASTContext &Context = this->Context;
641     EmptySubobjectMap *EmptySubobjects = this->EmptySubobjects;
642     this->~RecordLayoutBuilder();
643     new (this) RecordLayoutBuilder(Context, EmptySubobjects);
644     Alignment = UnpackedAlignment = TargetAlignment;
645   }
646 
647   void Layout(const RecordDecl *D);
648   void Layout(const CXXRecordDecl *D);
649   void Layout(const ObjCInterfaceDecl *D);
650 
651   void LayoutFields(const RecordDecl *D);
652   void LayoutField(const FieldDecl *D);
653   void LayoutWideBitField(uint64_t FieldSize, uint64_t TypeSize,
654                           bool FieldPacked, const FieldDecl *D);
655   void LayoutBitField(const FieldDecl *D);
656 
657   bool isMicrosoftCXXABI() const {
658     return Context.getTargetInfo().getCXXABI() == CXXABI_Microsoft;
659   }
660 
661   void MSLayoutVirtualBases(const CXXRecordDecl *RD);
662 
663   /// BaseSubobjectInfoAllocator - Allocator for BaseSubobjectInfo objects.
664   llvm::SpecificBumpPtrAllocator<BaseSubobjectInfo> BaseSubobjectInfoAllocator;
665 
666   typedef llvm::DenseMap<const CXXRecordDecl *, BaseSubobjectInfo *>
667     BaseSubobjectInfoMapTy;
668 
669   /// VirtualBaseInfo - Map from all the (direct or indirect) virtual bases
670   /// of the class we're laying out to their base subobject info.
671   BaseSubobjectInfoMapTy VirtualBaseInfo;
672 
673   /// NonVirtualBaseInfo - Map from all the direct non-virtual bases of the
674   /// class we're laying out to their base subobject info.
675   BaseSubobjectInfoMapTy NonVirtualBaseInfo;
676 
677   /// ComputeBaseSubobjectInfo - Compute the base subobject information for the
678   /// bases of the given class.
679   void ComputeBaseSubobjectInfo(const CXXRecordDecl *RD);
680 
681   /// ComputeBaseSubobjectInfo - Compute the base subobject information for a
682   /// single class and all of its base classes.
683   BaseSubobjectInfo *ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
684                                               bool IsVirtual,
685                                               BaseSubobjectInfo *Derived);
686 
687   /// DeterminePrimaryBase - Determine the primary base of the given class.
688   void DeterminePrimaryBase(const CXXRecordDecl *RD);
689 
690   void SelectPrimaryVBase(const CXXRecordDecl *RD);
691 
692   void EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign);
693 
694   /// LayoutNonVirtualBases - Determines the primary base class (if any) and
695   /// lays it out. Will then proceed to lay out all non-virtual base clasess.
696   void LayoutNonVirtualBases(const CXXRecordDecl *RD);
697 
698   /// LayoutNonVirtualBase - Lays out a single non-virtual base.
699   void LayoutNonVirtualBase(const BaseSubobjectInfo *Base);
700 
701   void AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
702                                     CharUnits Offset);
703 
704   bool needsVFTable(const CXXRecordDecl *RD) const;
705   bool hasNewVirtualFunction(const CXXRecordDecl *RD) const;
706   bool isPossiblePrimaryBase(const CXXRecordDecl *Base) const;
707 
708   /// LayoutVirtualBases - Lays out all the virtual bases.
709   void LayoutVirtualBases(const CXXRecordDecl *RD,
710                           const CXXRecordDecl *MostDerivedClass);
711 
712   /// LayoutVirtualBase - Lays out a single virtual base.
713   void LayoutVirtualBase(const BaseSubobjectInfo *Base);
714 
715   /// LayoutBase - Will lay out a base and return the offset where it was
716   /// placed, in chars.
717   CharUnits LayoutBase(const BaseSubobjectInfo *Base);
718 
719   /// InitializeLayout - Initialize record layout for the given record decl.
720   void InitializeLayout(const Decl *D);
721 
722   /// FinishLayout - Finalize record layout. Adjust record size based on the
723   /// alignment.
724   void FinishLayout(const NamedDecl *D);
725 
726   void UpdateAlignment(CharUnits NewAlignment, CharUnits UnpackedNewAlignment);
727   void UpdateAlignment(CharUnits NewAlignment) {
728     UpdateAlignment(NewAlignment, NewAlignment);
729   }
730 
731   void CheckFieldPadding(uint64_t Offset, uint64_t UnpaddedOffset,
732                           uint64_t UnpackedOffset, unsigned UnpackedAlign,
733                           bool isPacked, const FieldDecl *D);
734 
735   DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID);
736 
737   CharUnits getSize() const {
738     assert(Size % Context.getCharWidth() == 0);
739     return Context.toCharUnitsFromBits(Size);
740   }
741   uint64_t getSizeInBits() const { return Size; }
742 
743   void setSize(CharUnits NewSize) { Size = Context.toBits(NewSize); }
744   void setSize(uint64_t NewSize) { Size = NewSize; }
745 
746   CharUnits getAligment() const { return Alignment; }
747 
748   CharUnits getDataSize() const {
749     assert(DataSize % Context.getCharWidth() == 0);
750     return Context.toCharUnitsFromBits(DataSize);
751   }
752   uint64_t getDataSizeInBits() const { return DataSize; }
753 
754   void setDataSize(CharUnits NewSize) { DataSize = Context.toBits(NewSize); }
755   void setDataSize(uint64_t NewSize) { DataSize = NewSize; }
756 
757   RecordLayoutBuilder(const RecordLayoutBuilder&);   // DO NOT IMPLEMENT
758   void operator=(const RecordLayoutBuilder&); // DO NOT IMPLEMENT
759 public:
760   static const CXXMethodDecl *ComputeKeyFunction(const CXXRecordDecl *RD);
761 };
762 } // end anonymous namespace
763 
764 void
765 RecordLayoutBuilder::SelectPrimaryVBase(const CXXRecordDecl *RD) {
766   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
767          E = RD->bases_end(); I != E; ++I) {
768     assert(!I->getType()->isDependentType() &&
769            "Cannot layout class with dependent bases.");
770 
771     const CXXRecordDecl *Base =
772       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
773 
774     // Check if this is a nearly empty virtual base.
775     if (I->isVirtual() && Context.isNearlyEmpty(Base)) {
776       // If it's not an indirect primary base, then we've found our primary
777       // base.
778       if (!IndirectPrimaryBases.count(Base)) {
779         PrimaryBase = Base;
780         PrimaryBaseIsVirtual = true;
781         return;
782       }
783 
784       // Is this the first nearly empty virtual base?
785       if (!FirstNearlyEmptyVBase)
786         FirstNearlyEmptyVBase = Base;
787     }
788 
789     SelectPrimaryVBase(Base);
790     if (PrimaryBase)
791       return;
792   }
793 }
794 
795 /// DeterminePrimaryBase - Determine the primary base of the given class.
796 void RecordLayoutBuilder::DeterminePrimaryBase(const CXXRecordDecl *RD) {
797   // If the class isn't dynamic, it won't have a primary base.
798   if (!RD->isDynamicClass())
799     return;
800 
801   // Compute all the primary virtual bases for all of our direct and
802   // indirect bases, and record all their primary virtual base classes.
803   RD->getIndirectPrimaryBases(IndirectPrimaryBases);
804 
805   // If the record has a dynamic base class, attempt to choose a primary base
806   // class. It is the first (in direct base class order) non-virtual dynamic
807   // base class, if one exists.
808   for (CXXRecordDecl::base_class_const_iterator i = RD->bases_begin(),
809          e = RD->bases_end(); i != e; ++i) {
810     // Ignore virtual bases.
811     if (i->isVirtual())
812       continue;
813 
814     const CXXRecordDecl *Base =
815       cast<CXXRecordDecl>(i->getType()->getAs<RecordType>()->getDecl());
816 
817     if (isPossiblePrimaryBase(Base)) {
818       // We found it.
819       PrimaryBase = Base;
820       PrimaryBaseIsVirtual = false;
821       return;
822     }
823   }
824 
825   // The Microsoft ABI doesn't have primary virtual bases.
826   if (isMicrosoftCXXABI()) {
827     assert(!PrimaryBase && "Should not get here with a primary base!");
828     return;
829   }
830 
831   // Under the Itanium ABI, if there is no non-virtual primary base class,
832   // try to compute the primary virtual base.  The primary virtual base is
833   // the first nearly empty virtual base that is not an indirect primary
834   // virtual base class, if one exists.
835   if (RD->getNumVBases() != 0) {
836     SelectPrimaryVBase(RD);
837     if (PrimaryBase)
838       return;
839   }
840 
841   // Otherwise, it is the first indirect primary base class, if one exists.
842   if (FirstNearlyEmptyVBase) {
843     PrimaryBase = FirstNearlyEmptyVBase;
844     PrimaryBaseIsVirtual = true;
845     return;
846   }
847 
848   assert(!PrimaryBase && "Should not get here with a primary base!");
849 }
850 
851 BaseSubobjectInfo *
852 RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD,
853                                               bool IsVirtual,
854                                               BaseSubobjectInfo *Derived) {
855   BaseSubobjectInfo *Info;
856 
857   if (IsVirtual) {
858     // Check if we already have info about this virtual base.
859     BaseSubobjectInfo *&InfoSlot = VirtualBaseInfo[RD];
860     if (InfoSlot) {
861       assert(InfoSlot->Class == RD && "Wrong class for virtual base info!");
862       return InfoSlot;
863     }
864 
865     // We don't, create it.
866     InfoSlot = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
867     Info = InfoSlot;
868   } else {
869     Info = new (BaseSubobjectInfoAllocator.Allocate()) BaseSubobjectInfo;
870   }
871 
872   Info->Class = RD;
873   Info->IsVirtual = IsVirtual;
874   Info->Derived = 0;
875   Info->PrimaryVirtualBaseInfo = 0;
876 
877   const CXXRecordDecl *PrimaryVirtualBase = 0;
878   BaseSubobjectInfo *PrimaryVirtualBaseInfo = 0;
879 
880   // Check if this base has a primary virtual base.
881   if (RD->getNumVBases()) {
882     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
883     if (Layout.isPrimaryBaseVirtual()) {
884       // This base does have a primary virtual base.
885       PrimaryVirtualBase = Layout.getPrimaryBase();
886       assert(PrimaryVirtualBase && "Didn't have a primary virtual base!");
887 
888       // Now check if we have base subobject info about this primary base.
889       PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
890 
891       if (PrimaryVirtualBaseInfo) {
892         if (PrimaryVirtualBaseInfo->Derived) {
893           // We did have info about this primary base, and it turns out that it
894           // has already been claimed as a primary virtual base for another
895           // base.
896           PrimaryVirtualBase = 0;
897         } else {
898           // We can claim this base as our primary base.
899           Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
900           PrimaryVirtualBaseInfo->Derived = Info;
901         }
902       }
903     }
904   }
905 
906   // Now go through all direct bases.
907   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
908        E = RD->bases_end(); I != E; ++I) {
909     bool IsVirtual = I->isVirtual();
910 
911     const CXXRecordDecl *BaseDecl =
912       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
913 
914     Info->Bases.push_back(ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, Info));
915   }
916 
917   if (PrimaryVirtualBase && !PrimaryVirtualBaseInfo) {
918     // Traversing the bases must have created the base info for our primary
919     // virtual base.
920     PrimaryVirtualBaseInfo = VirtualBaseInfo.lookup(PrimaryVirtualBase);
921     assert(PrimaryVirtualBaseInfo &&
922            "Did not create a primary virtual base!");
923 
924     // Claim the primary virtual base as our primary virtual base.
925     Info->PrimaryVirtualBaseInfo = PrimaryVirtualBaseInfo;
926     PrimaryVirtualBaseInfo->Derived = Info;
927   }
928 
929   return Info;
930 }
931 
932 void RecordLayoutBuilder::ComputeBaseSubobjectInfo(const CXXRecordDecl *RD) {
933   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
934        E = RD->bases_end(); I != E; ++I) {
935     bool IsVirtual = I->isVirtual();
936 
937     const CXXRecordDecl *BaseDecl =
938       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
939 
940     // Compute the base subobject info for this base.
941     BaseSubobjectInfo *Info = ComputeBaseSubobjectInfo(BaseDecl, IsVirtual, 0);
942 
943     if (IsVirtual) {
944       // ComputeBaseInfo has already added this base for us.
945       assert(VirtualBaseInfo.count(BaseDecl) &&
946              "Did not add virtual base!");
947     } else {
948       // Add the base info to the map of non-virtual bases.
949       assert(!NonVirtualBaseInfo.count(BaseDecl) &&
950              "Non-virtual base already exists!");
951       NonVirtualBaseInfo.insert(std::make_pair(BaseDecl, Info));
952     }
953   }
954 }
955 
956 void
957 RecordLayoutBuilder::EnsureVTablePointerAlignment(CharUnits UnpackedBaseAlign) {
958   CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
959 
960   // The maximum field alignment overrides base align.
961   if (!MaxFieldAlignment.isZero()) {
962     BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
963     UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
964   }
965 
966   // Round up the current record size to pointer alignment.
967   setSize(getSize().RoundUpToAlignment(BaseAlign));
968   setDataSize(getSize());
969 
970   // Update the alignment.
971   UpdateAlignment(BaseAlign, UnpackedBaseAlign);
972 }
973 
974 void
975 RecordLayoutBuilder::LayoutNonVirtualBases(const CXXRecordDecl *RD) {
976   // Then, determine the primary base class.
977   DeterminePrimaryBase(RD);
978 
979   // Compute base subobject info.
980   ComputeBaseSubobjectInfo(RD);
981 
982   // If we have a primary base class, lay it out.
983   if (PrimaryBase) {
984     if (PrimaryBaseIsVirtual) {
985       // If the primary virtual base was a primary virtual base of some other
986       // base class we'll have to steal it.
987       BaseSubobjectInfo *PrimaryBaseInfo = VirtualBaseInfo.lookup(PrimaryBase);
988       PrimaryBaseInfo->Derived = 0;
989 
990       // We have a virtual primary base, insert it as an indirect primary base.
991       IndirectPrimaryBases.insert(PrimaryBase);
992 
993       assert(!VisitedVirtualBases.count(PrimaryBase) &&
994              "vbase already visited!");
995       VisitedVirtualBases.insert(PrimaryBase);
996 
997       LayoutVirtualBase(PrimaryBaseInfo);
998     } else {
999       BaseSubobjectInfo *PrimaryBaseInfo =
1000         NonVirtualBaseInfo.lookup(PrimaryBase);
1001       assert(PrimaryBaseInfo &&
1002              "Did not find base info for non-virtual primary base!");
1003 
1004       LayoutNonVirtualBase(PrimaryBaseInfo);
1005     }
1006 
1007   // If this class needs a vtable/vf-table and didn't get one from a
1008   // primary base, add it in now.
1009   } else if (needsVFTable(RD)) {
1010     assert(DataSize == 0 && "Vtable pointer must be at offset zero!");
1011     CharUnits PtrWidth =
1012       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
1013     CharUnits PtrAlign =
1014       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
1015     EnsureVTablePointerAlignment(PtrAlign);
1016     if (isMicrosoftCXXABI())
1017       VFPtrOffset = getSize();
1018     setSize(getSize() + PtrWidth);
1019     setDataSize(getSize());
1020   }
1021 
1022   bool HasDirectVirtualBases = false;
1023   bool HasNonVirtualBaseWithVBTable = false;
1024 
1025   // Now lay out the non-virtual bases.
1026   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1027          E = RD->bases_end(); I != E; ++I) {
1028 
1029     // Ignore virtual bases, but remember that we saw one.
1030     if (I->isVirtual()) {
1031       HasDirectVirtualBases = true;
1032       continue;
1033     }
1034 
1035     const CXXRecordDecl *BaseDecl =
1036       cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1037 
1038     // Remember if this base has virtual bases itself.
1039     if (BaseDecl->getNumVBases())
1040       HasNonVirtualBaseWithVBTable = true;
1041 
1042     // Skip the primary base, because we've already laid it out.  The
1043     // !PrimaryBaseIsVirtual check is required because we might have a
1044     // non-virtual base of the same type as a primary virtual base.
1045     if (BaseDecl == PrimaryBase && !PrimaryBaseIsVirtual)
1046       continue;
1047 
1048     // Lay out the base.
1049     BaseSubobjectInfo *BaseInfo = NonVirtualBaseInfo.lookup(BaseDecl);
1050     assert(BaseInfo && "Did not find base info for non-virtual base!");
1051 
1052     LayoutNonVirtualBase(BaseInfo);
1053   }
1054 
1055   // In the MS ABI, add the vb-table pointer if we need one, which is
1056   // whenever we have a virtual base and we can't re-use a vb-table
1057   // pointer from a non-virtual base.
1058   if (isMicrosoftCXXABI() &&
1059       HasDirectVirtualBases && !HasNonVirtualBaseWithVBTable) {
1060     CharUnits PtrWidth =
1061       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(0));
1062     CharUnits PtrAlign =
1063       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(0));
1064 
1065     // MSVC potentially over-aligns the vb-table pointer by giving it
1066     // the max alignment of all the non-virtual objects in the class.
1067     // This is completely unnecessary, but we're not here to pass
1068     // judgment.
1069     //
1070     // Note that we've only laid out the non-virtual bases, so on the
1071     // first pass Alignment won't be set correctly here, but if the
1072     // vb-table doesn't end up aligned correctly we'll come through
1073     // and redo the layout from scratch with the right alignment.
1074     //
1075     // TODO: Instead of doing this, just lay out the fields as if the
1076     // vb-table were at offset zero, then retroactively bump the field
1077     // offsets up.
1078     PtrAlign = std::max(PtrAlign, Alignment);
1079 
1080     EnsureVTablePointerAlignment(PtrAlign);
1081     VBPtrOffset = getSize();
1082     setSize(getSize() + PtrWidth);
1083     setDataSize(getSize());
1084   }
1085 }
1086 
1087 void RecordLayoutBuilder::LayoutNonVirtualBase(const BaseSubobjectInfo *Base) {
1088   // Layout the base.
1089   CharUnits Offset = LayoutBase(Base);
1090 
1091   // Add its base class offset.
1092   assert(!Bases.count(Base->Class) && "base offset already exists!");
1093   Bases.insert(std::make_pair(Base->Class, Offset));
1094 
1095   AddPrimaryVirtualBaseOffsets(Base, Offset);
1096 }
1097 
1098 void
1099 RecordLayoutBuilder::AddPrimaryVirtualBaseOffsets(const BaseSubobjectInfo *Info,
1100                                                   CharUnits Offset) {
1101   // This base isn't interesting, it has no virtual bases.
1102   if (!Info->Class->getNumVBases())
1103     return;
1104 
1105   // First, check if we have a virtual primary base to add offsets for.
1106   if (Info->PrimaryVirtualBaseInfo) {
1107     assert(Info->PrimaryVirtualBaseInfo->IsVirtual &&
1108            "Primary virtual base is not virtual!");
1109     if (Info->PrimaryVirtualBaseInfo->Derived == Info) {
1110       // Add the offset.
1111       assert(!VBases.count(Info->PrimaryVirtualBaseInfo->Class) &&
1112              "primary vbase offset already exists!");
1113       VBases.insert(std::make_pair(Info->PrimaryVirtualBaseInfo->Class,
1114                                    Offset));
1115 
1116       // Traverse the primary virtual base.
1117       AddPrimaryVirtualBaseOffsets(Info->PrimaryVirtualBaseInfo, Offset);
1118     }
1119   }
1120 
1121   // Now go through all direct non-virtual bases.
1122   const ASTRecordLayout &Layout = Context.getASTRecordLayout(Info->Class);
1123   for (unsigned I = 0, E = Info->Bases.size(); I != E; ++I) {
1124     const BaseSubobjectInfo *Base = Info->Bases[I];
1125     if (Base->IsVirtual)
1126       continue;
1127 
1128     CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base->Class);
1129     AddPrimaryVirtualBaseOffsets(Base, BaseOffset);
1130   }
1131 }
1132 
1133 /// needsVFTable - Return true if this class needs a vtable or vf-table
1134 /// when laid out as a base class.  These are treated the same because
1135 /// they're both always laid out at offset zero.
1136 ///
1137 /// This function assumes that the class has no primary base.
1138 bool RecordLayoutBuilder::needsVFTable(const CXXRecordDecl *RD) const {
1139   assert(!PrimaryBase);
1140 
1141   // In the Itanium ABI, every dynamic class needs a vtable: even if
1142   // this class has no virtual functions as a base class (i.e. it's
1143   // non-polymorphic or only has virtual functions from virtual
1144   // bases),x it still needs a vtable to locate its virtual bases.
1145   if (!isMicrosoftCXXABI())
1146     return RD->isDynamicClass();
1147 
1148   // In the MS ABI, we need a vfptr if the class has virtual functions
1149   // other than those declared by its virtual bases.  The AST doesn't
1150   // tell us that directly, and checking manually for virtual
1151   // functions that aren't overrides is expensive, but there are
1152   // some important shortcuts:
1153 
1154   //  - Non-polymorphic classes have no virtual functions at all.
1155   if (!RD->isPolymorphic()) return false;
1156 
1157   //  - Polymorphic classes with no virtual bases must either declare
1158   //    virtual functions directly or inherit them, but in the latter
1159   //    case we would have a primary base.
1160   if (RD->getNumVBases() == 0) return true;
1161 
1162   return hasNewVirtualFunction(RD);
1163 }
1164 
1165 /// hasNewVirtualFunction - Does the given polymorphic class declare a
1166 /// virtual function that does not override a method from any of its
1167 /// base classes?
1168 bool
1169 RecordLayoutBuilder::hasNewVirtualFunction(const CXXRecordDecl *RD) const {
1170   assert(RD->isPolymorphic());
1171   if (!RD->getNumBases())
1172     return true;
1173 
1174   for (CXXRecordDecl::method_iterator method = RD->method_begin();
1175        method != RD->method_end();
1176        ++method) {
1177     if (method->isVirtual() && !method->size_overridden_methods()) {
1178       return true;
1179     }
1180   }
1181   return false;
1182 }
1183 
1184 /// isPossiblePrimaryBase - Is the given base class an acceptable
1185 /// primary base class?
1186 bool
1187 RecordLayoutBuilder::isPossiblePrimaryBase(const CXXRecordDecl *Base) const {
1188   // In the Itanium ABI, a class can be a primary base class if it has
1189   // a vtable for any reason.
1190   if (!isMicrosoftCXXABI())
1191     return Base->isDynamicClass();
1192 
1193   // In the MS ABI, a class can only be a primary base class if it
1194   // provides a vf-table at a static offset.  That means it has to be
1195   // non-virtual base.  The existence of a separate vb-table means
1196   // that it's possible to get virtual functions only from a virtual
1197   // base, which we have to guard against.
1198 
1199   // First off, it has to have virtual functions.
1200   if (!Base->isPolymorphic()) return false;
1201 
1202   // If it has no virtual bases, then everything is at a static offset.
1203   if (!Base->getNumVBases()) return true;
1204 
1205   // Okay, just ask the base class's layout.
1206   return (Context.getASTRecordLayout(Base).getVFPtrOffset()
1207             != CharUnits::fromQuantity(-1));
1208 }
1209 
1210 void
1211 RecordLayoutBuilder::LayoutVirtualBases(const CXXRecordDecl *RD,
1212                                         const CXXRecordDecl *MostDerivedClass) {
1213   const CXXRecordDecl *PrimaryBase;
1214   bool PrimaryBaseIsVirtual;
1215 
1216   if (MostDerivedClass == RD) {
1217     PrimaryBase = this->PrimaryBase;
1218     PrimaryBaseIsVirtual = this->PrimaryBaseIsVirtual;
1219   } else {
1220     const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
1221     PrimaryBase = Layout.getPrimaryBase();
1222     PrimaryBaseIsVirtual = Layout.isPrimaryBaseVirtual();
1223   }
1224 
1225   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1226          E = RD->bases_end(); I != E; ++I) {
1227     assert(!I->getType()->isDependentType() &&
1228            "Cannot layout class with dependent bases.");
1229 
1230     const CXXRecordDecl *BaseDecl =
1231       cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl());
1232 
1233     if (I->isVirtual()) {
1234       if (PrimaryBase != BaseDecl || !PrimaryBaseIsVirtual) {
1235         bool IndirectPrimaryBase = IndirectPrimaryBases.count(BaseDecl);
1236 
1237         // Only lay out the virtual base if it's not an indirect primary base.
1238         if (!IndirectPrimaryBase) {
1239           // Only visit virtual bases once.
1240           if (!VisitedVirtualBases.insert(BaseDecl))
1241             continue;
1242 
1243           const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1244           assert(BaseInfo && "Did not find virtual base info!");
1245           LayoutVirtualBase(BaseInfo);
1246         }
1247       }
1248     }
1249 
1250     if (!BaseDecl->getNumVBases()) {
1251       // This base isn't interesting since it doesn't have any virtual bases.
1252       continue;
1253     }
1254 
1255     LayoutVirtualBases(BaseDecl, MostDerivedClass);
1256   }
1257 }
1258 
1259 void RecordLayoutBuilder::MSLayoutVirtualBases(const CXXRecordDecl *RD) {
1260 
1261   if (!RD->getNumVBases())
1262     return;
1263 
1264   // This is substantially simplified because there are no virtual
1265   // primary bases.
1266   for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
1267        E = RD->vbases_end(); I != E; ++I) {
1268     const CXXRecordDecl *BaseDecl = I->getType()->getAsCXXRecordDecl();
1269     const BaseSubobjectInfo *BaseInfo = VirtualBaseInfo.lookup(BaseDecl);
1270     assert(BaseInfo && "Did not find virtual base info!");
1271 
1272     LayoutVirtualBase(BaseInfo);
1273   }
1274 }
1275 
1276 void RecordLayoutBuilder::LayoutVirtualBase(const BaseSubobjectInfo *Base) {
1277   assert(!Base->Derived && "Trying to lay out a primary virtual base!");
1278 
1279   // Layout the base.
1280   CharUnits Offset = LayoutBase(Base);
1281 
1282   // Add its base class offset.
1283   assert(!VBases.count(Base->Class) && "vbase offset already exists!");
1284   VBases.insert(std::make_pair(Base->Class, Offset));
1285 
1286   AddPrimaryVirtualBaseOffsets(Base, Offset);
1287 }
1288 
1289 CharUnits RecordLayoutBuilder::LayoutBase(const BaseSubobjectInfo *Base) {
1290   const ASTRecordLayout &Layout = Context.getASTRecordLayout(Base->Class);
1291 
1292   // If we have an empty base class, try to place it at offset 0.
1293   if (Base->Class->isEmpty() &&
1294       EmptySubobjects->CanPlaceBaseAtOffset(Base, CharUnits::Zero())) {
1295     setSize(std::max(getSize(), Layout.getSize()));
1296 
1297     return CharUnits::Zero();
1298   }
1299 
1300   CharUnits UnpackedBaseAlign = Layout.getNonVirtualAlign();
1301   CharUnits BaseAlign = (Packed) ? CharUnits::One() : UnpackedBaseAlign;
1302 
1303   // The maximum field alignment overrides base align.
1304   if (!MaxFieldAlignment.isZero()) {
1305     BaseAlign = std::min(BaseAlign, MaxFieldAlignment);
1306     UnpackedBaseAlign = std::min(UnpackedBaseAlign, MaxFieldAlignment);
1307   }
1308 
1309   // Round up the current record size to the base's alignment boundary.
1310   CharUnits Offset = getDataSize().RoundUpToAlignment(BaseAlign);
1311 
1312   // Try to place the base.
1313   while (!EmptySubobjects->CanPlaceBaseAtOffset(Base, Offset))
1314     Offset += BaseAlign;
1315 
1316   if (!Base->Class->isEmpty()) {
1317     // Update the data size.
1318     setDataSize(Offset + Layout.getNonVirtualSize());
1319 
1320     setSize(std::max(getSize(), getDataSize()));
1321   } else
1322     setSize(std::max(getSize(), Offset + Layout.getSize()));
1323 
1324   // Remember max struct/class alignment.
1325   UpdateAlignment(BaseAlign, UnpackedBaseAlign);
1326 
1327   return Offset;
1328 }
1329 
1330 void RecordLayoutBuilder::InitializeLayout(const Decl *D) {
1331   if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
1332     IsUnion = RD->isUnion();
1333 
1334   Packed = D->hasAttr<PackedAttr>();
1335 
1336   IsMsStruct = D->hasAttr<MsStructAttr>();
1337 
1338   // Honor the default struct packing maximum alignment flag.
1339   if (unsigned DefaultMaxFieldAlignment = Context.getLangOptions().PackStruct) {
1340     MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
1341   }
1342 
1343   // mac68k alignment supersedes maximum field alignment and attribute aligned,
1344   // and forces all structures to have 2-byte alignment. The IBM docs on it
1345   // allude to additional (more complicated) semantics, especially with regard
1346   // to bit-fields, but gcc appears not to follow that.
1347   if (D->hasAttr<AlignMac68kAttr>()) {
1348     IsMac68kAlign = true;
1349     MaxFieldAlignment = CharUnits::fromQuantity(2);
1350     Alignment = CharUnits::fromQuantity(2);
1351   } else {
1352     if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>())
1353       MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment());
1354 
1355     if (unsigned MaxAlign = D->getMaxAlignment())
1356       UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign));
1357   }
1358 }
1359 
1360 void RecordLayoutBuilder::Layout(const RecordDecl *D) {
1361   InitializeLayout(D);
1362   LayoutFields(D);
1363 
1364   // Finally, round the size of the total struct up to the alignment of the
1365   // struct itself.
1366   FinishLayout(D);
1367 }
1368 
1369 void RecordLayoutBuilder::Layout(const CXXRecordDecl *RD) {
1370   InitializeLayout(RD);
1371 
1372   // Lay out the vtable and the non-virtual bases.
1373   LayoutNonVirtualBases(RD);
1374 
1375   LayoutFields(RD);
1376 
1377   NonVirtualSize = Context.toCharUnitsFromBits(
1378         llvm::RoundUpToAlignment(getSizeInBits(),
1379                                  Context.getTargetInfo().getCharAlign()));
1380   NonVirtualAlignment = Alignment;
1381 
1382   if (isMicrosoftCXXABI() &&
1383       NonVirtualSize != NonVirtualSize.RoundUpToAlignment(Alignment)) {
1384     CharUnits AlignMember =
1385       NonVirtualSize.RoundUpToAlignment(Alignment) - NonVirtualSize;
1386 
1387     setSize(getSize() + AlignMember);
1388     setDataSize(getSize());
1389 
1390     NonVirtualSize = Context.toCharUnitsFromBits(
1391                              llvm::RoundUpToAlignment(getSizeInBits(),
1392                              Context.getTargetInfo().getCharAlign()));
1393 
1394     MSLayoutVirtualBases(RD);
1395 
1396   } else {
1397     // Lay out the virtual bases and add the primary virtual base offsets.
1398     LayoutVirtualBases(RD, RD);
1399   }
1400 
1401   // Finally, round the size of the total struct up to the alignment
1402   // of the struct itself.  Amazingly, this does not occur in the MS
1403   // ABI after virtual base layout.
1404   if (!isMicrosoftCXXABI() || RD->getNumVBases())
1405     FinishLayout(RD);
1406 
1407 #ifndef NDEBUG
1408   // Check that we have base offsets for all bases.
1409   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1410        E = RD->bases_end(); I != E; ++I) {
1411     if (I->isVirtual())
1412       continue;
1413 
1414     const CXXRecordDecl *BaseDecl =
1415       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1416 
1417     assert(Bases.count(BaseDecl) && "Did not find base offset!");
1418   }
1419 
1420   // And all virtual bases.
1421   for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
1422        E = RD->vbases_end(); I != E; ++I) {
1423     const CXXRecordDecl *BaseDecl =
1424       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1425 
1426     assert(VBases.count(BaseDecl) && "Did not find base offset!");
1427   }
1428 #endif
1429 }
1430 
1431 void RecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) {
1432   if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
1433     const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD);
1434 
1435     UpdateAlignment(SL.getAlignment());
1436 
1437     // We start laying out ivars not at the end of the superclass
1438     // structure, but at the next byte following the last field.
1439     setSize(SL.getDataSize());
1440     setDataSize(getSize());
1441   }
1442 
1443   InitializeLayout(D);
1444   // Layout each ivar sequentially.
1445   for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD;
1446        IVD = IVD->getNextIvar())
1447     LayoutField(IVD);
1448 
1449   // Finally, round the size of the total struct up to the alignment of the
1450   // struct itself.
1451   FinishLayout(D);
1452 }
1453 
1454 void RecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
1455   // Layout each field, for now, just sequentially, respecting alignment.  In
1456   // the future, this will need to be tweakable by targets.
1457   const FieldDecl *LastFD = 0;
1458   ZeroLengthBitfield = 0;
1459   unsigned RemainingInAlignment = 0;
1460   for (RecordDecl::field_iterator Field = D->field_begin(),
1461        FieldEnd = D->field_end(); Field != FieldEnd; ++Field) {
1462     if (IsMsStruct) {
1463       FieldDecl *FD =  (*Field);
1464       if (Context.ZeroBitfieldFollowsBitfield(FD, LastFD))
1465         ZeroLengthBitfield = FD;
1466       // Zero-length bitfields following non-bitfield members are
1467       // ignored:
1468       else if (Context.ZeroBitfieldFollowsNonBitfield(FD, LastFD))
1469         continue;
1470       // FIXME. streamline these conditions into a simple one.
1471       else if (Context.BitfieldFollowsBitfield(FD, LastFD) ||
1472                Context.BitfieldFollowsNonBitfield(FD, LastFD) ||
1473                Context.NonBitfieldFollowsBitfield(FD, LastFD)) {
1474         // 1) Adjacent bit fields are packed into the same 1-, 2-, or
1475         // 4-byte allocation unit if the integral types are the same
1476         // size and if the next bit field fits into the current
1477         // allocation unit without crossing the boundary imposed by the
1478         // common alignment requirements of the bit fields.
1479         // 2) Establish a new alignment for a bitfield following
1480         // a non-bitfield if size of their types differ.
1481         // 3) Establish a new alignment for a non-bitfield following
1482         // a bitfield if size of their types differ.
1483         std::pair<uint64_t, unsigned> FieldInfo =
1484           Context.getTypeInfo(FD->getType());
1485         uint64_t TypeSize = FieldInfo.first;
1486         unsigned FieldAlign = FieldInfo.second;
1487         // This check is needed for 'long long' in -m32 mode.
1488         if (TypeSize > FieldAlign)
1489           FieldAlign = TypeSize;
1490         FieldInfo = Context.getTypeInfo(LastFD->getType());
1491         uint64_t TypeSizeLastFD = FieldInfo.first;
1492         unsigned FieldAlignLastFD = FieldInfo.second;
1493         // This check is needed for 'long long' in -m32 mode.
1494         if (TypeSizeLastFD > FieldAlignLastFD)
1495           FieldAlignLastFD = TypeSizeLastFD;
1496 
1497         if (TypeSizeLastFD != TypeSize) {
1498           if (RemainingInAlignment &&
1499               LastFD && LastFD->isBitField() &&
1500               LastFD->getBitWidthValue(Context)) {
1501             // If previous field was a bitfield with some remaining unfilled
1502             // bits, pad the field so current field starts on its type boundary.
1503             uint64_t FieldOffset =
1504             getDataSizeInBits() - UnfilledBitsInLastByte;
1505             uint64_t NewSizeInBits = RemainingInAlignment + FieldOffset;
1506             setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
1507                                                  Context.getTargetInfo().getCharAlign()));
1508             setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1509             RemainingInAlignment = 0;
1510           }
1511 
1512           uint64_t UnpaddedFieldOffset =
1513             getDataSizeInBits() - UnfilledBitsInLastByte;
1514           FieldAlign = std::max(FieldAlign, FieldAlignLastFD);
1515 
1516           // The maximum field alignment overrides the aligned attribute.
1517           if (!MaxFieldAlignment.isZero()) {
1518             unsigned MaxFieldAlignmentInBits =
1519               Context.toBits(MaxFieldAlignment);
1520             FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1521           }
1522 
1523           uint64_t NewSizeInBits =
1524             llvm::RoundUpToAlignment(UnpaddedFieldOffset, FieldAlign);
1525           setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
1526                                                Context.getTargetInfo().getCharAlign()));
1527           UnfilledBitsInLastByte = getDataSizeInBits() - NewSizeInBits;
1528           setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1529         }
1530         if (FD->isBitField()) {
1531           uint64_t FieldSize = FD->getBitWidthValue(Context);
1532           assert (FieldSize > 0 && "LayoutFields - ms_struct layout");
1533           if (RemainingInAlignment < FieldSize)
1534             RemainingInAlignment = TypeSize - FieldSize;
1535           else
1536             RemainingInAlignment -= FieldSize;
1537         }
1538       }
1539       else if (FD->isBitField()) {
1540         uint64_t FieldSize = FD->getBitWidthValue(Context);
1541         std::pair<uint64_t, unsigned> FieldInfo =
1542           Context.getTypeInfo(FD->getType());
1543         uint64_t TypeSize = FieldInfo.first;
1544         RemainingInAlignment = TypeSize - FieldSize;
1545       }
1546       LastFD = FD;
1547     }
1548     else if (!Context.getTargetInfo().useBitFieldTypeAlignment() &&
1549              Context.getTargetInfo().useZeroLengthBitfieldAlignment()) {
1550       FieldDecl *FD =  (*Field);
1551       if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
1552         ZeroLengthBitfield = FD;
1553     }
1554     LayoutField(*Field);
1555   }
1556   if (IsMsStruct && RemainingInAlignment &&
1557       LastFD && LastFD->isBitField() && LastFD->getBitWidthValue(Context)) {
1558     // If we ended a bitfield before the full length of the type then
1559     // pad the struct out to the full length of the last type.
1560     uint64_t FieldOffset =
1561       getDataSizeInBits() - UnfilledBitsInLastByte;
1562     uint64_t NewSizeInBits = RemainingInAlignment + FieldOffset;
1563     setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
1564                                          Context.getTargetInfo().getCharAlign()));
1565     setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1566   }
1567 }
1568 
1569 void RecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize,
1570                                              uint64_t TypeSize,
1571                                              bool FieldPacked,
1572                                              const FieldDecl *D) {
1573   assert(Context.getLangOptions().CPlusPlus &&
1574          "Can only have wide bit-fields in C++!");
1575 
1576   // Itanium C++ ABI 2.4:
1577   //   If sizeof(T)*8 < n, let T' be the largest integral POD type with
1578   //   sizeof(T')*8 <= n.
1579 
1580   QualType IntegralPODTypes[] = {
1581     Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy,
1582     Context.UnsignedLongTy, Context.UnsignedLongLongTy
1583   };
1584 
1585   QualType Type;
1586   for (unsigned I = 0, E = llvm::array_lengthof(IntegralPODTypes);
1587        I != E; ++I) {
1588     uint64_t Size = Context.getTypeSize(IntegralPODTypes[I]);
1589 
1590     if (Size > FieldSize)
1591       break;
1592 
1593     Type = IntegralPODTypes[I];
1594   }
1595   assert(!Type.isNull() && "Did not find a type!");
1596 
1597   CharUnits TypeAlign = Context.getTypeAlignInChars(Type);
1598 
1599   // We're not going to use any of the unfilled bits in the last byte.
1600   UnfilledBitsInLastByte = 0;
1601 
1602   uint64_t FieldOffset;
1603   uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastByte;
1604 
1605   if (IsUnion) {
1606     setDataSize(std::max(getDataSizeInBits(), FieldSize));
1607     FieldOffset = 0;
1608   } else {
1609     // The bitfield is allocated starting at the next offset aligned
1610     // appropriately for T', with length n bits.
1611     FieldOffset = llvm::RoundUpToAlignment(getDataSizeInBits(),
1612                                            Context.toBits(TypeAlign));
1613 
1614     uint64_t NewSizeInBits = FieldOffset + FieldSize;
1615 
1616     setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
1617                                          Context.getTargetInfo().getCharAlign()));
1618     UnfilledBitsInLastByte = getDataSizeInBits() - NewSizeInBits;
1619   }
1620 
1621   // Place this field at the current location.
1622   FieldOffsets.push_back(FieldOffset);
1623 
1624   CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset,
1625                     Context.toBits(TypeAlign), FieldPacked, D);
1626 
1627   // Update the size.
1628   setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1629 
1630   // Remember max struct/class alignment.
1631   UpdateAlignment(TypeAlign);
1632 }
1633 
1634 void RecordLayoutBuilder::LayoutBitField(const FieldDecl *D) {
1635   bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
1636   uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastByte;
1637   uint64_t FieldOffset = IsUnion ? 0 : UnpaddedFieldOffset;
1638   uint64_t FieldSize = D->getBitWidthValue(Context);
1639 
1640   std::pair<uint64_t, unsigned> FieldInfo = Context.getTypeInfo(D->getType());
1641   uint64_t TypeSize = FieldInfo.first;
1642   unsigned FieldAlign = FieldInfo.second;
1643 
1644   // This check is needed for 'long long' in -m32 mode.
1645   if (IsMsStruct && (TypeSize > FieldAlign))
1646     FieldAlign = TypeSize;
1647 
1648   if (ZeroLengthBitfield) {
1649     std::pair<uint64_t, unsigned> FieldInfo;
1650     unsigned ZeroLengthBitfieldAlignment;
1651     if (IsMsStruct) {
1652       // If a zero-length bitfield is inserted after a bitfield,
1653       // and the alignment of the zero-length bitfield is
1654       // greater than the member that follows it, `bar', `bar'
1655       // will be aligned as the type of the zero-length bitfield.
1656       if (ZeroLengthBitfield != D) {
1657         FieldInfo = Context.getTypeInfo(ZeroLengthBitfield->getType());
1658         ZeroLengthBitfieldAlignment = FieldInfo.second;
1659         // Ignore alignment of subsequent zero-length bitfields.
1660         if ((ZeroLengthBitfieldAlignment > FieldAlign) || (FieldSize == 0))
1661           FieldAlign = ZeroLengthBitfieldAlignment;
1662         if (FieldSize)
1663           ZeroLengthBitfield = 0;
1664       }
1665     } else {
1666       // The alignment of a zero-length bitfield affects the alignment
1667       // of the next member.  The alignment is the max of the zero
1668       // length bitfield's alignment and a target specific fixed value.
1669       unsigned ZeroLengthBitfieldBoundary =
1670         Context.getTargetInfo().getZeroLengthBitfieldBoundary();
1671       if (ZeroLengthBitfieldBoundary > FieldAlign)
1672         FieldAlign = ZeroLengthBitfieldBoundary;
1673     }
1674   }
1675 
1676   if (FieldSize > TypeSize) {
1677     LayoutWideBitField(FieldSize, TypeSize, FieldPacked, D);
1678     return;
1679   }
1680 
1681   // The align if the field is not packed. This is to check if the attribute
1682   // was unnecessary (-Wpacked).
1683   unsigned UnpackedFieldAlign = FieldAlign;
1684   uint64_t UnpackedFieldOffset = FieldOffset;
1685   if (!Context.getTargetInfo().useBitFieldTypeAlignment() && !ZeroLengthBitfield)
1686     UnpackedFieldAlign = 1;
1687 
1688   if (FieldPacked ||
1689       (!Context.getTargetInfo().useBitFieldTypeAlignment() && !ZeroLengthBitfield))
1690     FieldAlign = 1;
1691   FieldAlign = std::max(FieldAlign, D->getMaxAlignment());
1692   UnpackedFieldAlign = std::max(UnpackedFieldAlign, D->getMaxAlignment());
1693 
1694   // The maximum field alignment overrides the aligned attribute.
1695   if (!MaxFieldAlignment.isZero()) {
1696     unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment);
1697     FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1698     UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
1699   }
1700 
1701   // Check if we need to add padding to give the field the correct alignment.
1702   if (FieldSize == 0 || (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize)
1703     FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
1704 
1705   if (FieldSize == 0 ||
1706       (UnpackedFieldOffset & (UnpackedFieldAlign-1)) + FieldSize > TypeSize)
1707     UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1708                                                    UnpackedFieldAlign);
1709 
1710   // Padding members don't affect overall alignment, unless zero length bitfield
1711   // alignment is enabled.
1712   if (!D->getIdentifier() && !Context.getTargetInfo().useZeroLengthBitfieldAlignment())
1713     FieldAlign = UnpackedFieldAlign = 1;
1714 
1715   if (!IsMsStruct)
1716     ZeroLengthBitfield = 0;
1717 
1718   // Place this field at the current location.
1719   FieldOffsets.push_back(FieldOffset);
1720 
1721   CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset,
1722                     UnpackedFieldAlign, FieldPacked, D);
1723 
1724   // Update DataSize to include the last byte containing (part of) the bitfield.
1725   if (IsUnion) {
1726     // FIXME: I think FieldSize should be TypeSize here.
1727     setDataSize(std::max(getDataSizeInBits(), FieldSize));
1728   } else {
1729     uint64_t NewSizeInBits = FieldOffset + FieldSize;
1730 
1731     setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
1732                                          Context.getTargetInfo().getCharAlign()));
1733     UnfilledBitsInLastByte = getDataSizeInBits() - NewSizeInBits;
1734   }
1735 
1736   // Update the size.
1737   setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1738 
1739   // Remember max struct/class alignment.
1740   UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign),
1741                   Context.toCharUnitsFromBits(UnpackedFieldAlign));
1742 }
1743 
1744 void RecordLayoutBuilder::LayoutField(const FieldDecl *D) {
1745   if (D->isBitField()) {
1746     LayoutBitField(D);
1747     return;
1748   }
1749 
1750   uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastByte;
1751 
1752   // Reset the unfilled bits.
1753   UnfilledBitsInLastByte = 0;
1754 
1755   bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
1756   CharUnits FieldOffset =
1757     IsUnion ? CharUnits::Zero() : getDataSize();
1758   CharUnits FieldSize;
1759   CharUnits FieldAlign;
1760 
1761   if (D->getType()->isIncompleteArrayType()) {
1762     // This is a flexible array member; we can't directly
1763     // query getTypeInfo about these, so we figure it out here.
1764     // Flexible array members don't have any size, but they
1765     // have to be aligned appropriately for their element type.
1766     FieldSize = CharUnits::Zero();
1767     const ArrayType* ATy = Context.getAsArrayType(D->getType());
1768     FieldAlign = Context.getTypeAlignInChars(ATy->getElementType());
1769   } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) {
1770     unsigned AS = RT->getPointeeType().getAddressSpace();
1771     FieldSize =
1772       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(AS));
1773     FieldAlign =
1774       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(AS));
1775   } else {
1776     std::pair<CharUnits, CharUnits> FieldInfo =
1777       Context.getTypeInfoInChars(D->getType());
1778     FieldSize = FieldInfo.first;
1779     FieldAlign = FieldInfo.second;
1780 
1781     if (ZeroLengthBitfield) {
1782       CharUnits ZeroLengthBitfieldBoundary =
1783         Context.toCharUnitsFromBits(
1784           Context.getTargetInfo().getZeroLengthBitfieldBoundary());
1785       if (ZeroLengthBitfieldBoundary == CharUnits::Zero()) {
1786         // If a zero-length bitfield is inserted after a bitfield,
1787         // and the alignment of the zero-length bitfield is
1788         // greater than the member that follows it, `bar', `bar'
1789         // will be aligned as the type of the zero-length bitfield.
1790         std::pair<CharUnits, CharUnits> FieldInfo =
1791           Context.getTypeInfoInChars(ZeroLengthBitfield->getType());
1792         CharUnits ZeroLengthBitfieldAlignment = FieldInfo.second;
1793         if (ZeroLengthBitfieldAlignment > FieldAlign)
1794           FieldAlign = ZeroLengthBitfieldAlignment;
1795       } else if (ZeroLengthBitfieldBoundary > FieldAlign) {
1796         // Align 'bar' based on a fixed alignment specified by the target.
1797         assert(Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
1798                "ZeroLengthBitfieldBoundary should only be used in conjunction"
1799                " with useZeroLengthBitfieldAlignment.");
1800         FieldAlign = ZeroLengthBitfieldBoundary;
1801       }
1802       ZeroLengthBitfield = 0;
1803     }
1804 
1805     if (Context.getLangOptions().MSBitfields || IsMsStruct) {
1806       // If MS bitfield layout is required, figure out what type is being
1807       // laid out and align the field to the width of that type.
1808 
1809       // Resolve all typedefs down to their base type and round up the field
1810       // alignment if necessary.
1811       QualType T = Context.getBaseElementType(D->getType());
1812       if (const BuiltinType *BTy = T->getAs<BuiltinType>()) {
1813         CharUnits TypeSize = Context.getTypeSizeInChars(BTy);
1814         if (TypeSize > FieldAlign)
1815           FieldAlign = TypeSize;
1816       }
1817     }
1818   }
1819 
1820   // The align if the field is not packed. This is to check if the attribute
1821   // was unnecessary (-Wpacked).
1822   CharUnits UnpackedFieldAlign = FieldAlign;
1823   CharUnits UnpackedFieldOffset = FieldOffset;
1824 
1825   if (FieldPacked)
1826     FieldAlign = CharUnits::One();
1827   CharUnits MaxAlignmentInChars =
1828     Context.toCharUnitsFromBits(D->getMaxAlignment());
1829   FieldAlign = std::max(FieldAlign, MaxAlignmentInChars);
1830   UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars);
1831 
1832   // The maximum field alignment overrides the aligned attribute.
1833   if (!MaxFieldAlignment.isZero()) {
1834     FieldAlign = std::min(FieldAlign, MaxFieldAlignment);
1835     UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment);
1836   }
1837 
1838   // Round up the current record size to the field's alignment boundary.
1839   FieldOffset = FieldOffset.RoundUpToAlignment(FieldAlign);
1840   UnpackedFieldOffset =
1841     UnpackedFieldOffset.RoundUpToAlignment(UnpackedFieldAlign);
1842 
1843   if (!IsUnion && EmptySubobjects) {
1844     // Check if we can place the field at this offset.
1845     while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) {
1846       // We couldn't place the field at the offset. Try again at a new offset.
1847       FieldOffset += FieldAlign;
1848     }
1849   }
1850 
1851   // Place this field at the current location.
1852   FieldOffsets.push_back(Context.toBits(FieldOffset));
1853 
1854   CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset,
1855                     Context.toBits(UnpackedFieldOffset),
1856                     Context.toBits(UnpackedFieldAlign), FieldPacked, D);
1857 
1858   // Reserve space for this field.
1859   uint64_t FieldSizeInBits = Context.toBits(FieldSize);
1860   if (IsUnion)
1861     setSize(std::max(getSizeInBits(), FieldSizeInBits));
1862   else
1863     setSize(FieldOffset + FieldSize);
1864 
1865   // Update the data size.
1866   setDataSize(getSizeInBits());
1867 
1868   // Remember max struct/class alignment.
1869   UpdateAlignment(FieldAlign, UnpackedFieldAlign);
1870 }
1871 
1872 void RecordLayoutBuilder::FinishLayout(const NamedDecl *D) {
1873   // In C++, records cannot be of size 0.
1874   if (Context.getLangOptions().CPlusPlus && getSizeInBits() == 0) {
1875     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
1876       // Compatibility with gcc requires a class (pod or non-pod)
1877       // which is not empty but of size 0; such as having fields of
1878       // array of zero-length, remains of Size 0
1879       if (RD->isEmpty())
1880         setSize(CharUnits::One());
1881     }
1882     else
1883       setSize(CharUnits::One());
1884   }
1885   // Finally, round the size of the record up to the alignment of the
1886   // record itself.
1887   uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastByte;
1888   uint64_t UnpackedSizeInBits =
1889     llvm::RoundUpToAlignment(getSizeInBits(),
1890                              Context.toBits(UnpackedAlignment));
1891   CharUnits UnpackedSize = Context.toCharUnitsFromBits(UnpackedSizeInBits);
1892   setSize(llvm::RoundUpToAlignment(getSizeInBits(), Context.toBits(Alignment)));
1893 
1894   unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
1895   if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1896     // Warn if padding was introduced to the struct/class/union.
1897     if (getSizeInBits() > UnpaddedSize) {
1898       unsigned PadSize = getSizeInBits() - UnpaddedSize;
1899       bool InBits = true;
1900       if (PadSize % CharBitNum == 0) {
1901         PadSize = PadSize / CharBitNum;
1902         InBits = false;
1903       }
1904       Diag(RD->getLocation(), diag::warn_padded_struct_size)
1905           << Context.getTypeDeclType(RD)
1906           << PadSize
1907           << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
1908     }
1909 
1910     // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
1911     // bother since there won't be alignment issues.
1912     if (Packed && UnpackedAlignment > CharUnits::One() &&
1913         getSize() == UnpackedSize)
1914       Diag(D->getLocation(), diag::warn_unnecessary_packed)
1915           << Context.getTypeDeclType(RD);
1916   }
1917 }
1918 
1919 void RecordLayoutBuilder::UpdateAlignment(CharUnits NewAlignment,
1920                                           CharUnits UnpackedNewAlignment) {
1921   // The alignment is not modified when using 'mac68k' alignment.
1922   if (IsMac68kAlign)
1923     return;
1924 
1925   if (NewAlignment > Alignment) {
1926     assert(llvm::isPowerOf2_32(NewAlignment.getQuantity() &&
1927            "Alignment not a power of 2"));
1928     Alignment = NewAlignment;
1929   }
1930 
1931   if (UnpackedNewAlignment > UnpackedAlignment) {
1932     assert(llvm::isPowerOf2_32(UnpackedNewAlignment.getQuantity() &&
1933            "Alignment not a power of 2"));
1934     UnpackedAlignment = UnpackedNewAlignment;
1935   }
1936 }
1937 
1938 void RecordLayoutBuilder::CheckFieldPadding(uint64_t Offset,
1939                                             uint64_t UnpaddedOffset,
1940                                             uint64_t UnpackedOffset,
1941                                             unsigned UnpackedAlign,
1942                                             bool isPacked,
1943                                             const FieldDecl *D) {
1944   // We let objc ivars without warning, objc interfaces generally are not used
1945   // for padding tricks.
1946   if (isa<ObjCIvarDecl>(D))
1947     return;
1948 
1949   // Don't warn about structs created without a SourceLocation.  This can
1950   // be done by clients of the AST, such as codegen.
1951   if (D->getLocation().isInvalid())
1952     return;
1953 
1954   unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
1955 
1956   // Warn if padding was introduced to the struct/class.
1957   if (!IsUnion && Offset > UnpaddedOffset) {
1958     unsigned PadSize = Offset - UnpaddedOffset;
1959     bool InBits = true;
1960     if (PadSize % CharBitNum == 0) {
1961       PadSize = PadSize / CharBitNum;
1962       InBits = false;
1963     }
1964     if (D->getIdentifier())
1965       Diag(D->getLocation(), diag::warn_padded_struct_field)
1966           << (D->getParent()->isStruct() ? 0 : 1) // struct|class
1967           << Context.getTypeDeclType(D->getParent())
1968           << PadSize
1969           << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1) // plural or not
1970           << D->getIdentifier();
1971     else
1972       Diag(D->getLocation(), diag::warn_padded_struct_anon_field)
1973           << (D->getParent()->isStruct() ? 0 : 1) // struct|class
1974           << Context.getTypeDeclType(D->getParent())
1975           << PadSize
1976           << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
1977   }
1978 
1979   // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
1980   // bother since there won't be alignment issues.
1981   if (isPacked && UnpackedAlign > CharBitNum && Offset == UnpackedOffset)
1982     Diag(D->getLocation(), diag::warn_unnecessary_packed)
1983         << D->getIdentifier();
1984 }
1985 
1986 const CXXMethodDecl *
1987 RecordLayoutBuilder::ComputeKeyFunction(const CXXRecordDecl *RD) {
1988   // If a class isn't polymorphic it doesn't have a key function.
1989   if (!RD->isPolymorphic())
1990     return 0;
1991 
1992   // A class that is not externally visible doesn't have a key function. (Or
1993   // at least, there's no point to assigning a key function to such a class;
1994   // this doesn't affect the ABI.)
1995   if (RD->getLinkage() != ExternalLinkage)
1996     return 0;
1997 
1998   // Template instantiations don't have key functions,see Itanium C++ ABI 5.2.6.
1999   // Same behavior as GCC.
2000   TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
2001   if (TSK == TSK_ImplicitInstantiation ||
2002       TSK == TSK_ExplicitInstantiationDefinition)
2003     return 0;
2004 
2005   for (CXXRecordDecl::method_iterator I = RD->method_begin(),
2006          E = RD->method_end(); I != E; ++I) {
2007     const CXXMethodDecl *MD = *I;
2008 
2009     if (!MD->isVirtual())
2010       continue;
2011 
2012     if (MD->isPure())
2013       continue;
2014 
2015     // Ignore implicit member functions, they are always marked as inline, but
2016     // they don't have a body until they're defined.
2017     if (MD->isImplicit())
2018       continue;
2019 
2020     if (MD->isInlineSpecified())
2021       continue;
2022 
2023     if (MD->hasInlineBody())
2024       continue;
2025 
2026     // We found it.
2027     return MD;
2028   }
2029 
2030   return 0;
2031 }
2032 
2033 DiagnosticBuilder
2034 RecordLayoutBuilder::Diag(SourceLocation Loc, unsigned DiagID) {
2035   return Context.getDiagnostics().Report(Loc, DiagID);
2036 }
2037 
2038 /// getASTRecordLayout - Get or compute information about the layout of the
2039 /// specified record (struct/union/class), which indicates its size and field
2040 /// position information.
2041 const ASTRecordLayout &
2042 ASTContext::getASTRecordLayout(const RecordDecl *D) const {
2043   // These asserts test different things.  A record has a definition
2044   // as soon as we begin to parse the definition.  That definition is
2045   // not a complete definition (which is what isDefinition() tests)
2046   // until we *finish* parsing the definition.
2047   D = D->getDefinition();
2048   assert(D && "Cannot get layout of forward declarations!");
2049   assert(D->isCompleteDefinition() && "Cannot layout type before complete!");
2050 
2051   // Look up this layout, if already laid out, return what we have.
2052   // Note that we can't save a reference to the entry because this function
2053   // is recursive.
2054   const ASTRecordLayout *Entry = ASTRecordLayouts[D];
2055   if (Entry) return *Entry;
2056 
2057   const ASTRecordLayout *NewEntry;
2058 
2059   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2060     EmptySubobjectMap EmptySubobjects(*this, RD);
2061     RecordLayoutBuilder Builder(*this, &EmptySubobjects);
2062     Builder.Layout(RD);
2063 
2064     // MSVC gives the vb-table pointer an alignment equal to that of
2065     // the non-virtual part of the structure.  That's an inherently
2066     // multi-pass operation.  If our first pass doesn't give us
2067     // adequate alignment, try again with the specified minimum
2068     // alignment.  This is *much* more maintainable than computing the
2069     // alignment in advance in a separately-coded pass; it's also
2070     // significantly more efficient in the common case where the
2071     // vb-table doesn't need extra padding.
2072     if (Builder.VBPtrOffset != CharUnits::fromQuantity(-1) &&
2073         (Builder.VBPtrOffset % Builder.NonVirtualAlignment) != 0) {
2074       Builder.resetWithTargetAlignment(Builder.NonVirtualAlignment);
2075       Builder.Layout(RD);
2076     }
2077 
2078     // FIXME: This is not always correct. See the part about bitfields at
2079     // http://www.codesourcery.com/public/cxx-abi/abi.html#POD for more info.
2080     // FIXME: IsPODForThePurposeOfLayout should be stored in the record layout.
2081     // This does not affect the calculations of MSVC layouts
2082     bool IsPODForThePurposeOfLayout =
2083       (!Builder.isMicrosoftCXXABI() && cast<CXXRecordDecl>(D)->isPOD());
2084 
2085     // FIXME: This should be done in FinalizeLayout.
2086     CharUnits DataSize =
2087       IsPODForThePurposeOfLayout ? Builder.getSize() : Builder.getDataSize();
2088     CharUnits NonVirtualSize =
2089       IsPODForThePurposeOfLayout ? DataSize : Builder.NonVirtualSize;
2090 
2091     NewEntry =
2092       new (*this) ASTRecordLayout(*this, Builder.getSize(),
2093                                   Builder.Alignment,
2094                                   Builder.VFPtrOffset,
2095                                   Builder.VBPtrOffset,
2096                                   DataSize,
2097                                   Builder.FieldOffsets.data(),
2098                                   Builder.FieldOffsets.size(),
2099                                   NonVirtualSize,
2100                                   Builder.NonVirtualAlignment,
2101                                   EmptySubobjects.SizeOfLargestEmptySubobject,
2102                                   Builder.PrimaryBase,
2103                                   Builder.PrimaryBaseIsVirtual,
2104                                   Builder.Bases, Builder.VBases);
2105   } else {
2106     RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
2107     Builder.Layout(D);
2108 
2109     NewEntry =
2110       new (*this) ASTRecordLayout(*this, Builder.getSize(),
2111                                   Builder.Alignment,
2112                                   Builder.getSize(),
2113                                   Builder.FieldOffsets.data(),
2114                                   Builder.FieldOffsets.size());
2115   }
2116 
2117   ASTRecordLayouts[D] = NewEntry;
2118 
2119   if (getLangOptions().DumpRecordLayouts) {
2120     llvm::errs() << "\n*** Dumping AST Record Layout\n";
2121     DumpRecordLayout(D, llvm::errs());
2122   }
2123 
2124   return *NewEntry;
2125 }
2126 
2127 const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) {
2128   RD = cast<CXXRecordDecl>(RD->getDefinition());
2129   assert(RD && "Cannot get key function for forward declarations!");
2130 
2131   const CXXMethodDecl *&Entry = KeyFunctions[RD];
2132   if (!Entry)
2133     Entry = RecordLayoutBuilder::ComputeKeyFunction(RD);
2134 
2135   return Entry;
2136 }
2137 
2138 /// getObjCLayout - Get or compute information about the layout of the
2139 /// given interface.
2140 ///
2141 /// \param Impl - If given, also include the layout of the interface's
2142 /// implementation. This may differ by including synthesized ivars.
2143 const ASTRecordLayout &
2144 ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
2145                           const ObjCImplementationDecl *Impl) const {
2146   assert(!D->isForwardDecl() && "Invalid interface decl!");
2147 
2148   // Look up this layout, if already laid out, return what we have.
2149   ObjCContainerDecl *Key =
2150     Impl ? (ObjCContainerDecl*) Impl : (ObjCContainerDecl*) D;
2151   if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
2152     return *Entry;
2153 
2154   // Add in synthesized ivar count if laying out an implementation.
2155   if (Impl) {
2156     unsigned SynthCount = CountNonClassIvars(D);
2157     // If there aren't any sythesized ivars then reuse the interface
2158     // entry. Note we can't cache this because we simply free all
2159     // entries later; however we shouldn't look up implementations
2160     // frequently.
2161     if (SynthCount == 0)
2162       return getObjCLayout(D, 0);
2163   }
2164 
2165   RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
2166   Builder.Layout(D);
2167 
2168   const ASTRecordLayout *NewEntry =
2169     new (*this) ASTRecordLayout(*this, Builder.getSize(),
2170                                 Builder.Alignment,
2171                                 Builder.getDataSize(),
2172                                 Builder.FieldOffsets.data(),
2173                                 Builder.FieldOffsets.size());
2174 
2175   ObjCLayouts[Key] = NewEntry;
2176 
2177   return *NewEntry;
2178 }
2179 
2180 static void PrintOffset(raw_ostream &OS,
2181                         CharUnits Offset, unsigned IndentLevel) {
2182   OS << llvm::format("%4" PRId64 " | ", (int64_t)Offset.getQuantity());
2183   OS.indent(IndentLevel * 2);
2184 }
2185 
2186 static void DumpCXXRecordLayout(raw_ostream &OS,
2187                                 const CXXRecordDecl *RD, const ASTContext &C,
2188                                 CharUnits Offset,
2189                                 unsigned IndentLevel,
2190                                 const char* Description,
2191                                 bool IncludeVirtualBases) {
2192   const ASTRecordLayout &Layout = C.getASTRecordLayout(RD);
2193 
2194   PrintOffset(OS, Offset, IndentLevel);
2195   OS << C.getTypeDeclType(const_cast<CXXRecordDecl *>(RD)).getAsString();
2196   if (Description)
2197     OS << ' ' << Description;
2198   if (RD->isEmpty())
2199     OS << " (empty)";
2200   OS << '\n';
2201 
2202   IndentLevel++;
2203 
2204   const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
2205   bool HasVfptr = Layout.getVFPtrOffset() != CharUnits::fromQuantity(-1);
2206   bool HasVbptr = Layout.getVBPtrOffset() != CharUnits::fromQuantity(-1);
2207 
2208   // Vtable pointer.
2209   if (RD->isDynamicClass() && !PrimaryBase &&
2210       C.getTargetInfo().getCXXABI() != CXXABI_Microsoft) {
2211     PrintOffset(OS, Offset, IndentLevel);
2212     OS << '(' << *RD << " vtable pointer)\n";
2213   }
2214 
2215   // Dump (non-virtual) bases
2216   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
2217          E = RD->bases_end(); I != E; ++I) {
2218     assert(!I->getType()->isDependentType() &&
2219            "Cannot layout class with dependent bases.");
2220     if (I->isVirtual())
2221       continue;
2222 
2223     const CXXRecordDecl *Base =
2224       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
2225 
2226     CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
2227 
2228     DumpCXXRecordLayout(OS, Base, C, BaseOffset, IndentLevel,
2229                         Base == PrimaryBase ? "(primary base)" : "(base)",
2230                         /*IncludeVirtualBases=*/false);
2231   }
2232 
2233   // vfptr and vbptr (for Microsoft C++ ABI)
2234   if (HasVfptr) {
2235     PrintOffset(OS, Offset + Layout.getVFPtrOffset(), IndentLevel);
2236     OS << '(' << *RD << " vftable pointer)\n";
2237   }
2238   if (HasVbptr) {
2239     PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel);
2240     OS << '(' << *RD << " vbtable pointer)\n";
2241   }
2242 
2243   // Dump fields.
2244   uint64_t FieldNo = 0;
2245   for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2246          E = RD->field_end(); I != E; ++I, ++FieldNo) {
2247     const FieldDecl *Field = *I;
2248     CharUnits FieldOffset = Offset +
2249       C.toCharUnitsFromBits(Layout.getFieldOffset(FieldNo));
2250 
2251     if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
2252       if (const CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2253         DumpCXXRecordLayout(OS, D, C, FieldOffset, IndentLevel,
2254                             Field->getName().data(),
2255                             /*IncludeVirtualBases=*/true);
2256         continue;
2257       }
2258     }
2259 
2260     PrintOffset(OS, FieldOffset, IndentLevel);
2261     OS << Field->getType().getAsString() << ' ' << *Field << '\n';
2262   }
2263 
2264   if (!IncludeVirtualBases)
2265     return;
2266 
2267   // Dump virtual bases.
2268   for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
2269          E = RD->vbases_end(); I != E; ++I) {
2270     assert(I->isVirtual() && "Found non-virtual class!");
2271     const CXXRecordDecl *VBase =
2272       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
2273 
2274     CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
2275     DumpCXXRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel,
2276                         VBase == PrimaryBase ?
2277                         "(primary virtual base)" : "(virtual base)",
2278                         /*IncludeVirtualBases=*/false);
2279   }
2280 
2281   OS << "  sizeof=" << Layout.getSize().getQuantity();
2282   OS << ", dsize=" << Layout.getDataSize().getQuantity();
2283   OS << ", align=" << Layout.getAlignment().getQuantity() << '\n';
2284   OS << "  nvsize=" << Layout.getNonVirtualSize().getQuantity();
2285   OS << ", nvalign=" << Layout.getNonVirtualAlign().getQuantity() << '\n';
2286   OS << '\n';
2287 }
2288 
2289 void ASTContext::DumpRecordLayout(const RecordDecl *RD,
2290                                   raw_ostream &OS) const {
2291   const ASTRecordLayout &Info = getASTRecordLayout(RD);
2292 
2293   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2294     return DumpCXXRecordLayout(OS, CXXRD, *this, CharUnits(), 0, 0,
2295                                /*IncludeVirtualBases=*/true);
2296 
2297   OS << "Type: " << getTypeDeclType(RD).getAsString() << "\n";
2298   OS << "Record: ";
2299   RD->dump();
2300   OS << "\nLayout: ";
2301   OS << "<ASTRecordLayout\n";
2302   OS << "  Size:" << toBits(Info.getSize()) << "\n";
2303   OS << "  DataSize:" << toBits(Info.getDataSize()) << "\n";
2304   OS << "  Alignment:" << toBits(Info.getAlignment()) << "\n";
2305   OS << "  FieldOffsets: [";
2306   for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) {
2307     if (i) OS << ", ";
2308     OS << Info.getFieldOffset(i);
2309   }
2310   OS << "]>\n";
2311 }
2312