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