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