]> CyberLeo.Net >> Repos - FreeBSD/stable/9.git/blob - contrib/llvm/tools/clang/lib/AST/RecordLayoutBuilder.cpp
MFC r244628:
[FreeBSD/stable/9.git] / contrib / llvm / tools / clang / 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 &) LLVM_DELETED_FUNCTION;
793   void operator=(const RecordLayoutBuilder &) LLVM_DELETED_FUNCTION;
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     if (InferAlignment && Offset < getDataSize().RoundUpToAlignment(BaseAlign)){
1562       // The externally-supplied base offset is before the base offset we
1563       // computed. Assume that the structure is packed.
1564       Alignment = CharUnits::One();
1565       InferAlignment = false;
1566     }
1567   }
1568   
1569   if (!Base->Class->isEmpty()) {
1570     // Update the data size.
1571     setDataSize(Offset + Layout.getNonVirtualSize());
1572
1573     setSize(std::max(getSize(), getDataSize()));
1574   } else
1575     setSize(std::max(getSize(), Offset + Layout.getSize()));
1576
1577   // Remember max struct/class alignment.
1578   UpdateAlignment(BaseAlign, UnpackedBaseAlign);
1579
1580   return Offset;
1581 }
1582
1583 void RecordLayoutBuilder::InitializeLayout(const Decl *D) {
1584   if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
1585     IsUnion = RD->isUnion();
1586     IsMsStruct = RD->isMsStruct(Context);
1587   }
1588
1589   Packed = D->hasAttr<PackedAttr>();  
1590
1591   // Honor the default struct packing maximum alignment flag.
1592   if (unsigned DefaultMaxFieldAlignment = Context.getLangOpts().PackStruct) {
1593     MaxFieldAlignment = CharUnits::fromQuantity(DefaultMaxFieldAlignment);
1594   }
1595
1596   // mac68k alignment supersedes maximum field alignment and attribute aligned,
1597   // and forces all structures to have 2-byte alignment. The IBM docs on it
1598   // allude to additional (more complicated) semantics, especially with regard
1599   // to bit-fields, but gcc appears not to follow that.
1600   if (D->hasAttr<AlignMac68kAttr>()) {
1601     IsMac68kAlign = true;
1602     MaxFieldAlignment = CharUnits::fromQuantity(2);
1603     Alignment = CharUnits::fromQuantity(2);
1604   } else {
1605     if (const MaxFieldAlignmentAttr *MFAA = D->getAttr<MaxFieldAlignmentAttr>())
1606       MaxFieldAlignment = Context.toCharUnitsFromBits(MFAA->getAlignment());
1607
1608     if (unsigned MaxAlign = D->getMaxAlignment())
1609       UpdateAlignment(Context.toCharUnitsFromBits(MaxAlign));
1610   }
1611   
1612   // If there is an external AST source, ask it for the various offsets.
1613   if (const RecordDecl *RD = dyn_cast<RecordDecl>(D))
1614     if (ExternalASTSource *External = Context.getExternalSource()) {
1615       ExternalLayout = External->layoutRecordType(RD, 
1616                                                   ExternalSize,
1617                                                   ExternalAlign,
1618                                                   ExternalFieldOffsets,
1619                                                   ExternalBaseOffsets,
1620                                                   ExternalVirtualBaseOffsets);
1621       
1622       // Update based on external alignment.
1623       if (ExternalLayout) {
1624         if (ExternalAlign > 0) {
1625           Alignment = Context.toCharUnitsFromBits(ExternalAlign);
1626         } else {
1627           // The external source didn't have alignment information; infer it.
1628           InferAlignment = true;
1629         }
1630       }
1631     }
1632 }
1633
1634 void RecordLayoutBuilder::Layout(const RecordDecl *D) {
1635   InitializeLayout(D);
1636   LayoutFields(D);
1637
1638   // Finally, round the size of the total struct up to the alignment of the
1639   // struct itself.
1640   FinishLayout(D);
1641 }
1642
1643 void RecordLayoutBuilder::Layout(const CXXRecordDecl *RD) {
1644   InitializeLayout(RD);
1645
1646   // Lay out the vtable and the non-virtual bases.
1647   LayoutNonVirtualBases(RD);
1648
1649   LayoutFields(RD);
1650
1651   NonVirtualSize = Context.toCharUnitsFromBits(
1652         llvm::RoundUpToAlignment(getSizeInBits(), 
1653                                  Context.getTargetInfo().getCharAlign()));
1654   NonVirtualAlignment = Alignment;
1655
1656   if (isMicrosoftCXXABI()) {
1657     if (NonVirtualSize != NonVirtualSize.RoundUpToAlignment(Alignment)) {
1658     CharUnits AlignMember = 
1659       NonVirtualSize.RoundUpToAlignment(Alignment) - NonVirtualSize;
1660
1661     setSize(getSize() + AlignMember);
1662     setDataSize(getSize());
1663
1664     NonVirtualSize = Context.toCharUnitsFromBits(
1665                              llvm::RoundUpToAlignment(getSizeInBits(),
1666                              Context.getTargetInfo().getCharAlign()));
1667     }
1668
1669     MSLayoutVirtualBases(RD);
1670   } else {
1671     // Lay out the virtual bases and add the primary virtual base offsets.
1672     LayoutVirtualBases(RD, RD);
1673   }
1674
1675   // Finally, round the size of the total struct up to the alignment
1676   // of the struct itself.
1677   FinishLayout(RD);
1678
1679 #ifndef NDEBUG
1680   // Check that we have base offsets for all bases.
1681   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
1682        E = RD->bases_end(); I != E; ++I) {
1683     if (I->isVirtual())
1684       continue;
1685
1686     const CXXRecordDecl *BaseDecl =
1687       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1688
1689     assert(Bases.count(BaseDecl) && "Did not find base offset!");
1690   }
1691
1692   // And all virtual bases.
1693   for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
1694        E = RD->vbases_end(); I != E; ++I) {
1695     const CXXRecordDecl *BaseDecl =
1696       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
1697
1698     assert(VBases.count(BaseDecl) && "Did not find base offset!");
1699   }
1700 #endif
1701 }
1702
1703 void RecordLayoutBuilder::Layout(const ObjCInterfaceDecl *D) {
1704   if (ObjCInterfaceDecl *SD = D->getSuperClass()) {
1705     const ASTRecordLayout &SL = Context.getASTObjCInterfaceLayout(SD);
1706
1707     UpdateAlignment(SL.getAlignment());
1708
1709     // We start laying out ivars not at the end of the superclass
1710     // structure, but at the next byte following the last field.
1711     setSize(SL.getDataSize());
1712     setDataSize(getSize());
1713   }
1714
1715   InitializeLayout(D);
1716   // Layout each ivar sequentially.
1717   for (const ObjCIvarDecl *IVD = D->all_declared_ivar_begin(); IVD;
1718        IVD = IVD->getNextIvar())
1719     LayoutField(IVD);
1720
1721   // Finally, round the size of the total struct up to the alignment of the
1722   // struct itself.
1723   FinishLayout(D);
1724 }
1725
1726 void RecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
1727   // Layout each field, for now, just sequentially, respecting alignment.  In
1728   // the future, this will need to be tweakable by targets.
1729   const FieldDecl *LastFD = 0;
1730   ZeroLengthBitfield = 0;
1731   unsigned RemainingInAlignment = 0;
1732   for (RecordDecl::field_iterator Field = D->field_begin(),
1733        FieldEnd = D->field_end(); Field != FieldEnd; ++Field) {
1734     if (IsMsStruct) {
1735       FieldDecl *FD = *Field;
1736       if (Context.ZeroBitfieldFollowsBitfield(FD, LastFD))
1737         ZeroLengthBitfield = FD;
1738       // Zero-length bitfields following non-bitfield members are
1739       // ignored:
1740       else if (Context.ZeroBitfieldFollowsNonBitfield(FD, LastFD))
1741         continue;
1742       // FIXME. streamline these conditions into a simple one.
1743       else if (Context.BitfieldFollowsBitfield(FD, LastFD) ||
1744                Context.BitfieldFollowsNonBitfield(FD, LastFD) ||
1745                Context.NonBitfieldFollowsBitfield(FD, LastFD)) {
1746         // 1) Adjacent bit fields are packed into the same 1-, 2-, or
1747         // 4-byte allocation unit if the integral types are the same
1748         // size and if the next bit field fits into the current
1749         // allocation unit without crossing the boundary imposed by the
1750         // common alignment requirements of the bit fields.
1751         // 2) Establish a new alignment for a bitfield following
1752         // a non-bitfield if size of their types differ.
1753         // 3) Establish a new alignment for a non-bitfield following
1754         // a bitfield if size of their types differ.
1755         std::pair<uint64_t, unsigned> FieldInfo = 
1756           Context.getTypeInfo(FD->getType());
1757         uint64_t TypeSize = FieldInfo.first;
1758         unsigned FieldAlign = FieldInfo.second;
1759         // This check is needed for 'long long' in -m32 mode.
1760         if (TypeSize > FieldAlign &&
1761             (Context.hasSameType(FD->getType(), 
1762                                 Context.UnsignedLongLongTy) 
1763              ||Context.hasSameType(FD->getType(), 
1764                                    Context.LongLongTy)))
1765           FieldAlign = TypeSize;
1766         FieldInfo = Context.getTypeInfo(LastFD->getType());
1767         uint64_t TypeSizeLastFD = FieldInfo.first;
1768         unsigned FieldAlignLastFD = FieldInfo.second;
1769         // This check is needed for 'long long' in -m32 mode.
1770         if (TypeSizeLastFD > FieldAlignLastFD &&
1771             (Context.hasSameType(LastFD->getType(), 
1772                                 Context.UnsignedLongLongTy)
1773              || Context.hasSameType(LastFD->getType(), 
1774                                     Context.LongLongTy)))
1775           FieldAlignLastFD = TypeSizeLastFD;
1776         
1777         if (TypeSizeLastFD != TypeSize) {
1778           if (RemainingInAlignment &&
1779               LastFD && LastFD->isBitField() &&
1780               LastFD->getBitWidthValue(Context)) {
1781             // If previous field was a bitfield with some remaining unfilled
1782             // bits, pad the field so current field starts on its type boundary.
1783             uint64_t FieldOffset = 
1784             getDataSizeInBits() - UnfilledBitsInLastByte;
1785             uint64_t NewSizeInBits = RemainingInAlignment + FieldOffset;
1786             setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
1787                                                  Context.getTargetInfo().getCharAlign()));
1788             setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1789             RemainingInAlignment = 0;
1790           }
1791           
1792           uint64_t UnpaddedFieldOffset = 
1793             getDataSizeInBits() - UnfilledBitsInLastByte;
1794           FieldAlign = std::max(FieldAlign, FieldAlignLastFD);
1795           
1796           // The maximum field alignment overrides the aligned attribute.
1797           if (!MaxFieldAlignment.isZero()) {
1798             unsigned MaxFieldAlignmentInBits = 
1799               Context.toBits(MaxFieldAlignment);
1800             FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1801           }
1802           
1803           uint64_t NewSizeInBits = 
1804             llvm::RoundUpToAlignment(UnpaddedFieldOffset, FieldAlign);
1805           setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
1806                                                Context.getTargetInfo().getCharAlign()));
1807           UnfilledBitsInLastByte = getDataSizeInBits() - NewSizeInBits;
1808           setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1809         }
1810         if (FD->isBitField()) {
1811           uint64_t FieldSize = FD->getBitWidthValue(Context);
1812           assert (FieldSize > 0 && "LayoutFields - ms_struct layout");
1813           if (RemainingInAlignment < FieldSize)
1814             RemainingInAlignment = TypeSize - FieldSize;
1815           else
1816             RemainingInAlignment -= FieldSize;
1817         }
1818       }
1819       else if (FD->isBitField()) {
1820         uint64_t FieldSize = FD->getBitWidthValue(Context);
1821         std::pair<uint64_t, unsigned> FieldInfo = 
1822           Context.getTypeInfo(FD->getType());
1823         uint64_t TypeSize = FieldInfo.first;
1824         RemainingInAlignment = TypeSize - FieldSize;
1825       }
1826       LastFD = FD;
1827     }
1828     else if (!Context.getTargetInfo().useBitFieldTypeAlignment() &&
1829              Context.getTargetInfo().useZeroLengthBitfieldAlignment()) {             
1830       if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
1831         ZeroLengthBitfield = *Field;
1832     }
1833     LayoutField(*Field);
1834   }
1835   if (IsMsStruct && RemainingInAlignment &&
1836       LastFD && LastFD->isBitField() && LastFD->getBitWidthValue(Context)) {
1837     // If we ended a bitfield before the full length of the type then
1838     // pad the struct out to the full length of the last type.
1839     uint64_t FieldOffset = 
1840       getDataSizeInBits() - UnfilledBitsInLastByte;
1841     uint64_t NewSizeInBits = RemainingInAlignment + FieldOffset;
1842     setDataSize(llvm::RoundUpToAlignment(NewSizeInBits,
1843                                          Context.getTargetInfo().getCharAlign()));
1844     setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1845   }
1846 }
1847
1848 void RecordLayoutBuilder::LayoutWideBitField(uint64_t FieldSize,
1849                                              uint64_t TypeSize,
1850                                              bool FieldPacked,
1851                                              const FieldDecl *D) {
1852   assert(Context.getLangOpts().CPlusPlus &&
1853          "Can only have wide bit-fields in C++!");
1854
1855   // Itanium C++ ABI 2.4:
1856   //   If sizeof(T)*8 < n, let T' be the largest integral POD type with
1857   //   sizeof(T')*8 <= n.
1858
1859   QualType IntegralPODTypes[] = {
1860     Context.UnsignedCharTy, Context.UnsignedShortTy, Context.UnsignedIntTy,
1861     Context.UnsignedLongTy, Context.UnsignedLongLongTy
1862   };
1863
1864   QualType Type;
1865   for (unsigned I = 0, E = llvm::array_lengthof(IntegralPODTypes);
1866        I != E; ++I) {
1867     uint64_t Size = Context.getTypeSize(IntegralPODTypes[I]);
1868
1869     if (Size > FieldSize)
1870       break;
1871
1872     Type = IntegralPODTypes[I];
1873   }
1874   assert(!Type.isNull() && "Did not find a type!");
1875
1876   CharUnits TypeAlign = Context.getTypeAlignInChars(Type);
1877
1878   // We're not going to use any of the unfilled bits in the last byte.
1879   UnfilledBitsInLastByte = 0;
1880
1881   uint64_t FieldOffset;
1882   uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastByte;
1883
1884   if (IsUnion) {
1885     setDataSize(std::max(getDataSizeInBits(), FieldSize));
1886     FieldOffset = 0;
1887   } else {
1888     // The bitfield is allocated starting at the next offset aligned 
1889     // appropriately for T', with length n bits.
1890     FieldOffset = llvm::RoundUpToAlignment(getDataSizeInBits(), 
1891                                            Context.toBits(TypeAlign));
1892
1893     uint64_t NewSizeInBits = FieldOffset + FieldSize;
1894
1895     setDataSize(llvm::RoundUpToAlignment(NewSizeInBits, 
1896                                          Context.getTargetInfo().getCharAlign()));
1897     UnfilledBitsInLastByte = getDataSizeInBits() - NewSizeInBits;
1898   }
1899
1900   // Place this field at the current location.
1901   FieldOffsets.push_back(FieldOffset);
1902
1903   CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, FieldOffset,
1904                     Context.toBits(TypeAlign), FieldPacked, D);
1905
1906   // Update the size.
1907   setSize(std::max(getSizeInBits(), getDataSizeInBits()));
1908
1909   // Remember max struct/class alignment.
1910   UpdateAlignment(TypeAlign);
1911 }
1912
1913 void RecordLayoutBuilder::LayoutBitField(const FieldDecl *D) {
1914   bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
1915   uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastByte;
1916   uint64_t FieldOffset = IsUnion ? 0 : UnpaddedFieldOffset;
1917   uint64_t FieldSize = D->getBitWidthValue(Context);
1918
1919   std::pair<uint64_t, unsigned> FieldInfo = Context.getTypeInfo(D->getType());
1920   uint64_t TypeSize = FieldInfo.first;
1921   unsigned FieldAlign = FieldInfo.second;
1922   
1923   // This check is needed for 'long long' in -m32 mode.
1924   if (IsMsStruct && (TypeSize > FieldAlign) && 
1925       (Context.hasSameType(D->getType(), 
1926                            Context.UnsignedLongLongTy) 
1927        || Context.hasSameType(D->getType(), Context.LongLongTy)))
1928     FieldAlign = TypeSize;
1929
1930   if (ZeroLengthBitfield) {
1931     std::pair<uint64_t, unsigned> FieldInfo;
1932     unsigned ZeroLengthBitfieldAlignment;
1933     if (IsMsStruct) {
1934       // If a zero-length bitfield is inserted after a bitfield,
1935       // and the alignment of the zero-length bitfield is
1936       // greater than the member that follows it, `bar', `bar' 
1937       // will be aligned as the type of the zero-length bitfield.
1938       if (ZeroLengthBitfield != D) {
1939         FieldInfo = Context.getTypeInfo(ZeroLengthBitfield->getType());
1940         ZeroLengthBitfieldAlignment = FieldInfo.second;
1941         // Ignore alignment of subsequent zero-length bitfields.
1942         if ((ZeroLengthBitfieldAlignment > FieldAlign) || (FieldSize == 0))
1943           FieldAlign = ZeroLengthBitfieldAlignment;
1944         if (FieldSize)
1945           ZeroLengthBitfield = 0;
1946       }
1947     } else {
1948       // The alignment of a zero-length bitfield affects the alignment
1949       // of the next member.  The alignment is the max of the zero 
1950       // length bitfield's alignment and a target specific fixed value.
1951       unsigned ZeroLengthBitfieldBoundary =
1952         Context.getTargetInfo().getZeroLengthBitfieldBoundary();
1953       if (ZeroLengthBitfieldBoundary > FieldAlign)
1954         FieldAlign = ZeroLengthBitfieldBoundary;
1955     }
1956   }
1957
1958   if (FieldSize > TypeSize) {
1959     LayoutWideBitField(FieldSize, TypeSize, FieldPacked, D);
1960     return;
1961   }
1962
1963   // The align if the field is not packed. This is to check if the attribute
1964   // was unnecessary (-Wpacked).
1965   unsigned UnpackedFieldAlign = FieldAlign;
1966   uint64_t UnpackedFieldOffset = FieldOffset;
1967   if (!Context.getTargetInfo().useBitFieldTypeAlignment() && !ZeroLengthBitfield)
1968     UnpackedFieldAlign = 1;
1969
1970   if (FieldPacked || 
1971       (!Context.getTargetInfo().useBitFieldTypeAlignment() && !ZeroLengthBitfield))
1972     FieldAlign = 1;
1973   FieldAlign = std::max(FieldAlign, D->getMaxAlignment());
1974   UnpackedFieldAlign = std::max(UnpackedFieldAlign, D->getMaxAlignment());
1975
1976   // The maximum field alignment overrides the aligned attribute.
1977   if (!MaxFieldAlignment.isZero() && FieldSize != 0) {
1978     unsigned MaxFieldAlignmentInBits = Context.toBits(MaxFieldAlignment);
1979     FieldAlign = std::min(FieldAlign, MaxFieldAlignmentInBits);
1980     UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignmentInBits);
1981   }
1982
1983   // Check if we need to add padding to give the field the correct alignment.
1984   if (FieldSize == 0 || 
1985       (MaxFieldAlignment.isZero() &&
1986        (FieldOffset & (FieldAlign-1)) + FieldSize > TypeSize))
1987     FieldOffset = llvm::RoundUpToAlignment(FieldOffset, FieldAlign);
1988
1989   if (FieldSize == 0 ||
1990       (MaxFieldAlignment.isZero() &&
1991        (UnpackedFieldOffset & (UnpackedFieldAlign-1)) + FieldSize > TypeSize))
1992     UnpackedFieldOffset = llvm::RoundUpToAlignment(UnpackedFieldOffset,
1993                                                    UnpackedFieldAlign);
1994
1995   // Padding members don't affect overall alignment, unless zero length bitfield
1996   // alignment is enabled.
1997   if (!D->getIdentifier() && !Context.getTargetInfo().useZeroLengthBitfieldAlignment())
1998     FieldAlign = UnpackedFieldAlign = 1;
1999
2000   if (!IsMsStruct)
2001     ZeroLengthBitfield = 0;
2002
2003   if (ExternalLayout)
2004     FieldOffset = updateExternalFieldOffset(D, FieldOffset);
2005
2006   // Place this field at the current location.
2007   FieldOffsets.push_back(FieldOffset);
2008
2009   if (!ExternalLayout)
2010     CheckFieldPadding(FieldOffset, UnpaddedFieldOffset, UnpackedFieldOffset,
2011                       UnpackedFieldAlign, FieldPacked, D);
2012
2013   // Update DataSize to include the last byte containing (part of) the bitfield.
2014   if (IsUnion) {
2015     // FIXME: I think FieldSize should be TypeSize here.
2016     setDataSize(std::max(getDataSizeInBits(), FieldSize));
2017   } else {
2018     uint64_t NewSizeInBits = FieldOffset + FieldSize;
2019
2020     setDataSize(llvm::RoundUpToAlignment(NewSizeInBits, 
2021                                          Context.getTargetInfo().getCharAlign()));
2022     UnfilledBitsInLastByte = getDataSizeInBits() - NewSizeInBits;
2023   }
2024
2025   // Update the size.
2026   setSize(std::max(getSizeInBits(), getDataSizeInBits()));
2027
2028   // Remember max struct/class alignment.
2029   UpdateAlignment(Context.toCharUnitsFromBits(FieldAlign), 
2030                   Context.toCharUnitsFromBits(UnpackedFieldAlign));
2031 }
2032
2033 void RecordLayoutBuilder::LayoutField(const FieldDecl *D) {  
2034   if (D->isBitField()) {
2035     LayoutBitField(D);
2036     return;
2037   }
2038
2039   uint64_t UnpaddedFieldOffset = getDataSizeInBits() - UnfilledBitsInLastByte;
2040
2041   // Reset the unfilled bits.
2042   UnfilledBitsInLastByte = 0;
2043
2044   bool FieldPacked = Packed || D->hasAttr<PackedAttr>();
2045   CharUnits FieldOffset = 
2046     IsUnion ? CharUnits::Zero() : getDataSize();
2047   CharUnits FieldSize;
2048   CharUnits FieldAlign;
2049
2050   if (D->getType()->isIncompleteArrayType()) {
2051     // This is a flexible array member; we can't directly
2052     // query getTypeInfo about these, so we figure it out here.
2053     // Flexible array members don't have any size, but they
2054     // have to be aligned appropriately for their element type.
2055     FieldSize = CharUnits::Zero();
2056     const ArrayType* ATy = Context.getAsArrayType(D->getType());
2057     FieldAlign = Context.getTypeAlignInChars(ATy->getElementType());
2058   } else if (const ReferenceType *RT = D->getType()->getAs<ReferenceType>()) {
2059     unsigned AS = RT->getPointeeType().getAddressSpace();
2060     FieldSize = 
2061       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerWidth(AS));
2062     FieldAlign = 
2063       Context.toCharUnitsFromBits(Context.getTargetInfo().getPointerAlign(AS));
2064   } else {
2065     std::pair<CharUnits, CharUnits> FieldInfo = 
2066       Context.getTypeInfoInChars(D->getType());
2067     FieldSize = FieldInfo.first;
2068     FieldAlign = FieldInfo.second;
2069
2070     if (ZeroLengthBitfield) {
2071       CharUnits ZeroLengthBitfieldBoundary = 
2072         Context.toCharUnitsFromBits(
2073           Context.getTargetInfo().getZeroLengthBitfieldBoundary());
2074       if (ZeroLengthBitfieldBoundary == CharUnits::Zero()) {
2075         // If a zero-length bitfield is inserted after a bitfield,
2076         // and the alignment of the zero-length bitfield is
2077         // greater than the member that follows it, `bar', `bar' 
2078         // will be aligned as the type of the zero-length bitfield.
2079         std::pair<CharUnits, CharUnits> FieldInfo = 
2080           Context.getTypeInfoInChars(ZeroLengthBitfield->getType());
2081         CharUnits ZeroLengthBitfieldAlignment = FieldInfo.second;        
2082         if (ZeroLengthBitfieldAlignment > FieldAlign)
2083           FieldAlign = ZeroLengthBitfieldAlignment;
2084       } else if (ZeroLengthBitfieldBoundary > FieldAlign) {
2085         // Align 'bar' based on a fixed alignment specified by the target.
2086         assert(Context.getTargetInfo().useZeroLengthBitfieldAlignment() &&
2087                "ZeroLengthBitfieldBoundary should only be used in conjunction"
2088                " with useZeroLengthBitfieldAlignment.");
2089         FieldAlign = ZeroLengthBitfieldBoundary;
2090       }
2091       ZeroLengthBitfield = 0;
2092     }
2093
2094     if (IsMsStruct) {
2095       // If MS bitfield layout is required, figure out what type is being
2096       // laid out and align the field to the width of that type.
2097       
2098       // Resolve all typedefs down to their base type and round up the field
2099       // alignment if necessary.
2100       QualType T = Context.getBaseElementType(D->getType());
2101       if (const BuiltinType *BTy = T->getAs<BuiltinType>()) {
2102         CharUnits TypeSize = Context.getTypeSizeInChars(BTy);
2103         if (TypeSize > FieldAlign)
2104           FieldAlign = TypeSize;
2105       }
2106     }
2107   }
2108
2109   // The align if the field is not packed. This is to check if the attribute
2110   // was unnecessary (-Wpacked).
2111   CharUnits UnpackedFieldAlign = FieldAlign;
2112   CharUnits UnpackedFieldOffset = FieldOffset;
2113
2114   if (FieldPacked)
2115     FieldAlign = CharUnits::One();
2116   CharUnits MaxAlignmentInChars = 
2117     Context.toCharUnitsFromBits(D->getMaxAlignment());
2118   FieldAlign = std::max(FieldAlign, MaxAlignmentInChars);
2119   UnpackedFieldAlign = std::max(UnpackedFieldAlign, MaxAlignmentInChars);
2120
2121   // The maximum field alignment overrides the aligned attribute.
2122   if (!MaxFieldAlignment.isZero()) {
2123     FieldAlign = std::min(FieldAlign, MaxFieldAlignment);
2124     UnpackedFieldAlign = std::min(UnpackedFieldAlign, MaxFieldAlignment);
2125   }
2126
2127   // Round up the current record size to the field's alignment boundary.
2128   FieldOffset = FieldOffset.RoundUpToAlignment(FieldAlign);
2129   UnpackedFieldOffset = 
2130     UnpackedFieldOffset.RoundUpToAlignment(UnpackedFieldAlign);
2131
2132   if (ExternalLayout) {
2133     FieldOffset = Context.toCharUnitsFromBits(
2134                     updateExternalFieldOffset(D, Context.toBits(FieldOffset)));
2135     
2136     if (!IsUnion && EmptySubobjects) {
2137       // Record the fact that we're placing a field at this offset.
2138       bool Allowed = EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset);
2139       (void)Allowed;
2140       assert(Allowed && "Externally-placed field cannot be placed here");      
2141     }
2142   } else {
2143     if (!IsUnion && EmptySubobjects) {
2144       // Check if we can place the field at this offset.
2145       while (!EmptySubobjects->CanPlaceFieldAtOffset(D, FieldOffset)) {
2146         // We couldn't place the field at the offset. Try again at a new offset.
2147         FieldOffset += FieldAlign;
2148       }
2149     }
2150   }
2151   
2152   // Place this field at the current location.
2153   FieldOffsets.push_back(Context.toBits(FieldOffset));
2154
2155   if (!ExternalLayout)
2156     CheckFieldPadding(Context.toBits(FieldOffset), UnpaddedFieldOffset, 
2157                       Context.toBits(UnpackedFieldOffset),
2158                       Context.toBits(UnpackedFieldAlign), FieldPacked, D);
2159
2160   // Reserve space for this field.
2161   uint64_t FieldSizeInBits = Context.toBits(FieldSize);
2162   if (IsUnion)
2163     setDataSize(std::max(getDataSizeInBits(), FieldSizeInBits));
2164   else
2165     setDataSize(FieldOffset + FieldSize);
2166
2167   // Update the size.
2168   setSize(std::max(getSizeInBits(), getDataSizeInBits()));
2169
2170   // Remember max struct/class alignment.
2171   UpdateAlignment(FieldAlign, UnpackedFieldAlign);
2172 }
2173
2174 void RecordLayoutBuilder::FinishLayout(const NamedDecl *D) {
2175   // In C++, records cannot be of size 0.
2176   if (Context.getLangOpts().CPlusPlus && getSizeInBits() == 0) {
2177     if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2178       // Compatibility with gcc requires a class (pod or non-pod)
2179       // which is not empty but of size 0; such as having fields of
2180       // array of zero-length, remains of Size 0
2181       if (RD->isEmpty())
2182         setSize(CharUnits::One());
2183     }
2184     else
2185       setSize(CharUnits::One());
2186   }
2187
2188   // Finally, round the size of the record up to the alignment of the
2189   // record itself.
2190   uint64_t UnpaddedSize = getSizeInBits() - UnfilledBitsInLastByte;
2191   uint64_t UnpackedSizeInBits =
2192   llvm::RoundUpToAlignment(getSizeInBits(),
2193                            Context.toBits(UnpackedAlignment));
2194   CharUnits UnpackedSize = Context.toCharUnitsFromBits(UnpackedSizeInBits);
2195   uint64_t RoundedSize
2196     = llvm::RoundUpToAlignment(getSizeInBits(), Context.toBits(Alignment));
2197
2198   if (ExternalLayout) {
2199     // If we're inferring alignment, and the external size is smaller than
2200     // our size after we've rounded up to alignment, conservatively set the
2201     // alignment to 1.
2202     if (InferAlignment && ExternalSize < RoundedSize) {
2203       Alignment = CharUnits::One();
2204       InferAlignment = false;
2205     }
2206     setSize(ExternalSize);
2207     return;
2208   }
2209
2210
2211   // MSVC doesn't round up to the alignment of the record with virtual bases.
2212   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2213     if (isMicrosoftCXXABI() && RD->getNumVBases())
2214       return;
2215   }
2216
2217   // Set the size to the final size.
2218   setSize(RoundedSize);
2219
2220   unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
2221   if (const RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
2222     // Warn if padding was introduced to the struct/class/union.
2223     if (getSizeInBits() > UnpaddedSize) {
2224       unsigned PadSize = getSizeInBits() - UnpaddedSize;
2225       bool InBits = true;
2226       if (PadSize % CharBitNum == 0) {
2227         PadSize = PadSize / CharBitNum;
2228         InBits = false;
2229       }
2230       Diag(RD->getLocation(), diag::warn_padded_struct_size)
2231           << Context.getTypeDeclType(RD)
2232           << PadSize
2233           << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
2234     }
2235
2236     // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
2237     // bother since there won't be alignment issues.
2238     if (Packed && UnpackedAlignment > CharUnits::One() && 
2239         getSize() == UnpackedSize)
2240       Diag(D->getLocation(), diag::warn_unnecessary_packed)
2241           << Context.getTypeDeclType(RD);
2242   }
2243 }
2244
2245 void RecordLayoutBuilder::UpdateAlignment(CharUnits NewAlignment,
2246                                           CharUnits UnpackedNewAlignment) {
2247   // The alignment is not modified when using 'mac68k' alignment or when
2248   // we have an externally-supplied layout that also provides overall alignment.
2249   if (IsMac68kAlign || (ExternalLayout && !InferAlignment))
2250     return;
2251
2252   if (NewAlignment > Alignment) {
2253     assert(llvm::isPowerOf2_32(NewAlignment.getQuantity() && 
2254            "Alignment not a power of 2"));
2255     Alignment = NewAlignment;
2256   }
2257
2258   if (UnpackedNewAlignment > UnpackedAlignment) {
2259     assert(llvm::isPowerOf2_32(UnpackedNewAlignment.getQuantity() &&
2260            "Alignment not a power of 2"));
2261     UnpackedAlignment = UnpackedNewAlignment;
2262   }
2263 }
2264
2265 uint64_t
2266 RecordLayoutBuilder::updateExternalFieldOffset(const FieldDecl *Field, 
2267                                                uint64_t ComputedOffset) {
2268   assert(ExternalFieldOffsets.find(Field) != ExternalFieldOffsets.end() &&
2269          "Field does not have an external offset");
2270   
2271   uint64_t ExternalFieldOffset = ExternalFieldOffsets[Field];
2272   
2273   if (InferAlignment && ExternalFieldOffset < ComputedOffset) {
2274     // The externally-supplied field offset is before the field offset we
2275     // computed. Assume that the structure is packed.
2276     Alignment = CharUnits::One();
2277     InferAlignment = false;
2278   }
2279   
2280   // Use the externally-supplied field offset.
2281   return ExternalFieldOffset;
2282 }
2283
2284 /// \brief Get diagnostic %select index for tag kind for
2285 /// field padding diagnostic message.
2286 /// WARNING: Indexes apply to particular diagnostics only!
2287 ///
2288 /// \returns diagnostic %select index.
2289 static unsigned getPaddingDiagFromTagKind(TagTypeKind Tag) {
2290   switch (Tag) {
2291   case TTK_Struct: return 0;
2292   case TTK_Interface: return 1;
2293   case TTK_Class: return 2;
2294   default: llvm_unreachable("Invalid tag kind for field padding diagnostic!");
2295   }
2296 }
2297
2298 void RecordLayoutBuilder::CheckFieldPadding(uint64_t Offset,
2299                                             uint64_t UnpaddedOffset,
2300                                             uint64_t UnpackedOffset,
2301                                             unsigned UnpackedAlign,
2302                                             bool isPacked,
2303                                             const FieldDecl *D) {
2304   // We let objc ivars without warning, objc interfaces generally are not used
2305   // for padding tricks.
2306   if (isa<ObjCIvarDecl>(D))
2307     return;
2308
2309   // Don't warn about structs created without a SourceLocation.  This can
2310   // be done by clients of the AST, such as codegen.
2311   if (D->getLocation().isInvalid())
2312     return;
2313   
2314   unsigned CharBitNum = Context.getTargetInfo().getCharWidth();
2315
2316   // Warn if padding was introduced to the struct/class.
2317   if (!IsUnion && Offset > UnpaddedOffset) {
2318     unsigned PadSize = Offset - UnpaddedOffset;
2319     bool InBits = true;
2320     if (PadSize % CharBitNum == 0) {
2321       PadSize = PadSize / CharBitNum;
2322       InBits = false;
2323     }
2324     if (D->getIdentifier())
2325       Diag(D->getLocation(), diag::warn_padded_struct_field)
2326           << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
2327           << Context.getTypeDeclType(D->getParent())
2328           << PadSize
2329           << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1) // plural or not
2330           << D->getIdentifier();
2331     else
2332       Diag(D->getLocation(), diag::warn_padded_struct_anon_field)
2333           << getPaddingDiagFromTagKind(D->getParent()->getTagKind())
2334           << Context.getTypeDeclType(D->getParent())
2335           << PadSize
2336           << (InBits ? 1 : 0) /*(byte|bit)*/ << (PadSize > 1); // plural or not
2337   }
2338
2339   // Warn if we packed it unnecessarily. If the alignment is 1 byte don't
2340   // bother since there won't be alignment issues.
2341   if (isPacked && UnpackedAlign > CharBitNum && Offset == UnpackedOffset)
2342     Diag(D->getLocation(), diag::warn_unnecessary_packed)
2343         << D->getIdentifier();
2344 }
2345
2346 const CXXMethodDecl *
2347 RecordLayoutBuilder::ComputeKeyFunction(const CXXRecordDecl *RD) {
2348   // If a class isn't polymorphic it doesn't have a key function.
2349   if (!RD->isPolymorphic())
2350     return 0;
2351
2352   // A class that is not externally visible doesn't have a key function. (Or
2353   // at least, there's no point to assigning a key function to such a class;
2354   // this doesn't affect the ABI.)
2355   if (RD->getLinkage() != ExternalLinkage)
2356     return 0;
2357
2358   // Template instantiations don't have key functions,see Itanium C++ ABI 5.2.6.
2359   // Same behavior as GCC.
2360   TemplateSpecializationKind TSK = RD->getTemplateSpecializationKind();
2361   if (TSK == TSK_ImplicitInstantiation ||
2362       TSK == TSK_ExplicitInstantiationDefinition)
2363     return 0;
2364
2365   for (CXXRecordDecl::method_iterator I = RD->method_begin(),
2366          E = RD->method_end(); I != E; ++I) {
2367     const CXXMethodDecl *MD = *I;
2368
2369     if (!MD->isVirtual())
2370       continue;
2371
2372     if (MD->isPure())
2373       continue;
2374
2375     // Ignore implicit member functions, they are always marked as inline, but
2376     // they don't have a body until they're defined.
2377     if (MD->isImplicit())
2378       continue;
2379
2380     if (MD->isInlineSpecified())
2381       continue;
2382
2383     if (MD->hasInlineBody())
2384       continue;
2385
2386     // Ignore inline deleted or defaulted functions.
2387     if (!MD->isUserProvided())
2388       continue;
2389
2390     // We found it.
2391     return MD;
2392   }
2393
2394   return 0;
2395 }
2396
2397 DiagnosticBuilder
2398 RecordLayoutBuilder::Diag(SourceLocation Loc, unsigned DiagID) {
2399   return Context.getDiagnostics().Report(Loc, DiagID);
2400 }
2401
2402 /// getASTRecordLayout - Get or compute information about the layout of the
2403 /// specified record (struct/union/class), which indicates its size and field
2404 /// position information.
2405 const ASTRecordLayout &
2406 ASTContext::getASTRecordLayout(const RecordDecl *D) const {
2407   // These asserts test different things.  A record has a definition
2408   // as soon as we begin to parse the definition.  That definition is
2409   // not a complete definition (which is what isDefinition() tests)
2410   // until we *finish* parsing the definition.
2411
2412   if (D->hasExternalLexicalStorage() && !D->getDefinition())
2413     getExternalSource()->CompleteType(const_cast<RecordDecl*>(D));
2414     
2415   D = D->getDefinition();
2416   assert(D && "Cannot get layout of forward declarations!");
2417   assert(D->isCompleteDefinition() && "Cannot layout type before complete!");
2418
2419   // Look up this layout, if already laid out, return what we have.
2420   // Note that we can't save a reference to the entry because this function
2421   // is recursive.
2422   const ASTRecordLayout *Entry = ASTRecordLayouts[D];
2423   if (Entry) return *Entry;
2424
2425   const ASTRecordLayout *NewEntry;
2426
2427   if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
2428     EmptySubobjectMap EmptySubobjects(*this, RD);
2429     RecordLayoutBuilder Builder(*this, &EmptySubobjects);
2430     Builder.Layout(RD);
2431
2432     // MSVC gives the vb-table pointer an alignment equal to that of
2433     // the non-virtual part of the structure.  That's an inherently
2434     // multi-pass operation.  If our first pass doesn't give us
2435     // adequate alignment, try again with the specified minimum
2436     // alignment.  This is *much* more maintainable than computing the
2437     // alignment in advance in a separately-coded pass; it's also
2438     // significantly more efficient in the common case where the
2439     // vb-table doesn't need extra padding.
2440     if (Builder.VBPtrOffset != CharUnits::fromQuantity(-1) &&
2441         (Builder.VBPtrOffset % Builder.NonVirtualAlignment) != 0) {
2442       Builder.resetWithTargetAlignment(Builder.NonVirtualAlignment);
2443       Builder.Layout(RD);
2444     }
2445
2446     // FIXME: This is not always correct. See the part about bitfields at
2447     // http://www.codesourcery.com/public/cxx-abi/abi.html#POD for more info.
2448     // FIXME: IsPODForThePurposeOfLayout should be stored in the record layout.
2449     // This does not affect the calculations of MSVC layouts
2450     bool IsPODForThePurposeOfLayout = 
2451       (!Builder.isMicrosoftCXXABI() && cast<CXXRecordDecl>(D)->isPOD());
2452
2453     // FIXME: This should be done in FinalizeLayout.
2454     CharUnits DataSize =
2455       IsPODForThePurposeOfLayout ? Builder.getSize() : Builder.getDataSize();
2456     CharUnits NonVirtualSize = 
2457       IsPODForThePurposeOfLayout ? DataSize : Builder.NonVirtualSize;
2458
2459     NewEntry =
2460       new (*this) ASTRecordLayout(*this, Builder.getSize(), 
2461                                   Builder.Alignment,
2462                                   Builder.HasOwnVFPtr,
2463                                   Builder.VBPtrOffset,
2464                                   DataSize, 
2465                                   Builder.FieldOffsets.data(),
2466                                   Builder.FieldOffsets.size(),
2467                                   NonVirtualSize,
2468                                   Builder.NonVirtualAlignment,
2469                                   EmptySubobjects.SizeOfLargestEmptySubobject,
2470                                   Builder.PrimaryBase,
2471                                   Builder.PrimaryBaseIsVirtual,
2472                                   Builder.Bases, Builder.VBases);
2473   } else {
2474     RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
2475     Builder.Layout(D);
2476
2477     NewEntry =
2478       new (*this) ASTRecordLayout(*this, Builder.getSize(), 
2479                                   Builder.Alignment,
2480                                   Builder.getSize(),
2481                                   Builder.FieldOffsets.data(),
2482                                   Builder.FieldOffsets.size());
2483   }
2484
2485   ASTRecordLayouts[D] = NewEntry;
2486
2487   if (getLangOpts().DumpRecordLayouts) {
2488     llvm::errs() << "\n*** Dumping AST Record Layout\n";
2489     DumpRecordLayout(D, llvm::errs(), getLangOpts().DumpRecordLayoutsSimple);
2490   }
2491
2492   return *NewEntry;
2493 }
2494
2495 const CXXMethodDecl *ASTContext::getKeyFunction(const CXXRecordDecl *RD) {
2496   RD = cast<CXXRecordDecl>(RD->getDefinition());
2497   assert(RD && "Cannot get key function for forward declarations!");
2498
2499   const CXXMethodDecl *&Entry = KeyFunctions[RD];
2500   if (!Entry)
2501     Entry = RecordLayoutBuilder::ComputeKeyFunction(RD);
2502
2503   return Entry;
2504 }
2505
2506 static uint64_t getFieldOffset(const ASTContext &C, const FieldDecl *FD) {
2507   const ASTRecordLayout &Layout = C.getASTRecordLayout(FD->getParent());
2508   return Layout.getFieldOffset(FD->getFieldIndex());
2509 }
2510
2511 uint64_t ASTContext::getFieldOffset(const ValueDecl *VD) const {
2512   uint64_t OffsetInBits;
2513   if (const FieldDecl *FD = dyn_cast<FieldDecl>(VD)) {
2514     OffsetInBits = ::getFieldOffset(*this, FD);
2515   } else {
2516     const IndirectFieldDecl *IFD = cast<IndirectFieldDecl>(VD);
2517
2518     OffsetInBits = 0;
2519     for (IndirectFieldDecl::chain_iterator CI = IFD->chain_begin(),
2520                                            CE = IFD->chain_end();
2521          CI != CE; ++CI)
2522       OffsetInBits += ::getFieldOffset(*this, cast<FieldDecl>(*CI));
2523   }
2524
2525   return OffsetInBits;
2526 }
2527
2528 /// getObjCLayout - Get or compute information about the layout of the
2529 /// given interface.
2530 ///
2531 /// \param Impl - If given, also include the layout of the interface's
2532 /// implementation. This may differ by including synthesized ivars.
2533 const ASTRecordLayout &
2534 ASTContext::getObjCLayout(const ObjCInterfaceDecl *D,
2535                           const ObjCImplementationDecl *Impl) const {
2536   // Retrieve the definition
2537   if (D->hasExternalLexicalStorage() && !D->getDefinition())
2538     getExternalSource()->CompleteType(const_cast<ObjCInterfaceDecl*>(D));
2539   D = D->getDefinition();
2540   assert(D && D->isThisDeclarationADefinition() && "Invalid interface decl!");
2541
2542   // Look up this layout, if already laid out, return what we have.
2543   const ObjCContainerDecl *Key =
2544     Impl ? (const ObjCContainerDecl*) Impl : (const ObjCContainerDecl*) D;
2545   if (const ASTRecordLayout *Entry = ObjCLayouts[Key])
2546     return *Entry;
2547
2548   // Add in synthesized ivar count if laying out an implementation.
2549   if (Impl) {
2550     unsigned SynthCount = CountNonClassIvars(D);
2551     // If there aren't any sythesized ivars then reuse the interface
2552     // entry. Note we can't cache this because we simply free all
2553     // entries later; however we shouldn't look up implementations
2554     // frequently.
2555     if (SynthCount == 0)
2556       return getObjCLayout(D, 0);
2557   }
2558
2559   RecordLayoutBuilder Builder(*this, /*EmptySubobjects=*/0);
2560   Builder.Layout(D);
2561
2562   const ASTRecordLayout *NewEntry =
2563     new (*this) ASTRecordLayout(*this, Builder.getSize(), 
2564                                 Builder.Alignment,
2565                                 Builder.getDataSize(),
2566                                 Builder.FieldOffsets.data(),
2567                                 Builder.FieldOffsets.size());
2568
2569   ObjCLayouts[Key] = NewEntry;
2570
2571   return *NewEntry;
2572 }
2573
2574 static void PrintOffset(raw_ostream &OS,
2575                         CharUnits Offset, unsigned IndentLevel) {
2576   OS << llvm::format("%4" PRId64 " | ", (int64_t)Offset.getQuantity());
2577   OS.indent(IndentLevel * 2);
2578 }
2579
2580 static void DumpCXXRecordLayout(raw_ostream &OS,
2581                                 const CXXRecordDecl *RD, const ASTContext &C,
2582                                 CharUnits Offset,
2583                                 unsigned IndentLevel,
2584                                 const char* Description,
2585                                 bool IncludeVirtualBases) {
2586   const ASTRecordLayout &Layout = C.getASTRecordLayout(RD);
2587
2588   PrintOffset(OS, Offset, IndentLevel);
2589   OS << C.getTypeDeclType(const_cast<CXXRecordDecl *>(RD)).getAsString();
2590   if (Description)
2591     OS << ' ' << Description;
2592   if (RD->isEmpty())
2593     OS << " (empty)";
2594   OS << '\n';
2595
2596   IndentLevel++;
2597
2598   const CXXRecordDecl *PrimaryBase = Layout.getPrimaryBase();
2599   bool HasVfptr = Layout.hasOwnVFPtr();
2600   bool HasVbptr = Layout.getVBPtrOffset() != CharUnits::fromQuantity(-1);
2601
2602   // Vtable pointer.
2603   if (RD->isDynamicClass() && !PrimaryBase &&
2604       C.getTargetInfo().getCXXABI() != CXXABI_Microsoft) {
2605     PrintOffset(OS, Offset, IndentLevel);
2606     OS << '(' << *RD << " vtable pointer)\n";
2607   }
2608   
2609   // Dump (non-virtual) bases
2610   for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(),
2611          E = RD->bases_end(); I != E; ++I) {
2612     assert(!I->getType()->isDependentType() &&
2613            "Cannot layout class with dependent bases.");
2614     if (I->isVirtual())
2615       continue;
2616
2617     const CXXRecordDecl *Base =
2618       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
2619
2620     CharUnits BaseOffset = Offset + Layout.getBaseClassOffset(Base);
2621
2622     DumpCXXRecordLayout(OS, Base, C, BaseOffset, IndentLevel,
2623                         Base == PrimaryBase ? "(primary base)" : "(base)",
2624                         /*IncludeVirtualBases=*/false);
2625   }
2626
2627   // vfptr and vbptr (for Microsoft C++ ABI)
2628   if (HasVfptr) {
2629     PrintOffset(OS, Offset, IndentLevel);
2630     OS << '(' << *RD << " vftable pointer)\n";
2631   }
2632   if (HasVbptr) {
2633     PrintOffset(OS, Offset + Layout.getVBPtrOffset(), IndentLevel);
2634     OS << '(' << *RD << " vbtable pointer)\n";
2635   }
2636
2637   // Dump fields.
2638   uint64_t FieldNo = 0;
2639   for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2640          E = RD->field_end(); I != E; ++I, ++FieldNo) {
2641     const FieldDecl &Field = **I;
2642     CharUnits FieldOffset = Offset + 
2643       C.toCharUnitsFromBits(Layout.getFieldOffset(FieldNo));
2644
2645     if (const RecordType *RT = Field.getType()->getAs<RecordType>()) {
2646       if (const CXXRecordDecl *D = dyn_cast<CXXRecordDecl>(RT->getDecl())) {
2647         DumpCXXRecordLayout(OS, D, C, FieldOffset, IndentLevel,
2648                             Field.getName().data(),
2649                             /*IncludeVirtualBases=*/true);
2650         continue;
2651       }
2652     }
2653
2654     PrintOffset(OS, FieldOffset, IndentLevel);
2655     OS << Field.getType().getAsString() << ' ' << Field << '\n';
2656   }
2657
2658   if (!IncludeVirtualBases)
2659     return;
2660
2661   // Dump virtual bases.
2662   const ASTRecordLayout::VBaseOffsetsMapTy &vtordisps = 
2663     Layout.getVBaseOffsetsMap();
2664   for (CXXRecordDecl::base_class_const_iterator I = RD->vbases_begin(),
2665          E = RD->vbases_end(); I != E; ++I) {
2666     assert(I->isVirtual() && "Found non-virtual class!");
2667     const CXXRecordDecl *VBase =
2668       cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
2669
2670     CharUnits VBaseOffset = Offset + Layout.getVBaseClassOffset(VBase);
2671
2672     if (vtordisps.find(VBase)->second.hasVtorDisp()) {
2673       PrintOffset(OS, VBaseOffset - CharUnits::fromQuantity(4), IndentLevel);
2674       OS << "(vtordisp for vbase " << *VBase << ")\n";
2675     }
2676
2677     DumpCXXRecordLayout(OS, VBase, C, VBaseOffset, IndentLevel,
2678                         VBase == PrimaryBase ?
2679                         "(primary virtual base)" : "(virtual base)",
2680                         /*IncludeVirtualBases=*/false);
2681   }
2682
2683   OS << "  sizeof=" << Layout.getSize().getQuantity();
2684   OS << ", dsize=" << Layout.getDataSize().getQuantity();
2685   OS << ", align=" << Layout.getAlignment().getQuantity() << '\n';
2686   OS << "  nvsize=" << Layout.getNonVirtualSize().getQuantity();
2687   OS << ", nvalign=" << Layout.getNonVirtualAlign().getQuantity() << '\n';
2688   OS << '\n';
2689 }
2690
2691 void ASTContext::DumpRecordLayout(const RecordDecl *RD,
2692                                   raw_ostream &OS,
2693                                   bool Simple) const {
2694   const ASTRecordLayout &Info = getASTRecordLayout(RD);
2695
2696   if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
2697     if (!Simple)
2698       return DumpCXXRecordLayout(OS, CXXRD, *this, CharUnits(), 0, 0,
2699                                  /*IncludeVirtualBases=*/true);
2700
2701   OS << "Type: " << getTypeDeclType(RD).getAsString() << "\n";
2702   if (!Simple) {
2703     OS << "Record: ";
2704     RD->dump();
2705   }
2706   OS << "\nLayout: ";
2707   OS << "<ASTRecordLayout\n";
2708   OS << "  Size:" << toBits(Info.getSize()) << "\n";
2709   OS << "  DataSize:" << toBits(Info.getDataSize()) << "\n";
2710   OS << "  Alignment:" << toBits(Info.getAlignment()) << "\n";
2711   OS << "  FieldOffsets: [";
2712   for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) {
2713     if (i) OS << ", ";
2714     OS << Info.getFieldOffset(i);
2715   }
2716   OS << "]>\n";
2717 }