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