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