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