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