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