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