Home | History | Annotate | Download | only in Serialization
      1 //===--- ASTReaderDecl.cpp - Decl Deserialization ---------------*- C++ -*-===//
      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 // This file implements the ASTReader::ReadDeclRecord method, which is the
     11 // entrypoint for loading a decl.
     12 //
     13 //===----------------------------------------------------------------------===//
     14 
     15 #include "ASTCommon.h"
     16 #include "clang/Serialization/ASTReader.h"
     17 #include "clang/Sema/SemaDiagnostic.h"
     18 #include "clang/AST/ASTConsumer.h"
     19 #include "clang/AST/ASTContext.h"
     20 #include "clang/AST/DeclVisitor.h"
     21 #include "clang/AST/DeclGroup.h"
     22 #include "clang/AST/DeclCXX.h"
     23 #include "clang/AST/DeclTemplate.h"
     24 #include "clang/AST/Expr.h"
     25 using namespace clang;
     26 using namespace clang::serialization;
     27 
     28 //===----------------------------------------------------------------------===//
     29 // Declaration deserialization
     30 //===----------------------------------------------------------------------===//
     31 
     32 namespace clang {
     33   class ASTDeclReader : public DeclVisitor<ASTDeclReader, void> {
     34     ASTReader &Reader;
     35     Module &F;
     36     llvm::BitstreamCursor &Cursor;
     37     const DeclID ThisDeclID;
     38     typedef ASTReader::RecordData RecordData;
     39     const RecordData &Record;
     40     unsigned &Idx;
     41     TypeID TypeIDForTypeDecl;
     42 
     43     DeclID DeclContextIDForTemplateParmDecl;
     44     DeclID LexicalDeclContextIDForTemplateParmDecl;
     45 
     46     uint64_t GetCurrentCursorOffset();
     47 
     48     SourceLocation ReadSourceLocation(const RecordData &R, unsigned &I) {
     49       return Reader.ReadSourceLocation(F, R, I);
     50     }
     51 
     52     SourceRange ReadSourceRange(const RecordData &R, unsigned &I) {
     53       return Reader.ReadSourceRange(F, R, I);
     54     }
     55 
     56     TypeSourceInfo *GetTypeSourceInfo(const RecordData &R, unsigned &I) {
     57       return Reader.GetTypeSourceInfo(F, R, I);
     58     }
     59 
     60     serialization::DeclID ReadDeclID(const RecordData &R, unsigned &I) {
     61       return Reader.ReadDeclID(F, R, I);
     62     }
     63 
     64     Decl *ReadDecl(const RecordData &R, unsigned &I) {
     65       return Reader.ReadDecl(F, R, I);
     66     }
     67 
     68     template<typename T>
     69     T *ReadDeclAs(const RecordData &R, unsigned &I) {
     70       return Reader.ReadDeclAs<T>(F, R, I);
     71     }
     72 
     73     void ReadQualifierInfo(QualifierInfo &Info,
     74                            const RecordData &R, unsigned &I) {
     75       Reader.ReadQualifierInfo(F, Info, R, I);
     76     }
     77 
     78     void ReadDeclarationNameLoc(DeclarationNameLoc &DNLoc, DeclarationName Name,
     79                                 const RecordData &R, unsigned &I) {
     80       Reader.ReadDeclarationNameLoc(F, DNLoc, Name, R, I);
     81     }
     82 
     83     void ReadDeclarationNameInfo(DeclarationNameInfo &NameInfo,
     84                                 const RecordData &R, unsigned &I) {
     85       Reader.ReadDeclarationNameInfo(F, NameInfo, R, I);
     86     }
     87 
     88     void ReadCXXDefinitionData(struct CXXRecordDecl::DefinitionData &Data,
     89                                const RecordData &R, unsigned &I);
     90 
     91     void InitializeCXXDefinitionData(CXXRecordDecl *D,
     92                                      CXXRecordDecl *DefinitionDecl,
     93                                      const RecordData &Record, unsigned &Idx);
     94   public:
     95     ASTDeclReader(ASTReader &Reader, Module &F,
     96                   llvm::BitstreamCursor &Cursor, DeclID thisDeclID,
     97                   const RecordData &Record, unsigned &Idx)
     98       : Reader(Reader), F(F), Cursor(Cursor), ThisDeclID(thisDeclID),
     99         Record(Record), Idx(Idx), TypeIDForTypeDecl(0) { }
    100 
    101     static void attachPreviousDecl(Decl *D, Decl *previous);
    102 
    103     void Visit(Decl *D);
    104 
    105     void UpdateDecl(Decl *D, Module &Module,
    106                     const RecordData &Record);
    107 
    108     static void setNextObjCCategory(ObjCCategoryDecl *Cat,
    109                                     ObjCCategoryDecl *Next) {
    110       Cat->NextClassCategory = Next;
    111     }
    112 
    113     void VisitDecl(Decl *D);
    114     void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
    115     void VisitNamedDecl(NamedDecl *ND);
    116     void VisitLabelDecl(LabelDecl *LD);
    117     void VisitNamespaceDecl(NamespaceDecl *D);
    118     void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
    119     void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
    120     void VisitTypeDecl(TypeDecl *TD);
    121     void VisitTypedefDecl(TypedefDecl *TD);
    122     void VisitTypeAliasDecl(TypeAliasDecl *TD);
    123     void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
    124     void VisitTagDecl(TagDecl *TD);
    125     void VisitEnumDecl(EnumDecl *ED);
    126     void VisitRecordDecl(RecordDecl *RD);
    127     void VisitCXXRecordDecl(CXXRecordDecl *D);
    128     void VisitClassTemplateSpecializationDecl(
    129                                             ClassTemplateSpecializationDecl *D);
    130     void VisitClassTemplatePartialSpecializationDecl(
    131                                      ClassTemplatePartialSpecializationDecl *D);
    132     void VisitClassScopeFunctionSpecializationDecl(
    133                                        ClassScopeFunctionSpecializationDecl *D);
    134     void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
    135     void VisitValueDecl(ValueDecl *VD);
    136     void VisitEnumConstantDecl(EnumConstantDecl *ECD);
    137     void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
    138     void VisitDeclaratorDecl(DeclaratorDecl *DD);
    139     void VisitFunctionDecl(FunctionDecl *FD);
    140     void VisitCXXMethodDecl(CXXMethodDecl *D);
    141     void VisitCXXConstructorDecl(CXXConstructorDecl *D);
    142     void VisitCXXDestructorDecl(CXXDestructorDecl *D);
    143     void VisitCXXConversionDecl(CXXConversionDecl *D);
    144     void VisitFieldDecl(FieldDecl *FD);
    145     void VisitIndirectFieldDecl(IndirectFieldDecl *FD);
    146     void VisitVarDecl(VarDecl *VD);
    147     void VisitImplicitParamDecl(ImplicitParamDecl *PD);
    148     void VisitParmVarDecl(ParmVarDecl *PD);
    149     void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
    150     void VisitTemplateDecl(TemplateDecl *D);
    151     void VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);
    152     void VisitClassTemplateDecl(ClassTemplateDecl *D);
    153     void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
    154     void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
    155     void VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
    156     void VisitUsingDecl(UsingDecl *D);
    157     void VisitUsingShadowDecl(UsingShadowDecl *D);
    158     void VisitLinkageSpecDecl(LinkageSpecDecl *D);
    159     void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);
    160     void VisitAccessSpecDecl(AccessSpecDecl *D);
    161     void VisitFriendDecl(FriendDecl *D);
    162     void VisitFriendTemplateDecl(FriendTemplateDecl *D);
    163     void VisitStaticAssertDecl(StaticAssertDecl *D);
    164     void VisitBlockDecl(BlockDecl *BD);
    165 
    166     std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
    167     template <typename T> void VisitRedeclarable(Redeclarable<T> *D);
    168 
    169     // FIXME: Reorder according to DeclNodes.td?
    170     void VisitObjCMethodDecl(ObjCMethodDecl *D);
    171     void VisitObjCContainerDecl(ObjCContainerDecl *D);
    172     void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
    173     void VisitObjCIvarDecl(ObjCIvarDecl *D);
    174     void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
    175     void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
    176     void VisitObjCClassDecl(ObjCClassDecl *D);
    177     void VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *D);
    178     void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
    179     void VisitObjCImplDecl(ObjCImplDecl *D);
    180     void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
    181     void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
    182     void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
    183     void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
    184     void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
    185   };
    186 }
    187 
    188 uint64_t ASTDeclReader::GetCurrentCursorOffset() {
    189   return F.DeclsCursor.GetCurrentBitNo() + F.GlobalBitOffset;
    190 }
    191 
    192 void ASTDeclReader::Visit(Decl *D) {
    193   DeclVisitor<ASTDeclReader, void>::Visit(D);
    194 
    195   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
    196     if (DD->DeclInfo) {
    197       DeclaratorDecl::ExtInfo *Info =
    198           DD->DeclInfo.get<DeclaratorDecl::ExtInfo *>();
    199       Info->TInfo =
    200           GetTypeSourceInfo(Record, Idx);
    201     }
    202     else {
    203       DD->DeclInfo = GetTypeSourceInfo(Record, Idx);
    204     }
    205   }
    206 
    207   if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
    208     // if we have a fully initialized TypeDecl, we can safely read its type now.
    209     TD->setTypeForDecl(Reader.GetType(TypeIDForTypeDecl).getTypePtrOrNull());
    210   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
    211     // FunctionDecl's body was written last after all other Stmts/Exprs.
    212     if (Record[Idx++])
    213       FD->setLazyBody(GetCurrentCursorOffset());
    214   } else if (D->isTemplateParameter()) {
    215     // If we have a fully initialized template parameter, we can now
    216     // set its DeclContext.
    217     D->setDeclContext(
    218           cast_or_null<DeclContext>(
    219                             Reader.GetDecl(DeclContextIDForTemplateParmDecl)));
    220     D->setLexicalDeclContext(
    221           cast_or_null<DeclContext>(
    222                       Reader.GetDecl(LexicalDeclContextIDForTemplateParmDecl)));
    223   }
    224 }
    225 
    226 void ASTDeclReader::VisitDecl(Decl *D) {
    227   if (D->isTemplateParameter()) {
    228     // We don't want to deserialize the DeclContext of a template
    229     // parameter immediately, because the template parameter might be
    230     // used in the formulation of its DeclContext. Use the translation
    231     // unit DeclContext as a placeholder.
    232     DeclContextIDForTemplateParmDecl = ReadDeclID(Record, Idx);
    233     LexicalDeclContextIDForTemplateParmDecl = ReadDeclID(Record, Idx);
    234     D->setDeclContext(Reader.getContext().getTranslationUnitDecl());
    235   } else {
    236     D->setDeclContext(ReadDeclAs<DeclContext>(Record, Idx));
    237     D->setLexicalDeclContext(ReadDeclAs<DeclContext>(Record, Idx));
    238   }
    239   D->setLocation(ReadSourceLocation(Record, Idx));
    240   D->setInvalidDecl(Record[Idx++]);
    241   if (Record[Idx++]) { // hasAttrs
    242     AttrVec Attrs;
    243     Reader.ReadAttributes(F, Attrs, Record, Idx);
    244     D->setAttrs(Attrs);
    245   }
    246   D->setImplicit(Record[Idx++]);
    247   D->setUsed(Record[Idx++]);
    248   D->setReferenced(Record[Idx++]);
    249   D->setAccess((AccessSpecifier)Record[Idx++]);
    250   D->FromASTFile = true;
    251   D->ModulePrivate = Record[Idx++];
    252 }
    253 
    254 void ASTDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
    255   llvm_unreachable("Translation units are not serialized");
    256 }
    257 
    258 void ASTDeclReader::VisitNamedDecl(NamedDecl *ND) {
    259   VisitDecl(ND);
    260   ND->setDeclName(Reader.ReadDeclarationName(F, Record, Idx));
    261 }
    262 
    263 void ASTDeclReader::VisitTypeDecl(TypeDecl *TD) {
    264   VisitNamedDecl(TD);
    265   TD->setLocStart(ReadSourceLocation(Record, Idx));
    266   // Delay type reading until after we have fully initialized the decl.
    267   TypeIDForTypeDecl = Reader.getGlobalTypeID(F, Record[Idx++]);
    268 }
    269 
    270 void ASTDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
    271   VisitTypeDecl(TD);
    272   TD->setTypeSourceInfo(GetTypeSourceInfo(Record, Idx));
    273 }
    274 
    275 void ASTDeclReader::VisitTypeAliasDecl(TypeAliasDecl *TD) {
    276   VisitTypeDecl(TD);
    277   TD->setTypeSourceInfo(GetTypeSourceInfo(Record, Idx));
    278 }
    279 
    280 void ASTDeclReader::VisitTagDecl(TagDecl *TD) {
    281   VisitTypeDecl(TD);
    282   VisitRedeclarable(TD);
    283   TD->IdentifierNamespace = Record[Idx++];
    284   TD->setTagKind((TagDecl::TagKind)Record[Idx++]);
    285   TD->setCompleteDefinition(Record[Idx++]);
    286   TD->setEmbeddedInDeclarator(Record[Idx++]);
    287   TD->setFreeStanding(Record[Idx++]);
    288   TD->setRBraceLoc(ReadSourceLocation(Record, Idx));
    289   if (Record[Idx++]) { // hasExtInfo
    290     TagDecl::ExtInfo *Info = new (Reader.getContext()) TagDecl::ExtInfo();
    291     ReadQualifierInfo(*Info, Record, Idx);
    292     TD->TypedefNameDeclOrQualifier = Info;
    293   } else
    294     TD->setTypedefNameForAnonDecl(ReadDeclAs<TypedefNameDecl>(Record, Idx));
    295 }
    296 
    297 void ASTDeclReader::VisitEnumDecl(EnumDecl *ED) {
    298   VisitTagDecl(ED);
    299   if (TypeSourceInfo *TI = Reader.GetTypeSourceInfo(F, Record, Idx))
    300     ED->setIntegerTypeSourceInfo(TI);
    301   else
    302     ED->setIntegerType(Reader.readType(F, Record, Idx));
    303   ED->setPromotionType(Reader.readType(F, Record, Idx));
    304   ED->setNumPositiveBits(Record[Idx++]);
    305   ED->setNumNegativeBits(Record[Idx++]);
    306   ED->IsScoped = Record[Idx++];
    307   ED->IsScopedUsingClassTag = Record[Idx++];
    308   ED->IsFixed = Record[Idx++];
    309   ED->setInstantiationOfMemberEnum(ReadDeclAs<EnumDecl>(Record, Idx));
    310 }
    311 
    312 void ASTDeclReader::VisitRecordDecl(RecordDecl *RD) {
    313   VisitTagDecl(RD);
    314   RD->setHasFlexibleArrayMember(Record[Idx++]);
    315   RD->setAnonymousStructOrUnion(Record[Idx++]);
    316   RD->setHasObjectMember(Record[Idx++]);
    317 }
    318 
    319 void ASTDeclReader::VisitValueDecl(ValueDecl *VD) {
    320   VisitNamedDecl(VD);
    321   VD->setType(Reader.readType(F, Record, Idx));
    322 }
    323 
    324 void ASTDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
    325   VisitValueDecl(ECD);
    326   if (Record[Idx++])
    327     ECD->setInitExpr(Reader.ReadExpr(F));
    328   ECD->setInitVal(Reader.ReadAPSInt(Record, Idx));
    329 }
    330 
    331 void ASTDeclReader::VisitDeclaratorDecl(DeclaratorDecl *DD) {
    332   VisitValueDecl(DD);
    333   DD->setInnerLocStart(ReadSourceLocation(Record, Idx));
    334   if (Record[Idx++]) { // hasExtInfo
    335     DeclaratorDecl::ExtInfo *Info
    336         = new (Reader.getContext()) DeclaratorDecl::ExtInfo();
    337     ReadQualifierInfo(*Info, Record, Idx);
    338     DD->DeclInfo = Info;
    339   }
    340 }
    341 
    342 void ASTDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
    343   VisitDeclaratorDecl(FD);
    344   VisitRedeclarable(FD);
    345 
    346   ReadDeclarationNameLoc(FD->DNLoc, FD->getDeclName(), Record, Idx);
    347   FD->IdentifierNamespace = Record[Idx++];
    348   switch ((FunctionDecl::TemplatedKind)Record[Idx++]) {
    349   default: llvm_unreachable("Unhandled TemplatedKind!");
    350   case FunctionDecl::TK_NonTemplate:
    351     break;
    352   case FunctionDecl::TK_FunctionTemplate:
    353     FD->setDescribedFunctionTemplate(ReadDeclAs<FunctionTemplateDecl>(Record,
    354                                                                       Idx));
    355     break;
    356   case FunctionDecl::TK_MemberSpecialization: {
    357     FunctionDecl *InstFD = ReadDeclAs<FunctionDecl>(Record, Idx);
    358     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
    359     SourceLocation POI = ReadSourceLocation(Record, Idx);
    360     FD->setInstantiationOfMemberFunction(Reader.getContext(), InstFD, TSK);
    361     FD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
    362     break;
    363   }
    364   case FunctionDecl::TK_FunctionTemplateSpecialization: {
    365     FunctionTemplateDecl *Template = ReadDeclAs<FunctionTemplateDecl>(Record,
    366                                                                       Idx);
    367     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
    368 
    369     // Template arguments.
    370     SmallVector<TemplateArgument, 8> TemplArgs;
    371     Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
    372 
    373     // Template args as written.
    374     SmallVector<TemplateArgumentLoc, 8> TemplArgLocs;
    375     SourceLocation LAngleLoc, RAngleLoc;
    376     bool HasTemplateArgumentsAsWritten = Record[Idx++];
    377     if (HasTemplateArgumentsAsWritten) {
    378       unsigned NumTemplateArgLocs = Record[Idx++];
    379       TemplArgLocs.reserve(NumTemplateArgLocs);
    380       for (unsigned i=0; i != NumTemplateArgLocs; ++i)
    381         TemplArgLocs.push_back(
    382             Reader.ReadTemplateArgumentLoc(F, Record, Idx));
    383 
    384       LAngleLoc = ReadSourceLocation(Record, Idx);
    385       RAngleLoc = ReadSourceLocation(Record, Idx);
    386     }
    387 
    388     SourceLocation POI = ReadSourceLocation(Record, Idx);
    389 
    390     ASTContext &C = Reader.getContext();
    391     TemplateArgumentList *TemplArgList
    392       = TemplateArgumentList::CreateCopy(C, TemplArgs.data(), TemplArgs.size());
    393     TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
    394     for (unsigned i=0, e = TemplArgLocs.size(); i != e; ++i)
    395       TemplArgsInfo.addArgument(TemplArgLocs[i]);
    396     FunctionTemplateSpecializationInfo *FTInfo
    397         = FunctionTemplateSpecializationInfo::Create(C, FD, Template, TSK,
    398                                                      TemplArgList,
    399                              HasTemplateArgumentsAsWritten ? &TemplArgsInfo : 0,
    400                                                      POI);
    401     FD->TemplateOrSpecialization = FTInfo;
    402 
    403     if (FD->isCanonicalDecl()) { // if canonical add to template's set.
    404       // The template that contains the specializations set. It's not safe to
    405       // use getCanonicalDecl on Template since it may still be initializing.
    406       FunctionTemplateDecl *CanonTemplate
    407         = ReadDeclAs<FunctionTemplateDecl>(Record, Idx);
    408       // Get the InsertPos by FindNodeOrInsertPos() instead of calling
    409       // InsertNode(FTInfo) directly to avoid the getASTContext() call in
    410       // FunctionTemplateSpecializationInfo's Profile().
    411       // We avoid getASTContext because a decl in the parent hierarchy may
    412       // be initializing.
    413       llvm::FoldingSetNodeID ID;
    414       FunctionTemplateSpecializationInfo::Profile(ID, TemplArgs.data(),
    415                                                   TemplArgs.size(), C);
    416       void *InsertPos = 0;
    417       CanonTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
    418       assert(InsertPos && "Another specialization already inserted!");
    419       CanonTemplate->getSpecializations().InsertNode(FTInfo, InsertPos);
    420     }
    421     break;
    422   }
    423   case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
    424     // Templates.
    425     UnresolvedSet<8> TemplDecls;
    426     unsigned NumTemplates = Record[Idx++];
    427     while (NumTemplates--)
    428       TemplDecls.addDecl(ReadDeclAs<NamedDecl>(Record, Idx));
    429 
    430     // Templates args.
    431     TemplateArgumentListInfo TemplArgs;
    432     unsigned NumArgs = Record[Idx++];
    433     while (NumArgs--)
    434       TemplArgs.addArgument(Reader.ReadTemplateArgumentLoc(F, Record, Idx));
    435     TemplArgs.setLAngleLoc(ReadSourceLocation(Record, Idx));
    436     TemplArgs.setRAngleLoc(ReadSourceLocation(Record, Idx));
    437 
    438     FD->setDependentTemplateSpecialization(Reader.getContext(),
    439                                            TemplDecls, TemplArgs);
    440     break;
    441   }
    442   }
    443 
    444   // FunctionDecl's body is handled last at ASTDeclReader::Visit,
    445   // after everything else is read.
    446 
    447   FD->SClass = (StorageClass)Record[Idx++];
    448   FD->SClassAsWritten = (StorageClass)Record[Idx++];
    449   FD->IsInline = Record[Idx++];
    450   FD->IsInlineSpecified = Record[Idx++];
    451   FD->IsVirtualAsWritten = Record[Idx++];
    452   FD->IsPure = Record[Idx++];
    453   FD->HasInheritedPrototype = Record[Idx++];
    454   FD->HasWrittenPrototype = Record[Idx++];
    455   FD->IsDeleted = Record[Idx++];
    456   FD->IsTrivial = Record[Idx++];
    457   FD->IsDefaulted = Record[Idx++];
    458   FD->IsExplicitlyDefaulted = Record[Idx++];
    459   FD->HasImplicitReturnZero = Record[Idx++];
    460   FD->IsConstexpr = Record[Idx++];
    461   FD->EndRangeLoc = ReadSourceLocation(Record, Idx);
    462 
    463   // Read in the parameters.
    464   unsigned NumParams = Record[Idx++];
    465   SmallVector<ParmVarDecl *, 16> Params;
    466   Params.reserve(NumParams);
    467   for (unsigned I = 0; I != NumParams; ++I)
    468     Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
    469   FD->setParams(Reader.getContext(), Params);
    470 }
    471 
    472 void ASTDeclReader::VisitObjCMethodDecl(ObjCMethodDecl *MD) {
    473   VisitNamedDecl(MD);
    474   if (Record[Idx++]) {
    475     // In practice, this won't be executed (since method definitions
    476     // don't occur in header files).
    477     MD->setBody(Reader.ReadStmt(F));
    478     MD->setSelfDecl(ReadDeclAs<ImplicitParamDecl>(Record, Idx));
    479     MD->setCmdDecl(ReadDeclAs<ImplicitParamDecl>(Record, Idx));
    480   }
    481   MD->setInstanceMethod(Record[Idx++]);
    482   MD->setVariadic(Record[Idx++]);
    483   MD->setSynthesized(Record[Idx++]);
    484   MD->setDefined(Record[Idx++]);
    485 
    486   MD->IsRedeclaration = Record[Idx++];
    487   MD->HasRedeclaration = Record[Idx++];
    488   if (MD->HasRedeclaration)
    489     Reader.getContext().setObjCMethodRedeclaration(MD,
    490                                        ReadDeclAs<ObjCMethodDecl>(Record, Idx));
    491 
    492   MD->setDeclImplementation((ObjCMethodDecl::ImplementationControl)Record[Idx++]);
    493   MD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record[Idx++]);
    494   MD->SetRelatedResultType(Record[Idx++]);
    495   MD->setResultType(Reader.readType(F, Record, Idx));
    496   MD->setResultTypeSourceInfo(GetTypeSourceInfo(Record, Idx));
    497   MD->setEndLoc(ReadSourceLocation(Record, Idx));
    498   unsigned NumParams = Record[Idx++];
    499   SmallVector<ParmVarDecl *, 16> Params;
    500   Params.reserve(NumParams);
    501   for (unsigned I = 0; I != NumParams; ++I)
    502     Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
    503 
    504   MD->SelLocsKind = Record[Idx++];
    505   unsigned NumStoredSelLocs = Record[Idx++];
    506   SmallVector<SourceLocation, 16> SelLocs;
    507   SelLocs.reserve(NumStoredSelLocs);
    508   for (unsigned i = 0; i != NumStoredSelLocs; ++i)
    509     SelLocs.push_back(ReadSourceLocation(Record, Idx));
    510 
    511   MD->setParamsAndSelLocs(Reader.getContext(), Params, SelLocs);
    512 }
    513 
    514 void ASTDeclReader::VisitObjCContainerDecl(ObjCContainerDecl *CD) {
    515   VisitNamedDecl(CD);
    516   CD->setAtStartLoc(ReadSourceLocation(Record, Idx));
    517   CD->setAtEndRange(ReadSourceRange(Record, Idx));
    518 }
    519 
    520 void ASTDeclReader::VisitObjCInterfaceDecl(ObjCInterfaceDecl *ID) {
    521   VisitObjCContainerDecl(ID);
    522   ID->setTypeForDecl(Reader.readType(F, Record, Idx).getTypePtrOrNull());
    523   ID->setSuperClass(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
    524 
    525   // Read the directly referenced protocols and their SourceLocations.
    526   unsigned NumProtocols = Record[Idx++];
    527   SmallVector<ObjCProtocolDecl *, 16> Protocols;
    528   Protocols.reserve(NumProtocols);
    529   for (unsigned I = 0; I != NumProtocols; ++I)
    530     Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
    531   SmallVector<SourceLocation, 16> ProtoLocs;
    532   ProtoLocs.reserve(NumProtocols);
    533   for (unsigned I = 0; I != NumProtocols; ++I)
    534     ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
    535   ID->setProtocolList(Protocols.data(), NumProtocols, ProtoLocs.data(),
    536                       Reader.getContext());
    537 
    538   // Read the transitive closure of protocols referenced by this class.
    539   NumProtocols = Record[Idx++];
    540   Protocols.clear();
    541   Protocols.reserve(NumProtocols);
    542   for (unsigned I = 0; I != NumProtocols; ++I)
    543     Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
    544   ID->AllReferencedProtocols.set(Protocols.data(), NumProtocols,
    545                                  Reader.getContext());
    546 
    547   // Read the ivars.
    548   unsigned NumIvars = Record[Idx++];
    549   SmallVector<ObjCIvarDecl *, 16> IVars;
    550   IVars.reserve(NumIvars);
    551   for (unsigned I = 0; I != NumIvars; ++I)
    552     IVars.push_back(ReadDeclAs<ObjCIvarDecl>(Record, Idx));
    553   ID->setCategoryList(ReadDeclAs<ObjCCategoryDecl>(Record, Idx));
    554 
    555   // We will rebuild this list lazily.
    556   ID->setIvarList(0);
    557   ID->InitiallyForwardDecl = Record[Idx++];
    558   ID->setForwardDecl(Record[Idx++]);
    559   ID->setImplicitInterfaceDecl(Record[Idx++]);
    560   ID->setSuperClassLoc(ReadSourceLocation(Record, Idx));
    561   ID->setLocEnd(ReadSourceLocation(Record, Idx));
    562 }
    563 
    564 void ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) {
    565   VisitFieldDecl(IVD);
    566   IVD->setAccessControl((ObjCIvarDecl::AccessControl)Record[Idx++]);
    567   // This field will be built lazily.
    568   IVD->setNextIvar(0);
    569   bool synth = Record[Idx++];
    570   IVD->setSynthesize(synth);
    571 }
    572 
    573 void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {
    574   VisitObjCContainerDecl(PD);
    575   PD->InitiallyForwardDecl = Record[Idx++];
    576   PD->setForwardDecl(Record[Idx++]);
    577   PD->setLocEnd(ReadSourceLocation(Record, Idx));
    578   unsigned NumProtoRefs = Record[Idx++];
    579   SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
    580   ProtoRefs.reserve(NumProtoRefs);
    581   for (unsigned I = 0; I != NumProtoRefs; ++I)
    582     ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
    583   SmallVector<SourceLocation, 16> ProtoLocs;
    584   ProtoLocs.reserve(NumProtoRefs);
    585   for (unsigned I = 0; I != NumProtoRefs; ++I)
    586     ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
    587   PD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
    588                       Reader.getContext());
    589 }
    590 
    591 void ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {
    592   VisitFieldDecl(FD);
    593 }
    594 
    595 void ASTDeclReader::VisitObjCClassDecl(ObjCClassDecl *CD) {
    596   VisitDecl(CD);
    597   ObjCInterfaceDecl *ClassRef = ReadDeclAs<ObjCInterfaceDecl>(Record, Idx);
    598   SourceLocation SLoc = ReadSourceLocation(Record, Idx);
    599   CD->setClass(Reader.getContext(), ClassRef, SLoc);
    600 }
    601 
    602 void ASTDeclReader::VisitObjCForwardProtocolDecl(ObjCForwardProtocolDecl *FPD) {
    603   VisitDecl(FPD);
    604   unsigned NumProtoRefs = Record[Idx++];
    605   SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
    606   ProtoRefs.reserve(NumProtoRefs);
    607   for (unsigned I = 0; I != NumProtoRefs; ++I)
    608     ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
    609   SmallVector<SourceLocation, 16> ProtoLocs;
    610   ProtoLocs.reserve(NumProtoRefs);
    611   for (unsigned I = 0; I != NumProtoRefs; ++I)
    612     ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
    613   FPD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
    614                        Reader.getContext());
    615 }
    616 
    617 void ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {
    618   VisitObjCContainerDecl(CD);
    619   CD->ClassInterface = ReadDeclAs<ObjCInterfaceDecl>(Record, Idx);
    620   unsigned NumProtoRefs = Record[Idx++];
    621   SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
    622   ProtoRefs.reserve(NumProtoRefs);
    623   for (unsigned I = 0; I != NumProtoRefs; ++I)
    624     ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
    625   SmallVector<SourceLocation, 16> ProtoLocs;
    626   ProtoLocs.reserve(NumProtoRefs);
    627   for (unsigned I = 0; I != NumProtoRefs; ++I)
    628     ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
    629   CD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
    630                       Reader.getContext());
    631   CD->NextClassCategory = ReadDeclAs<ObjCCategoryDecl>(Record, Idx);
    632   CD->setHasSynthBitfield(Record[Idx++]);
    633   CD->setCategoryNameLoc(ReadSourceLocation(Record, Idx));
    634 }
    635 
    636 void ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
    637   VisitNamedDecl(CAD);
    638   CAD->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
    639 }
    640 
    641 void ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
    642   VisitNamedDecl(D);
    643   D->setAtLoc(ReadSourceLocation(Record, Idx));
    644   D->setType(GetTypeSourceInfo(Record, Idx));
    645   // FIXME: stable encoding
    646   D->setPropertyAttributes(
    647                       (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
    648   D->setPropertyAttributesAsWritten(
    649                       (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
    650   // FIXME: stable encoding
    651   D->setPropertyImplementation(
    652                             (ObjCPropertyDecl::PropertyControl)Record[Idx++]);
    653   D->setGetterName(Reader.ReadDeclarationName(F,Record, Idx).getObjCSelector());
    654   D->setSetterName(Reader.ReadDeclarationName(F,Record, Idx).getObjCSelector());
    655   D->setGetterMethodDecl(ReadDeclAs<ObjCMethodDecl>(Record, Idx));
    656   D->setSetterMethodDecl(ReadDeclAs<ObjCMethodDecl>(Record, Idx));
    657   D->setPropertyIvarDecl(ReadDeclAs<ObjCIvarDecl>(Record, Idx));
    658 }
    659 
    660 void ASTDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) {
    661   VisitObjCContainerDecl(D);
    662   D->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
    663 }
    664 
    665 void ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
    666   VisitObjCImplDecl(D);
    667   D->setIdentifier(Reader.GetIdentifierInfo(F, Record, Idx));
    668 }
    669 
    670 void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
    671   VisitObjCImplDecl(D);
    672   D->setSuperClass(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
    673   llvm::tie(D->IvarInitializers, D->NumIvarInitializers)
    674       = Reader.ReadCXXCtorInitializers(F, Record, Idx);
    675   D->setHasSynthBitfield(Record[Idx++]);
    676 }
    677 
    678 
    679 void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
    680   VisitDecl(D);
    681   D->setAtLoc(ReadSourceLocation(Record, Idx));
    682   D->setPropertyDecl(ReadDeclAs<ObjCPropertyDecl>(Record, Idx));
    683   D->PropertyIvarDecl = ReadDeclAs<ObjCIvarDecl>(Record, Idx);
    684   D->IvarLoc = ReadSourceLocation(Record, Idx);
    685   D->setGetterCXXConstructor(Reader.ReadExpr(F));
    686   D->setSetterCXXAssignment(Reader.ReadExpr(F));
    687 }
    688 
    689 void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {
    690   VisitDeclaratorDecl(FD);
    691   FD->setMutable(Record[Idx++]);
    692   int BitWidthOrInitializer = Record[Idx++];
    693   if (BitWidthOrInitializer == 1)
    694     FD->setBitWidth(Reader.ReadExpr(F));
    695   else if (BitWidthOrInitializer == 2)
    696     FD->setInClassInitializer(Reader.ReadExpr(F));
    697   if (!FD->getDeclName()) {
    698     if (FieldDecl *Tmpl = ReadDeclAs<FieldDecl>(Record, Idx))
    699       Reader.getContext().setInstantiatedFromUnnamedFieldDecl(FD, Tmpl);
    700   }
    701 }
    702 
    703 void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
    704   VisitValueDecl(FD);
    705 
    706   FD->ChainingSize = Record[Idx++];
    707   assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2");
    708   FD->Chaining = new (Reader.getContext())NamedDecl*[FD->ChainingSize];
    709 
    710   for (unsigned I = 0; I != FD->ChainingSize; ++I)
    711     FD->Chaining[I] = ReadDeclAs<NamedDecl>(Record, Idx);
    712 }
    713 
    714 void ASTDeclReader::VisitVarDecl(VarDecl *VD) {
    715   VisitDeclaratorDecl(VD);
    716   VisitRedeclarable(VD);
    717   VD->VarDeclBits.SClass = (StorageClass)Record[Idx++];
    718   VD->VarDeclBits.SClassAsWritten = (StorageClass)Record[Idx++];
    719   VD->VarDeclBits.ThreadSpecified = Record[Idx++];
    720   VD->VarDeclBits.HasCXXDirectInit = Record[Idx++];
    721   VD->VarDeclBits.ExceptionVar = Record[Idx++];
    722   VD->VarDeclBits.NRVOVariable = Record[Idx++];
    723   VD->VarDeclBits.CXXForRangeDecl = Record[Idx++];
    724   VD->VarDeclBits.ARCPseudoStrong = Record[Idx++];
    725   if (Record[Idx++])
    726     VD->setInit(Reader.ReadExpr(F));
    727 
    728   if (Record[Idx++]) { // HasMemberSpecializationInfo.
    729     VarDecl *Tmpl = ReadDeclAs<VarDecl>(Record, Idx);
    730     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
    731     SourceLocation POI = ReadSourceLocation(Record, Idx);
    732     Reader.getContext().setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);
    733   }
    734 }
    735 
    736 void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
    737   VisitVarDecl(PD);
    738 }
    739 
    740 void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
    741   VisitVarDecl(PD);
    742   unsigned isObjCMethodParam = Record[Idx++];
    743   unsigned scopeDepth = Record[Idx++];
    744   unsigned scopeIndex = Record[Idx++];
    745   unsigned declQualifier = Record[Idx++];
    746   if (isObjCMethodParam) {
    747     assert(scopeDepth == 0);
    748     PD->setObjCMethodScopeInfo(scopeIndex);
    749     PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier;
    750   } else {
    751     PD->setScopeInfo(scopeDepth, scopeIndex);
    752   }
    753   PD->ParmVarDeclBits.IsKNRPromoted = Record[Idx++];
    754   PD->ParmVarDeclBits.HasInheritedDefaultArg = Record[Idx++];
    755   if (Record[Idx++]) // hasUninstantiatedDefaultArg.
    756     PD->setUninstantiatedDefaultArg(Reader.ReadExpr(F));
    757 }
    758 
    759 void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
    760   VisitDecl(AD);
    761   AD->setAsmString(cast<StringLiteral>(Reader.ReadExpr(F)));
    762   AD->setRParenLoc(ReadSourceLocation(Record, Idx));
    763 }
    764 
    765 void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
    766   VisitDecl(BD);
    767   BD->setBody(cast_or_null<CompoundStmt>(Reader.ReadStmt(F)));
    768   BD->setSignatureAsWritten(GetTypeSourceInfo(Record, Idx));
    769   unsigned NumParams = Record[Idx++];
    770   SmallVector<ParmVarDecl *, 16> Params;
    771   Params.reserve(NumParams);
    772   for (unsigned I = 0; I != NumParams; ++I)
    773     Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
    774   BD->setParams(Params);
    775 
    776   bool capturesCXXThis = Record[Idx++];
    777   unsigned numCaptures = Record[Idx++];
    778   SmallVector<BlockDecl::Capture, 16> captures;
    779   captures.reserve(numCaptures);
    780   for (unsigned i = 0; i != numCaptures; ++i) {
    781     VarDecl *decl = ReadDeclAs<VarDecl>(Record, Idx);
    782     unsigned flags = Record[Idx++];
    783     bool byRef = (flags & 1);
    784     bool nested = (flags & 2);
    785     Expr *copyExpr = ((flags & 4) ? Reader.ReadExpr(F) : 0);
    786 
    787     captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr));
    788   }
    789   BD->setCaptures(Reader.getContext(), captures.begin(),
    790                   captures.end(), capturesCXXThis);
    791 }
    792 
    793 void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
    794   VisitDecl(D);
    795   D->setLanguage((LinkageSpecDecl::LanguageIDs)Record[Idx++]);
    796   D->setExternLoc(ReadSourceLocation(Record, Idx));
    797   D->setRBraceLoc(ReadSourceLocation(Record, Idx));
    798 }
    799 
    800 void ASTDeclReader::VisitLabelDecl(LabelDecl *D) {
    801   VisitNamedDecl(D);
    802   D->setLocStart(ReadSourceLocation(Record, Idx));
    803 }
    804 
    805 
    806 void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
    807   VisitNamedDecl(D);
    808   D->IsInline = Record[Idx++];
    809   D->LocStart = ReadSourceLocation(Record, Idx);
    810   D->RBraceLoc = ReadSourceLocation(Record, Idx);
    811   D->NextNamespace = Record[Idx++];
    812 
    813   bool IsOriginal = Record[Idx++];
    814   // FIXME: Modules will likely have trouble with pointing directly at
    815   // the original namespace.
    816   D->OrigOrAnonNamespace.setInt(IsOriginal);
    817   D->OrigOrAnonNamespace.setPointer(ReadDeclAs<NamespaceDecl>(Record, Idx));
    818 }
    819 
    820 void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
    821   VisitNamedDecl(D);
    822   D->NamespaceLoc = ReadSourceLocation(Record, Idx);
    823   D->IdentLoc = ReadSourceLocation(Record, Idx);
    824   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
    825   D->Namespace = ReadDeclAs<NamedDecl>(Record, Idx);
    826 }
    827 
    828 void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
    829   VisitNamedDecl(D);
    830   D->setUsingLocation(ReadSourceLocation(Record, Idx));
    831   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
    832   ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
    833   D->FirstUsingShadow = ReadDeclAs<UsingShadowDecl>(Record, Idx);
    834   D->setTypeName(Record[Idx++]);
    835   if (NamedDecl *Pattern = ReadDeclAs<NamedDecl>(Record, Idx))
    836     Reader.getContext().setInstantiatedFromUsingDecl(D, Pattern);
    837 }
    838 
    839 void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
    840   VisitNamedDecl(D);
    841   D->setTargetDecl(ReadDeclAs<NamedDecl>(Record, Idx));
    842   D->UsingOrNextShadow = ReadDeclAs<NamedDecl>(Record, Idx);
    843   UsingShadowDecl *Pattern = ReadDeclAs<UsingShadowDecl>(Record, Idx);
    844   if (Pattern)
    845     Reader.getContext().setInstantiatedFromUsingShadowDecl(D, Pattern);
    846 }
    847 
    848 void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
    849   VisitNamedDecl(D);
    850   D->UsingLoc = ReadSourceLocation(Record, Idx);
    851   D->NamespaceLoc = ReadSourceLocation(Record, Idx);
    852   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
    853   D->NominatedNamespace = ReadDeclAs<NamedDecl>(Record, Idx);
    854   D->CommonAncestor = ReadDeclAs<DeclContext>(Record, Idx);
    855 }
    856 
    857 void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
    858   VisitValueDecl(D);
    859   D->setUsingLoc(ReadSourceLocation(Record, Idx));
    860   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
    861   ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
    862 }
    863 
    864 void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
    865                                                UnresolvedUsingTypenameDecl *D) {
    866   VisitTypeDecl(D);
    867   D->TypenameLocation = ReadSourceLocation(Record, Idx);
    868   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
    869 }
    870 
    871 void ASTDeclReader::ReadCXXDefinitionData(
    872                                    struct CXXRecordDecl::DefinitionData &Data,
    873                                    const RecordData &Record, unsigned &Idx) {
    874   Data.UserDeclaredConstructor = Record[Idx++];
    875   Data.UserDeclaredCopyConstructor = Record[Idx++];
    876   Data.UserDeclaredMoveConstructor = Record[Idx++];
    877   Data.UserDeclaredCopyAssignment = Record[Idx++];
    878   Data.UserDeclaredMoveAssignment = Record[Idx++];
    879   Data.UserDeclaredDestructor = Record[Idx++];
    880   Data.Aggregate = Record[Idx++];
    881   Data.PlainOldData = Record[Idx++];
    882   Data.Empty = Record[Idx++];
    883   Data.Polymorphic = Record[Idx++];
    884   Data.Abstract = Record[Idx++];
    885   Data.IsStandardLayout = Record[Idx++];
    886   Data.HasNoNonEmptyBases = Record[Idx++];
    887   Data.HasPrivateFields = Record[Idx++];
    888   Data.HasProtectedFields = Record[Idx++];
    889   Data.HasPublicFields = Record[Idx++];
    890   Data.HasMutableFields = Record[Idx++];
    891   Data.HasTrivialDefaultConstructor = Record[Idx++];
    892   Data.HasConstexprNonCopyMoveConstructor = Record[Idx++];
    893   Data.HasTrivialCopyConstructor = Record[Idx++];
    894   Data.HasTrivialMoveConstructor = Record[Idx++];
    895   Data.HasTrivialCopyAssignment = Record[Idx++];
    896   Data.HasTrivialMoveAssignment = Record[Idx++];
    897   Data.HasTrivialDestructor = Record[Idx++];
    898   Data.HasNonLiteralTypeFieldsOrBases = Record[Idx++];
    899   Data.ComputedVisibleConversions = Record[Idx++];
    900   Data.UserProvidedDefaultConstructor = Record[Idx++];
    901   Data.DeclaredDefaultConstructor = Record[Idx++];
    902   Data.DeclaredCopyConstructor = Record[Idx++];
    903   Data.DeclaredMoveConstructor = Record[Idx++];
    904   Data.DeclaredCopyAssignment = Record[Idx++];
    905   Data.DeclaredMoveAssignment = Record[Idx++];
    906   Data.DeclaredDestructor = Record[Idx++];
    907   Data.FailedImplicitMoveConstructor = Record[Idx++];
    908   Data.FailedImplicitMoveAssignment = Record[Idx++];
    909 
    910   Data.NumBases = Record[Idx++];
    911   if (Data.NumBases)
    912     Data.Bases = Reader.readCXXBaseSpecifiers(F, Record, Idx);
    913   Data.NumVBases = Record[Idx++];
    914   if (Data.NumVBases)
    915     Data.VBases = Reader.readCXXBaseSpecifiers(F, Record, Idx);
    916 
    917   Reader.ReadUnresolvedSet(F, Data.Conversions, Record, Idx);
    918   Reader.ReadUnresolvedSet(F, Data.VisibleConversions, Record, Idx);
    919   assert(Data.Definition && "Data.Definition should be already set!");
    920   Data.FirstFriend = ReadDeclAs<FriendDecl>(Record, Idx);
    921 }
    922 
    923 void ASTDeclReader::InitializeCXXDefinitionData(CXXRecordDecl *D,
    924                                                 CXXRecordDecl *DefinitionDecl,
    925                                                 const RecordData &Record,
    926                                                 unsigned &Idx) {
    927   ASTContext &C = Reader.getContext();
    928 
    929   if (D == DefinitionDecl) {
    930     D->DefinitionData = new (C) struct CXXRecordDecl::DefinitionData(D);
    931     ReadCXXDefinitionData(*D->DefinitionData, Record, Idx);
    932     // We read the definition info. Check if there are pending forward
    933     // references that need to point to this DefinitionData pointer.
    934     ASTReader::PendingForwardRefsMap::iterator
    935         FindI = Reader.PendingForwardRefs.find(D);
    936     if (FindI != Reader.PendingForwardRefs.end()) {
    937       ASTReader::ForwardRefs &Refs = FindI->second;
    938       for (ASTReader::ForwardRefs::iterator
    939              I = Refs.begin(), E = Refs.end(); I != E; ++I)
    940         (*I)->DefinitionData = D->DefinitionData;
    941 #ifndef NDEBUG
    942       // We later check whether PendingForwardRefs is empty to make sure all
    943       // pending references were linked.
    944       Reader.PendingForwardRefs.erase(D);
    945 #endif
    946     }
    947   } else if (DefinitionDecl) {
    948     if (DefinitionDecl->DefinitionData) {
    949       D->DefinitionData = DefinitionDecl->DefinitionData;
    950     } else {
    951       // The definition is still initializing.
    952       Reader.PendingForwardRefs[DefinitionDecl].push_back(D);
    953     }
    954   }
    955 }
    956 
    957 void ASTDeclReader::VisitCXXRecordDecl(CXXRecordDecl *D) {
    958   VisitRecordDecl(D);
    959 
    960   CXXRecordDecl *DefinitionDecl = ReadDeclAs<CXXRecordDecl>(Record, Idx);
    961   InitializeCXXDefinitionData(D, DefinitionDecl, Record, Idx);
    962 
    963   ASTContext &C = Reader.getContext();
    964 
    965   enum CXXRecKind {
    966     CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
    967   };
    968   switch ((CXXRecKind)Record[Idx++]) {
    969   default:
    970     llvm_unreachable("Out of sync with ASTDeclWriter::VisitCXXRecordDecl?");
    971   case CXXRecNotTemplate:
    972     break;
    973   case CXXRecTemplate:
    974     D->TemplateOrInstantiation = ReadDeclAs<ClassTemplateDecl>(Record, Idx);
    975     break;
    976   case CXXRecMemberSpecialization: {
    977     CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(Record, Idx);
    978     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
    979     SourceLocation POI = ReadSourceLocation(Record, Idx);
    980     MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
    981     MSI->setPointOfInstantiation(POI);
    982     D->TemplateOrInstantiation = MSI;
    983     break;
    984   }
    985   }
    986 
    987   // Load the key function to avoid deserializing every method so we can
    988   // compute it.
    989   if (D->IsCompleteDefinition) {
    990     if (CXXMethodDecl *Key = ReadDeclAs<CXXMethodDecl>(Record, Idx))
    991       C.KeyFunctions[D] = Key;
    992   }
    993 }
    994 
    995 void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
    996   VisitFunctionDecl(D);
    997   unsigned NumOverridenMethods = Record[Idx++];
    998   while (NumOverridenMethods--) {
    999     // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
   1000     // MD may be initializing.
   1001     if (CXXMethodDecl *MD = ReadDeclAs<CXXMethodDecl>(Record, Idx))
   1002       Reader.getContext().addOverriddenMethod(D, MD);
   1003   }
   1004 }
   1005 
   1006 void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
   1007   VisitCXXMethodDecl(D);
   1008 
   1009   D->IsExplicitSpecified = Record[Idx++];
   1010   D->ImplicitlyDefined = Record[Idx++];
   1011   llvm::tie(D->CtorInitializers, D->NumCtorInitializers)
   1012       = Reader.ReadCXXCtorInitializers(F, Record, Idx);
   1013 }
   1014 
   1015 void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
   1016   VisitCXXMethodDecl(D);
   1017 
   1018   D->ImplicitlyDefined = Record[Idx++];
   1019   D->OperatorDelete = ReadDeclAs<FunctionDecl>(Record, Idx);
   1020 }
   1021 
   1022 void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
   1023   VisitCXXMethodDecl(D);
   1024   D->IsExplicitSpecified = Record[Idx++];
   1025 }
   1026 
   1027 void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
   1028   VisitDecl(D);
   1029   D->setColonLoc(ReadSourceLocation(Record, Idx));
   1030 }
   1031 
   1032 void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
   1033   VisitDecl(D);
   1034   if (Record[Idx++])
   1035     D->Friend = GetTypeSourceInfo(Record, Idx);
   1036   else
   1037     D->Friend = ReadDeclAs<NamedDecl>(Record, Idx);
   1038   D->NextFriend = Record[Idx++];
   1039   D->UnsupportedFriend = (Record[Idx++] != 0);
   1040   D->FriendLoc = ReadSourceLocation(Record, Idx);
   1041 }
   1042 
   1043 void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
   1044   VisitDecl(D);
   1045   unsigned NumParams = Record[Idx++];
   1046   D->NumParams = NumParams;
   1047   D->Params = new TemplateParameterList*[NumParams];
   1048   for (unsigned i = 0; i != NumParams; ++i)
   1049     D->Params[i] = Reader.ReadTemplateParameterList(F, Record, Idx);
   1050   if (Record[Idx++]) // HasFriendDecl
   1051     D->Friend = ReadDeclAs<NamedDecl>(Record, Idx);
   1052   else
   1053     D->Friend = GetTypeSourceInfo(Record, Idx);
   1054   D->FriendLoc = ReadSourceLocation(Record, Idx);
   1055 }
   1056 
   1057 void ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
   1058   VisitNamedDecl(D);
   1059 
   1060   NamedDecl *TemplatedDecl = ReadDeclAs<NamedDecl>(Record, Idx);
   1061   TemplateParameterList* TemplateParams
   1062       = Reader.ReadTemplateParameterList(F, Record, Idx);
   1063   D->init(TemplatedDecl, TemplateParams);
   1064 }
   1065 
   1066 void ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
   1067   // Initialize CommonOrPrev before VisitTemplateDecl so that getCommonPtr()
   1068   // can be used while this is still initializing.
   1069 
   1070   assert(D->CommonOrPrev.isNull() && "getCommonPtr was called earlier on this");
   1071   DeclID PreviousDeclID = ReadDeclID(Record, Idx);
   1072   DeclID FirstDeclID =  PreviousDeclID ? ReadDeclID(Record, Idx) : 0;
   1073   // We delay loading of the redeclaration chain to avoid deeply nested calls.
   1074   // We temporarily set the first (canonical) declaration as the previous one
   1075   // which is the one that matters and mark the real previous DeclID to be
   1076   // loaded & attached later on.
   1077   RedeclarableTemplateDecl *FirstDecl =
   1078       cast_or_null<RedeclarableTemplateDecl>(Reader.GetDecl(FirstDeclID));
   1079   assert((FirstDecl == 0 || FirstDecl->getKind() == D->getKind()) &&
   1080          "FirstDecl kind mismatch");
   1081   if (FirstDecl) {
   1082     D->CommonOrPrev = FirstDecl;
   1083     // Mark the real previous DeclID to be loaded & attached later on.
   1084     if (PreviousDeclID != FirstDeclID)
   1085       Reader.PendingPreviousDecls.push_back(std::make_pair(D, PreviousDeclID));
   1086   } else {
   1087     D->CommonOrPrev = D->newCommon(Reader.getContext());
   1088     if (RedeclarableTemplateDecl *RTD
   1089           = ReadDeclAs<RedeclarableTemplateDecl>(Record, Idx)) {
   1090       assert(RTD->getKind() == D->getKind() &&
   1091              "InstantiatedFromMemberTemplate kind mismatch");
   1092       D->setInstantiatedFromMemberTemplateImpl(RTD);
   1093       if (Record[Idx++])
   1094         D->setMemberSpecialization();
   1095     }
   1096 
   1097     RedeclarableTemplateDecl *LatestDecl
   1098       = ReadDeclAs<RedeclarableTemplateDecl>(Record, Idx);
   1099 
   1100     // This decl is a first one and the latest declaration that it points to is
   1101     // in the same AST file. However, if this actually needs to point to a
   1102     // redeclaration in another AST file, we need to update it by checking
   1103     // the FirstLatestDeclIDs map which tracks this kind of decls.
   1104     assert(Reader.GetDecl(ThisDeclID) == D && "Invalid ThisDeclID ?");
   1105     ASTReader::FirstLatestDeclIDMap::iterator I
   1106         = Reader.FirstLatestDeclIDs.find(ThisDeclID);
   1107     if (I != Reader.FirstLatestDeclIDs.end()) {
   1108       if (Decl *NewLatest = Reader.GetDecl(I->second))
   1109         LatestDecl = cast<RedeclarableTemplateDecl>(NewLatest);
   1110     }
   1111 
   1112     assert(LatestDecl->getKind() == D->getKind() && "Latest kind mismatch");
   1113     D->getCommonPtr()->Latest = LatestDecl;
   1114   }
   1115 
   1116   VisitTemplateDecl(D);
   1117   D->IdentifierNamespace = Record[Idx++];
   1118 }
   1119 
   1120 void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
   1121   VisitRedeclarableTemplateDecl(D);
   1122 
   1123   if (D->getPreviousDeclaration() == 0) {
   1124     // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
   1125     // the specializations.
   1126     SmallVector<serialization::DeclID, 2> SpecIDs;
   1127     SpecIDs.push_back(0);
   1128 
   1129     // Specializations.
   1130     unsigned Size = Record[Idx++];
   1131     SpecIDs[0] += Size;
   1132     for (unsigned I = 0; I != Size; ++I)
   1133       SpecIDs.push_back(ReadDeclID(Record, Idx));
   1134 
   1135     // Partial specializations.
   1136     Size = Record[Idx++];
   1137     SpecIDs[0] += Size;
   1138     for (unsigned I = 0; I != Size; ++I)
   1139       SpecIDs.push_back(ReadDeclID(Record, Idx));
   1140 
   1141     if (SpecIDs[0]) {
   1142       typedef serialization::DeclID DeclID;
   1143 
   1144       ClassTemplateDecl::Common *CommonPtr = D->getCommonPtr();
   1145       CommonPtr->LazySpecializations
   1146         = new (Reader.getContext()) DeclID [SpecIDs.size()];
   1147       memcpy(CommonPtr->LazySpecializations, SpecIDs.data(),
   1148              SpecIDs.size() * sizeof(DeclID));
   1149     }
   1150 
   1151     // InjectedClassNameType is computed.
   1152   }
   1153 }
   1154 
   1155 void ASTDeclReader::VisitClassTemplateSpecializationDecl(
   1156                                            ClassTemplateSpecializationDecl *D) {
   1157   VisitCXXRecordDecl(D);
   1158 
   1159   ASTContext &C = Reader.getContext();
   1160   if (Decl *InstD = ReadDecl(Record, Idx)) {
   1161     if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
   1162       D->SpecializedTemplate = CTD;
   1163     } else {
   1164       SmallVector<TemplateArgument, 8> TemplArgs;
   1165       Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
   1166       TemplateArgumentList *ArgList
   1167         = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
   1168                                            TemplArgs.size());
   1169       ClassTemplateSpecializationDecl::SpecializedPartialSpecialization *PS
   1170           = new (C) ClassTemplateSpecializationDecl::
   1171                                              SpecializedPartialSpecialization();
   1172       PS->PartialSpecialization
   1173           = cast<ClassTemplatePartialSpecializationDecl>(InstD);
   1174       PS->TemplateArgs = ArgList;
   1175       D->SpecializedTemplate = PS;
   1176     }
   1177   }
   1178 
   1179   // Explicit info.
   1180   if (TypeSourceInfo *TyInfo = GetTypeSourceInfo(Record, Idx)) {
   1181     ClassTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo
   1182         = new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
   1183     ExplicitInfo->TypeAsWritten = TyInfo;
   1184     ExplicitInfo->ExternLoc = ReadSourceLocation(Record, Idx);
   1185     ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation(Record, Idx);
   1186     D->ExplicitInfo = ExplicitInfo;
   1187   }
   1188 
   1189   SmallVector<TemplateArgument, 8> TemplArgs;
   1190   Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
   1191   D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
   1192                                                      TemplArgs.size());
   1193   D->PointOfInstantiation = ReadSourceLocation(Record, Idx);
   1194   D->SpecializationKind = (TemplateSpecializationKind)Record[Idx++];
   1195 
   1196   if (D->isCanonicalDecl()) { // It's kept in the folding set.
   1197     ClassTemplateDecl *CanonPattern = ReadDeclAs<ClassTemplateDecl>(Record,Idx);
   1198     if (ClassTemplatePartialSpecializationDecl *Partial
   1199                        = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
   1200       CanonPattern->getCommonPtr()->PartialSpecializations.InsertNode(Partial);
   1201     } else {
   1202       CanonPattern->getCommonPtr()->Specializations.InsertNode(D);
   1203     }
   1204   }
   1205 }
   1206 
   1207 void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
   1208                                     ClassTemplatePartialSpecializationDecl *D) {
   1209   VisitClassTemplateSpecializationDecl(D);
   1210 
   1211   ASTContext &C = Reader.getContext();
   1212   D->TemplateParams = Reader.ReadTemplateParameterList(F, Record, Idx);
   1213 
   1214   unsigned NumArgs = Record[Idx++];
   1215   if (NumArgs) {
   1216     D->NumArgsAsWritten = NumArgs;
   1217     D->ArgsAsWritten = new (C) TemplateArgumentLoc[NumArgs];
   1218     for (unsigned i=0; i != NumArgs; ++i)
   1219       D->ArgsAsWritten[i] = Reader.ReadTemplateArgumentLoc(F, Record, Idx);
   1220   }
   1221 
   1222   D->SequenceNumber = Record[Idx++];
   1223 
   1224   // These are read/set from/to the first declaration.
   1225   if (D->getPreviousDeclaration() == 0) {
   1226     D->InstantiatedFromMember.setPointer(
   1227       ReadDeclAs<ClassTemplatePartialSpecializationDecl>(Record, Idx));
   1228     D->InstantiatedFromMember.setInt(Record[Idx++]);
   1229   }
   1230 }
   1231 
   1232 void ASTDeclReader::VisitClassScopeFunctionSpecializationDecl(
   1233                                     ClassScopeFunctionSpecializationDecl *D) {
   1234   VisitDecl(D);
   1235   D->Specialization = ReadDeclAs<CXXMethodDecl>(Record, Idx);
   1236 }
   1237 
   1238 void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
   1239   VisitRedeclarableTemplateDecl(D);
   1240 
   1241   if (D->getPreviousDeclaration() == 0) {
   1242     // This FunctionTemplateDecl owns a CommonPtr; read it.
   1243 
   1244     // Read the function specialization declarations.
   1245     // FunctionTemplateDecl's FunctionTemplateSpecializationInfos are filled
   1246     // when reading the specialized FunctionDecl.
   1247     unsigned NumSpecs = Record[Idx++];
   1248     while (NumSpecs--)
   1249       (void)ReadDecl(Record, Idx);
   1250   }
   1251 }
   1252 
   1253 void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
   1254   VisitTypeDecl(D);
   1255 
   1256   D->setDeclaredWithTypename(Record[Idx++]);
   1257 
   1258   bool Inherited = Record[Idx++];
   1259   TypeSourceInfo *DefArg = GetTypeSourceInfo(Record, Idx);
   1260   D->setDefaultArgument(DefArg, Inherited);
   1261 }
   1262 
   1263 void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
   1264   VisitDeclaratorDecl(D);
   1265   // TemplateParmPosition.
   1266   D->setDepth(Record[Idx++]);
   1267   D->setPosition(Record[Idx++]);
   1268   if (D->isExpandedParameterPack()) {
   1269     void **Data = reinterpret_cast<void **>(D + 1);
   1270     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
   1271       Data[2*I] = Reader.readType(F, Record, Idx).getAsOpaquePtr();
   1272       Data[2*I + 1] = GetTypeSourceInfo(Record, Idx);
   1273     }
   1274   } else {
   1275     // Rest of NonTypeTemplateParmDecl.
   1276     D->ParameterPack = Record[Idx++];
   1277     if (Record[Idx++]) {
   1278       Expr *DefArg = Reader.ReadExpr(F);
   1279       bool Inherited = Record[Idx++];
   1280       D->setDefaultArgument(DefArg, Inherited);
   1281    }
   1282   }
   1283 }
   1284 
   1285 void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
   1286   VisitTemplateDecl(D);
   1287   // TemplateParmPosition.
   1288   D->setDepth(Record[Idx++]);
   1289   D->setPosition(Record[Idx++]);
   1290   // Rest of TemplateTemplateParmDecl.
   1291   TemplateArgumentLoc Arg = Reader.ReadTemplateArgumentLoc(F, Record, Idx);
   1292   bool IsInherited = Record[Idx++];
   1293   D->setDefaultArgument(Arg, IsInherited);
   1294   D->ParameterPack = Record[Idx++];
   1295 }
   1296 
   1297 void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
   1298   VisitRedeclarableTemplateDecl(D);
   1299 }
   1300 
   1301 void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
   1302   VisitDecl(D);
   1303   D->AssertExpr = Reader.ReadExpr(F);
   1304   D->Message = cast<StringLiteral>(Reader.ReadExpr(F));
   1305   D->RParenLoc = ReadSourceLocation(Record, Idx);
   1306 }
   1307 
   1308 std::pair<uint64_t, uint64_t>
   1309 ASTDeclReader::VisitDeclContext(DeclContext *DC) {
   1310   uint64_t LexicalOffset = Record[Idx++];
   1311   uint64_t VisibleOffset = Record[Idx++];
   1312   return std::make_pair(LexicalOffset, VisibleOffset);
   1313 }
   1314 
   1315 template <typename T>
   1316 void ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
   1317   enum RedeclKind { NoRedeclaration = 0, PointsToPrevious, PointsToLatest };
   1318   RedeclKind Kind = (RedeclKind)Record[Idx++];
   1319   switch (Kind) {
   1320   default:
   1321     llvm_unreachable("Out of sync with ASTDeclWriter::VisitRedeclarable or"
   1322                      " messed up reading");
   1323   case NoRedeclaration:
   1324     break;
   1325   case PointsToPrevious: {
   1326     DeclID PreviousDeclID = ReadDeclID(Record, Idx);
   1327     DeclID FirstDeclID = ReadDeclID(Record, Idx);
   1328     // We delay loading of the redeclaration chain to avoid deeply nested calls.
   1329     // We temporarily set the first (canonical) declaration as the previous one
   1330     // which is the one that matters and mark the real previous DeclID to be
   1331     // loaded & attached later on.
   1332     D->RedeclLink = typename Redeclarable<T>::PreviousDeclLink(
   1333                                 cast_or_null<T>(Reader.GetDecl(FirstDeclID)));
   1334     if (PreviousDeclID != FirstDeclID)
   1335       Reader.PendingPreviousDecls.push_back(std::make_pair(static_cast<T*>(D),
   1336                                                            PreviousDeclID));
   1337     break;
   1338   }
   1339   case PointsToLatest:
   1340     D->RedeclLink = typename Redeclarable<T>::LatestDeclLink(
   1341                                                    ReadDeclAs<T>(Record, Idx));
   1342     break;
   1343   }
   1344 
   1345   assert(!(Kind == PointsToPrevious &&
   1346            Reader.FirstLatestDeclIDs.find(ThisDeclID) !=
   1347                Reader.FirstLatestDeclIDs.end()) &&
   1348          "This decl is not first, it should not be in the map");
   1349   if (Kind == PointsToPrevious)
   1350     return;
   1351 
   1352   // This decl is a first one and the latest declaration that it points to is in
   1353   // the same AST file. However, if this actually needs to point to a
   1354   // redeclaration in another AST file, we need to update it by checking the
   1355   // FirstLatestDeclIDs map which tracks this kind of decls.
   1356   assert(Reader.GetDecl(ThisDeclID) == static_cast<T*>(D) &&
   1357          "Invalid ThisDeclID ?");
   1358   ASTReader::FirstLatestDeclIDMap::iterator I
   1359       = Reader.FirstLatestDeclIDs.find(ThisDeclID);
   1360   if (I != Reader.FirstLatestDeclIDs.end()) {
   1361     Decl *NewLatest = Reader.GetDecl(I->second);
   1362     D->RedeclLink
   1363         = typename Redeclarable<T>::LatestDeclLink(cast_or_null<T>(NewLatest));
   1364   }
   1365 }
   1366 
   1367 //===----------------------------------------------------------------------===//
   1368 // Attribute Reading
   1369 //===----------------------------------------------------------------------===//
   1370 
   1371 /// \brief Reads attributes from the current stream position.
   1372 void ASTReader::ReadAttributes(Module &F, AttrVec &Attrs,
   1373                                const RecordData &Record, unsigned &Idx) {
   1374   for (unsigned i = 0, e = Record[Idx++]; i != e; ++i) {
   1375     Attr *New = 0;
   1376     attr::Kind Kind = (attr::Kind)Record[Idx++];
   1377     SourceRange Range = ReadSourceRange(F, Record, Idx);
   1378 
   1379 #include "clang/Serialization/AttrPCHRead.inc"
   1380 
   1381     assert(New && "Unable to decode attribute?");
   1382     Attrs.push_back(New);
   1383   }
   1384 }
   1385 
   1386 //===----------------------------------------------------------------------===//
   1387 // ASTReader Implementation
   1388 //===----------------------------------------------------------------------===//
   1389 
   1390 /// \brief Note that we have loaded the declaration with the given
   1391 /// Index.
   1392 ///
   1393 /// This routine notes that this declaration has already been loaded,
   1394 /// so that future GetDecl calls will return this declaration rather
   1395 /// than trying to load a new declaration.
   1396 inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
   1397   assert(!DeclsLoaded[Index] && "Decl loaded twice?");
   1398   DeclsLoaded[Index] = D;
   1399 }
   1400 
   1401 
   1402 /// \brief Determine whether the consumer will be interested in seeing
   1403 /// this declaration (via HandleTopLevelDecl).
   1404 ///
   1405 /// This routine should return true for anything that might affect
   1406 /// code generation, e.g., inline function definitions, Objective-C
   1407 /// declarations with metadata, etc.
   1408 static bool isConsumerInterestedIn(Decl *D) {
   1409   // An ObjCMethodDecl is never considered as "interesting" because its
   1410   // implementation container always is.
   1411 
   1412   if (isa<FileScopeAsmDecl>(D) ||
   1413       isa<ObjCProtocolDecl>(D) ||
   1414       isa<ObjCImplDecl>(D))
   1415     return true;
   1416   if (VarDecl *Var = dyn_cast<VarDecl>(D))
   1417     return Var->isFileVarDecl() &&
   1418            Var->isThisDeclarationADefinition() == VarDecl::Definition;
   1419   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
   1420     return Func->doesThisDeclarationHaveABody();
   1421 
   1422   return false;
   1423 }
   1424 
   1425 /// \brief Get the correct cursor and offset for loading a declaration.
   1426 ASTReader::RecordLocation
   1427 ASTReader::DeclCursorForID(DeclID ID) {
   1428   // See if there's an override.
   1429   DeclReplacementMap::iterator It = ReplacedDecls.find(ID);
   1430   if (It != ReplacedDecls.end())
   1431     return RecordLocation(It->second.first, It->second.second);
   1432 
   1433   GlobalDeclMapType::iterator I = GlobalDeclMap.find(ID);
   1434   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
   1435   Module *M = I->second;
   1436   return RecordLocation(M,
   1437            M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS]);
   1438 }
   1439 
   1440 ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
   1441   ContinuousRangeMap<uint64_t, Module*, 4>::iterator I
   1442     = GlobalBitOffsetsMap.find(GlobalOffset);
   1443 
   1444   assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map");
   1445   return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
   1446 }
   1447 
   1448 uint64_t ASTReader::getGlobalBitOffset(Module &M, uint32_t LocalOffset) {
   1449   return LocalOffset + M.GlobalBitOffset;
   1450 }
   1451 
   1452 void ASTDeclReader::attachPreviousDecl(Decl *D, Decl *previous) {
   1453   assert(D && previous);
   1454   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
   1455     TD->RedeclLink.setPointer(cast<TagDecl>(previous));
   1456   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
   1457     FD->RedeclLink.setPointer(cast<FunctionDecl>(previous));
   1458   } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
   1459     VD->RedeclLink.setPointer(cast<VarDecl>(previous));
   1460   } else {
   1461     RedeclarableTemplateDecl *TD = cast<RedeclarableTemplateDecl>(D);
   1462     TD->CommonOrPrev = cast<RedeclarableTemplateDecl>(previous);
   1463   }
   1464 }
   1465 
   1466 void ASTReader::loadAndAttachPreviousDecl(Decl *D, serialization::DeclID ID) {
   1467   Decl *previous = GetDecl(ID);
   1468   ASTDeclReader::attachPreviousDecl(D, previous);
   1469 }
   1470 
   1471 /// \brief Read the declaration at the given offset from the AST file.
   1472 Decl *ASTReader::ReadDeclRecord(DeclID ID) {
   1473   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
   1474   RecordLocation Loc = DeclCursorForID(ID);
   1475   llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
   1476   // Keep track of where we are in the stream, then jump back there
   1477   // after reading this declaration.
   1478   SavedStreamPosition SavedPosition(DeclsCursor);
   1479 
   1480   ReadingKindTracker ReadingKind(Read_Decl, *this);
   1481 
   1482   // Note that we are loading a declaration record.
   1483   Deserializing ADecl(this);
   1484 
   1485   DeclsCursor.JumpToBit(Loc.Offset);
   1486   RecordData Record;
   1487   unsigned Code = DeclsCursor.ReadCode();
   1488   unsigned Idx = 0;
   1489   ASTDeclReader Reader(*this, *Loc.F, DeclsCursor, ID, Record, Idx);
   1490 
   1491   Decl *D = 0;
   1492   switch ((DeclCode)DeclsCursor.ReadRecord(Code, Record)) {
   1493   case DECL_CONTEXT_LEXICAL:
   1494   case DECL_CONTEXT_VISIBLE:
   1495     llvm_unreachable("Record cannot be de-serialized with ReadDeclRecord");
   1496   case DECL_TYPEDEF:
   1497     D = TypedefDecl::Create(Context, 0, SourceLocation(), SourceLocation(),
   1498                             0, 0);
   1499     break;
   1500   case DECL_TYPEALIAS:
   1501     D = TypeAliasDecl::Create(Context, 0, SourceLocation(), SourceLocation(),
   1502                               0, 0);
   1503     break;
   1504   case DECL_ENUM:
   1505     D = EnumDecl::Create(Context, Decl::EmptyShell());
   1506     break;
   1507   case DECL_RECORD:
   1508     D = RecordDecl::Create(Context, Decl::EmptyShell());
   1509     break;
   1510   case DECL_ENUM_CONSTANT:
   1511     D = EnumConstantDecl::Create(Context, 0, SourceLocation(), 0, QualType(),
   1512                                  0, llvm::APSInt());
   1513     break;
   1514   case DECL_FUNCTION:
   1515     D = FunctionDecl::Create(Context, 0, SourceLocation(), SourceLocation(),
   1516                              DeclarationName(), QualType(), 0);
   1517     break;
   1518   case DECL_LINKAGE_SPEC:
   1519     D = LinkageSpecDecl::Create(Context, 0, SourceLocation(), SourceLocation(),
   1520                                 (LinkageSpecDecl::LanguageIDs)0,
   1521                                 SourceLocation());
   1522     break;
   1523   case DECL_LABEL:
   1524     D = LabelDecl::Create(Context, 0, SourceLocation(), 0);
   1525     break;
   1526   case DECL_NAMESPACE:
   1527     D = NamespaceDecl::Create(Context, 0, SourceLocation(),
   1528                               SourceLocation(), 0);
   1529     break;
   1530   case DECL_NAMESPACE_ALIAS:
   1531     D = NamespaceAliasDecl::Create(Context, 0, SourceLocation(),
   1532                                    SourceLocation(), 0,
   1533                                    NestedNameSpecifierLoc(),
   1534                                    SourceLocation(), 0);
   1535     break;
   1536   case DECL_USING:
   1537     D = UsingDecl::Create(Context, 0, SourceLocation(),
   1538                           NestedNameSpecifierLoc(), DeclarationNameInfo(),
   1539                           false);
   1540     break;
   1541   case DECL_USING_SHADOW:
   1542     D = UsingShadowDecl::Create(Context, 0, SourceLocation(), 0, 0);
   1543     break;
   1544   case DECL_USING_DIRECTIVE:
   1545     D = UsingDirectiveDecl::Create(Context, 0, SourceLocation(),
   1546                                    SourceLocation(), NestedNameSpecifierLoc(),
   1547                                    SourceLocation(), 0, 0);
   1548     break;
   1549   case DECL_UNRESOLVED_USING_VALUE:
   1550     D = UnresolvedUsingValueDecl::Create(Context, 0, SourceLocation(),
   1551                                          NestedNameSpecifierLoc(),
   1552                                          DeclarationNameInfo());
   1553     break;
   1554   case DECL_UNRESOLVED_USING_TYPENAME:
   1555     D = UnresolvedUsingTypenameDecl::Create(Context, 0, SourceLocation(),
   1556                                             SourceLocation(),
   1557                                             NestedNameSpecifierLoc(),
   1558                                             SourceLocation(),
   1559                                             DeclarationName());
   1560     break;
   1561   case DECL_CXX_RECORD:
   1562     D = CXXRecordDecl::Create(Context, Decl::EmptyShell());
   1563     break;
   1564   case DECL_CXX_METHOD:
   1565     D = CXXMethodDecl::Create(Context, 0, SourceLocation(),
   1566                               DeclarationNameInfo(), QualType(), 0,
   1567                               false, SC_None, false, false, SourceLocation());
   1568     break;
   1569   case DECL_CXX_CONSTRUCTOR:
   1570     D = CXXConstructorDecl::Create(Context, Decl::EmptyShell());
   1571     break;
   1572   case DECL_CXX_DESTRUCTOR:
   1573     D = CXXDestructorDecl::Create(Context, Decl::EmptyShell());
   1574     break;
   1575   case DECL_CXX_CONVERSION:
   1576     D = CXXConversionDecl::Create(Context, Decl::EmptyShell());
   1577     break;
   1578   case DECL_ACCESS_SPEC:
   1579     D = AccessSpecDecl::Create(Context, Decl::EmptyShell());
   1580     break;
   1581   case DECL_FRIEND:
   1582     D = FriendDecl::Create(Context, Decl::EmptyShell());
   1583     break;
   1584   case DECL_FRIEND_TEMPLATE:
   1585     D = FriendTemplateDecl::Create(Context, Decl::EmptyShell());
   1586     break;
   1587   case DECL_CLASS_TEMPLATE:
   1588     D = ClassTemplateDecl::Create(Context, Decl::EmptyShell());
   1589     break;
   1590   case DECL_CLASS_TEMPLATE_SPECIALIZATION:
   1591     D = ClassTemplateSpecializationDecl::Create(Context, Decl::EmptyShell());
   1592     break;
   1593   case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
   1594     D = ClassTemplatePartialSpecializationDecl::Create(Context,
   1595                                                        Decl::EmptyShell());
   1596     break;
   1597   case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
   1598     D = ClassScopeFunctionSpecializationDecl::Create(Context,
   1599                                                      Decl::EmptyShell());
   1600     break;
   1601   case DECL_FUNCTION_TEMPLATE:
   1602       D = FunctionTemplateDecl::Create(Context, Decl::EmptyShell());
   1603     break;
   1604   case DECL_TEMPLATE_TYPE_PARM:
   1605     D = TemplateTypeParmDecl::Create(Context, Decl::EmptyShell());
   1606     break;
   1607   case DECL_NON_TYPE_TEMPLATE_PARM:
   1608     D = NonTypeTemplateParmDecl::Create(Context, 0, SourceLocation(),
   1609                                         SourceLocation(), 0, 0, 0, QualType(),
   1610                                         false, 0);
   1611     break;
   1612   case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK:
   1613     D = NonTypeTemplateParmDecl::Create(Context, 0, SourceLocation(),
   1614                                         SourceLocation(), 0, 0, 0, QualType(),
   1615                                         0, 0, Record[Idx++], 0);
   1616     break;
   1617   case DECL_TEMPLATE_TEMPLATE_PARM:
   1618     D = TemplateTemplateParmDecl::Create(Context, 0, SourceLocation(), 0, 0,
   1619                                          false, 0, 0);
   1620     break;
   1621   case DECL_TYPE_ALIAS_TEMPLATE:
   1622     D = TypeAliasTemplateDecl::Create(Context, Decl::EmptyShell());
   1623     break;
   1624   case DECL_STATIC_ASSERT:
   1625     D = StaticAssertDecl::Create(Context, 0, SourceLocation(), 0, 0,
   1626                                  SourceLocation());
   1627     break;
   1628 
   1629   case DECL_OBJC_METHOD:
   1630     D = ObjCMethodDecl::Create(Context, SourceLocation(), SourceLocation(),
   1631                                Selector(), QualType(), 0, 0);
   1632     break;
   1633   case DECL_OBJC_INTERFACE:
   1634     D = ObjCInterfaceDecl::Create(Context, 0, SourceLocation(), 0);
   1635     break;
   1636   case DECL_OBJC_IVAR:
   1637     D = ObjCIvarDecl::Create(Context, 0, SourceLocation(), SourceLocation(),
   1638                              0, QualType(), 0, ObjCIvarDecl::None);
   1639     break;
   1640   case DECL_OBJC_PROTOCOL:
   1641     D = ObjCProtocolDecl::Create(Context, 0, 0, SourceLocation(),
   1642                                  SourceLocation(), 0);
   1643     break;
   1644   case DECL_OBJC_AT_DEFS_FIELD:
   1645     D = ObjCAtDefsFieldDecl::Create(Context, 0, SourceLocation(),
   1646                                     SourceLocation(), 0, QualType(), 0);
   1647     break;
   1648   case DECL_OBJC_CLASS:
   1649     D = ObjCClassDecl::Create(Context, 0, SourceLocation());
   1650     break;
   1651   case DECL_OBJC_FORWARD_PROTOCOL:
   1652     D = ObjCForwardProtocolDecl::Create(Context, 0, SourceLocation());
   1653     break;
   1654   case DECL_OBJC_CATEGORY:
   1655     D = ObjCCategoryDecl::Create(Context, Decl::EmptyShell());
   1656     break;
   1657   case DECL_OBJC_CATEGORY_IMPL:
   1658     D = ObjCCategoryImplDecl::Create(Context, 0, 0, 0, SourceLocation(),
   1659                                      SourceLocation());
   1660     break;
   1661   case DECL_OBJC_IMPLEMENTATION:
   1662     D = ObjCImplementationDecl::Create(Context, 0, 0, 0, SourceLocation(),
   1663                                        SourceLocation());
   1664     break;
   1665   case DECL_OBJC_COMPATIBLE_ALIAS:
   1666     D = ObjCCompatibleAliasDecl::Create(Context, 0, SourceLocation(), 0, 0);
   1667     break;
   1668   case DECL_OBJC_PROPERTY:
   1669     D = ObjCPropertyDecl::Create(Context, 0, SourceLocation(), 0, SourceLocation(),
   1670                                  0);
   1671     break;
   1672   case DECL_OBJC_PROPERTY_IMPL:
   1673     D = ObjCPropertyImplDecl::Create(Context, 0, SourceLocation(),
   1674                                      SourceLocation(), 0,
   1675                                      ObjCPropertyImplDecl::Dynamic, 0,
   1676                                      SourceLocation());
   1677     break;
   1678   case DECL_FIELD:
   1679     D = FieldDecl::Create(Context, 0, SourceLocation(), SourceLocation(), 0,
   1680                           QualType(), 0, 0, false, false);
   1681     break;
   1682   case DECL_INDIRECTFIELD:
   1683     D = IndirectFieldDecl::Create(Context, 0, SourceLocation(), 0, QualType(),
   1684                                   0, 0);
   1685     break;
   1686   case DECL_VAR:
   1687     D = VarDecl::Create(Context, 0, SourceLocation(), SourceLocation(), 0,
   1688                         QualType(), 0, SC_None, SC_None);
   1689     break;
   1690 
   1691   case DECL_IMPLICIT_PARAM:
   1692     D = ImplicitParamDecl::Create(Context, 0, SourceLocation(), 0, QualType());
   1693     break;
   1694 
   1695   case DECL_PARM_VAR:
   1696     D = ParmVarDecl::Create(Context, 0, SourceLocation(), SourceLocation(), 0,
   1697                             QualType(), 0, SC_None, SC_None, 0);
   1698     break;
   1699   case DECL_FILE_SCOPE_ASM:
   1700     D = FileScopeAsmDecl::Create(Context, 0, 0, SourceLocation(),
   1701                                  SourceLocation());
   1702     break;
   1703   case DECL_BLOCK:
   1704     D = BlockDecl::Create(Context, 0, SourceLocation());
   1705     break;
   1706   case DECL_CXX_BASE_SPECIFIERS:
   1707     Error("attempt to read a C++ base-specifier record as a declaration");
   1708     return 0;
   1709   }
   1710 
   1711   assert(D && "Unknown declaration reading AST file");
   1712   LoadedDecl(Index, D);
   1713   Reader.Visit(D);
   1714 
   1715   // If this declaration is also a declaration context, get the
   1716   // offsets for its tables of lexical and visible declarations.
   1717   if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
   1718     std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
   1719     if (Offsets.first || Offsets.second) {
   1720       if (Offsets.first != 0)
   1721         DC->setHasExternalLexicalStorage(true);
   1722       if (Offsets.second != 0)
   1723         DC->setHasExternalVisibleStorage(true);
   1724       if (ReadDeclContextStorage(*Loc.F, DeclsCursor, Offsets,
   1725                                  Loc.F->DeclContextInfos[DC]))
   1726         return 0;
   1727     }
   1728 
   1729     // Now add the pending visible updates for this decl context, if it has any.
   1730     DeclContextVisibleUpdatesPending::iterator I =
   1731         PendingVisibleUpdates.find(ID);
   1732     if (I != PendingVisibleUpdates.end()) {
   1733       // There are updates. This means the context has external visible
   1734       // storage, even if the original stored version didn't.
   1735       DC->setHasExternalVisibleStorage(true);
   1736       DeclContextVisibleUpdates &U = I->second;
   1737       for (DeclContextVisibleUpdates::iterator UI = U.begin(), UE = U.end();
   1738            UI != UE; ++UI) {
   1739         UI->second->DeclContextInfos[DC].NameLookupTableData = UI->first;
   1740       }
   1741       PendingVisibleUpdates.erase(I);
   1742     }
   1743   }
   1744   assert(Idx == Record.size());
   1745 
   1746   // Load any relevant update records.
   1747   loadDeclUpdateRecords(ID, D);
   1748 
   1749   if (ObjCChainedCategoriesInterfaces.count(ID))
   1750     loadObjCChainedCategories(ID, cast<ObjCInterfaceDecl>(D));
   1751 
   1752   // If we have deserialized a declaration that has a definition the
   1753   // AST consumer might need to know about, queue it.
   1754   // We don't pass it to the consumer immediately because we may be in recursive
   1755   // loading, and some declarations may still be initializing.
   1756   if (isConsumerInterestedIn(D))
   1757       InterestingDecls.push_back(D);
   1758 
   1759   return D;
   1760 }
   1761 
   1762 void ASTReader::loadDeclUpdateRecords(serialization::DeclID ID, Decl *D) {
   1763   // The declaration may have been modified by files later in the chain.
   1764   // If this is the case, read the record containing the updates from each file
   1765   // and pass it to ASTDeclReader to make the modifications.
   1766   DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
   1767   if (UpdI != DeclUpdateOffsets.end()) {
   1768     FileOffsetsTy &UpdateOffsets = UpdI->second;
   1769     for (FileOffsetsTy::iterator
   1770          I = UpdateOffsets.begin(), E = UpdateOffsets.end(); I != E; ++I) {
   1771       Module *F = I->first;
   1772       uint64_t Offset = I->second;
   1773       llvm::BitstreamCursor &Cursor = F->DeclsCursor;
   1774       SavedStreamPosition SavedPosition(Cursor);
   1775       Cursor.JumpToBit(Offset);
   1776       RecordData Record;
   1777       unsigned Code = Cursor.ReadCode();
   1778       unsigned RecCode = Cursor.ReadRecord(Code, Record);
   1779       (void)RecCode;
   1780       assert(RecCode == DECL_UPDATES && "Expected DECL_UPDATES record!");
   1781 
   1782       unsigned Idx = 0;
   1783       ASTDeclReader Reader(*this, *F, Cursor, ID, Record, Idx);
   1784       Reader.UpdateDecl(D, *F, Record);
   1785     }
   1786   }
   1787 }
   1788 
   1789 namespace {
   1790   /// \brief Given an ObjC interface, goes through the modules and links to the
   1791   /// interface all the categories for it.
   1792   class ObjCChainedCategoriesVisitor {
   1793     ASTReader &Reader;
   1794     serialization::GlobalDeclID InterfaceID;
   1795     ObjCInterfaceDecl *Interface;
   1796     ObjCCategoryDecl *GlobHeadCat, *GlobTailCat;
   1797     llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
   1798 
   1799   public:
   1800     ObjCChainedCategoriesVisitor(ASTReader &Reader,
   1801                                  serialization::GlobalDeclID InterfaceID,
   1802                                  ObjCInterfaceDecl *Interface)
   1803       : Reader(Reader), InterfaceID(InterfaceID), Interface(Interface),
   1804         GlobHeadCat(0), GlobTailCat(0) { }
   1805 
   1806     static bool visit(Module &M, void *UserData) {
   1807       return static_cast<ObjCChainedCategoriesVisitor *>(UserData)->visit(M);
   1808     }
   1809 
   1810     bool visit(Module &M) {
   1811       if (Reader.isDeclIDFromModule(InterfaceID, M))
   1812         return true; // We reached the module where the interface originated
   1813                     // from. Stop traversing the imported modules.
   1814 
   1815       Module::ChainedObjCCategoriesMap::iterator
   1816         I = M.ChainedObjCCategories.find(InterfaceID);
   1817       if (I == M.ChainedObjCCategories.end())
   1818         return false;
   1819 
   1820       ObjCCategoryDecl *
   1821         HeadCat = Reader.GetLocalDeclAs<ObjCCategoryDecl>(M, I->second.first);
   1822       ObjCCategoryDecl *
   1823         TailCat = Reader.GetLocalDeclAs<ObjCCategoryDecl>(M, I->second.second);
   1824 
   1825       addCategories(HeadCat, TailCat);
   1826       return false;
   1827     }
   1828 
   1829     void addCategories(ObjCCategoryDecl *HeadCat,
   1830                        ObjCCategoryDecl *TailCat = 0) {
   1831       if (!HeadCat) {
   1832         assert(!TailCat);
   1833         return;
   1834       }
   1835 
   1836       if (!TailCat) {
   1837         TailCat = HeadCat;
   1838         while (TailCat->getNextClassCategory())
   1839           TailCat = TailCat->getNextClassCategory();
   1840       }
   1841 
   1842       if (!GlobHeadCat) {
   1843         GlobHeadCat = HeadCat;
   1844         GlobTailCat = TailCat;
   1845       } else {
   1846         ASTDeclReader::setNextObjCCategory(GlobTailCat, HeadCat);
   1847         GlobTailCat = TailCat;
   1848       }
   1849 
   1850       llvm::DenseSet<DeclarationName> Checked;
   1851       for (ObjCCategoryDecl *Cat = HeadCat,
   1852                             *CatEnd = TailCat->getNextClassCategory();
   1853              Cat != CatEnd; Cat = Cat->getNextClassCategory()) {
   1854         if (Checked.count(Cat->getDeclName()))
   1855           continue;
   1856         Checked.insert(Cat->getDeclName());
   1857         checkForDuplicate(Cat);
   1858       }
   1859     }
   1860 
   1861     /// \brief Warns for duplicate categories that come from different modules.
   1862     void checkForDuplicate(ObjCCategoryDecl *Cat) {
   1863       DeclarationName Name = Cat->getDeclName();
   1864       // Find the top category with the same name. We do not want to warn for
   1865       // duplicates along the established chain because there were already
   1866       // warnings for them when the module was created. We only want to warn for
   1867       // duplicates between non-dependent modules:
   1868       //
   1869       //   MT     //
   1870       //  /  \    //
   1871       // ML  MR   //
   1872       //
   1873       // We want to warn for duplicates between ML and MR,not between ML and MT.
   1874       //
   1875       // FIXME: We should not warn for duplicates in diamond:
   1876       //
   1877       //   MT     //
   1878       //  /  \    //
   1879       // ML  MR   //
   1880       //  \  /    //
   1881       //   MB     //
   1882       //
   1883       // If there are duplicates in ML/MR, there will be warning when creating
   1884       // MB *and* when importing MB. We should not warn when importing.
   1885       for (ObjCCategoryDecl *Next = Cat->getNextClassCategory(); Next;
   1886              Next = Next->getNextClassCategory()) {
   1887         if (Next->getDeclName() == Name)
   1888           Cat = Next;
   1889       }
   1890 
   1891       ObjCCategoryDecl *&PrevCat = NameCategoryMap[Name];
   1892       if (!PrevCat)
   1893         PrevCat = Cat;
   1894 
   1895       if (PrevCat != Cat) {
   1896         Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
   1897           << Interface->getDeclName() << Name;
   1898         Reader.Diag(PrevCat->getLocation(), diag::note_previous_definition);
   1899       }
   1900     }
   1901 
   1902     ObjCCategoryDecl *getHeadCategory() const { return GlobHeadCat; }
   1903   };
   1904 }
   1905 
   1906 void ASTReader::loadObjCChainedCategories(serialization::GlobalDeclID ID,
   1907                                           ObjCInterfaceDecl *D) {
   1908   ObjCChainedCategoriesVisitor Visitor(*this, ID, D);
   1909   ModuleMgr.visit(ObjCChainedCategoriesVisitor::visit, &Visitor);
   1910   // Also add the categories that the interface already links to.
   1911   Visitor.addCategories(D->getCategoryList());
   1912   D->setCategoryList(Visitor.getHeadCategory());
   1913 }
   1914 
   1915 void ASTDeclReader::UpdateDecl(Decl *D, Module &Module,
   1916                                const RecordData &Record) {
   1917   unsigned Idx = 0;
   1918   while (Idx < Record.size()) {
   1919     switch ((DeclUpdateKind)Record[Idx++]) {
   1920     case UPD_CXX_SET_DEFINITIONDATA: {
   1921       CXXRecordDecl *RD = cast<CXXRecordDecl>(D);
   1922       CXXRecordDecl *DefinitionDecl
   1923         = Reader.ReadDeclAs<CXXRecordDecl>(Module, Record, Idx);
   1924       assert(!RD->DefinitionData && "DefinitionData is already set!");
   1925       InitializeCXXDefinitionData(RD, DefinitionDecl, Record, Idx);
   1926       break;
   1927     }
   1928 
   1929     case UPD_CXX_ADDED_IMPLICIT_MEMBER:
   1930       cast<CXXRecordDecl>(D)->addedMember(Reader.ReadDecl(Module, Record, Idx));
   1931       break;
   1932 
   1933     case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
   1934       // It will be added to the template's specializations set when loaded.
   1935       (void)Reader.ReadDecl(Module, Record, Idx);
   1936       break;
   1937 
   1938     case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
   1939       NamespaceDecl *Anon
   1940         = Reader.ReadDeclAs<NamespaceDecl>(Module, Record, Idx);
   1941       // Guard against these being loaded out of original order. Don't use
   1942       // getNextNamespace(), since it tries to access the context and can't in
   1943       // the middle of deserialization.
   1944       if (!Anon->NextNamespace) {
   1945         if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(D))
   1946           TU->setAnonymousNamespace(Anon);
   1947         else
   1948           cast<NamespaceDecl>(D)->OrigOrAnonNamespace.setPointer(Anon);
   1949       }
   1950       break;
   1951     }
   1952 
   1953     case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
   1954       cast<VarDecl>(D)->getMemberSpecializationInfo()->setPointOfInstantiation(
   1955           Reader.ReadSourceLocation(Module, Record, Idx));
   1956       break;
   1957     }
   1958   }
   1959 }
   1960