]> CyberLeo.Net >> Repos - FreeBSD/releng/10.0.git/blob - contrib/llvm/tools/clang/lib/Serialization/ASTReaderDecl.cpp
- Copy stable/10 (r259064) to releng/10.0 as part of the
[FreeBSD/releng/10.0.git] / contrib / llvm / tools / clang / lib / Serialization / ASTReaderDecl.cpp
1 //===--- ASTReaderDecl.cpp - Decl Deserialization ---------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the ASTReader::ReadDeclRecord method, which is the
11 // entrypoint for loading a decl.
12 //
13 //===----------------------------------------------------------------------===//
14
15 #include "clang/Serialization/ASTReader.h"
16 #include "ASTCommon.h"
17 #include "ASTReaderInternals.h"
18 #include "clang/AST/ASTConsumer.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclGroup.h"
22 #include "clang/AST/DeclTemplate.h"
23 #include "clang/AST/DeclVisitor.h"
24 #include "clang/AST/Expr.h"
25 #include "clang/Sema/IdentifierResolver.h"
26 #include "clang/Sema/Sema.h"
27 #include "clang/Sema/SemaDiagnostic.h"
28 #include "llvm/Support/SaveAndRestore.h"
29 using namespace clang;
30 using namespace clang::serialization;
31
32 //===----------------------------------------------------------------------===//
33 // Declaration deserialization
34 //===----------------------------------------------------------------------===//
35
36 namespace clang {
37   class ASTDeclReader : public DeclVisitor<ASTDeclReader, void> {
38     ASTReader &Reader;
39     ModuleFile &F;
40     const DeclID ThisDeclID;
41     const unsigned RawLocation;
42     typedef ASTReader::RecordData RecordData;
43     const RecordData &Record;
44     unsigned &Idx;
45     TypeID TypeIDForTypeDecl;
46     
47     bool HasPendingBody;
48
49     uint64_t GetCurrentCursorOffset();
50     
51     SourceLocation ReadSourceLocation(const RecordData &R, unsigned &I) {
52       return Reader.ReadSourceLocation(F, R, I);
53     }
54     
55     SourceRange ReadSourceRange(const RecordData &R, unsigned &I) {
56       return Reader.ReadSourceRange(F, R, I);
57     }
58     
59     TypeSourceInfo *GetTypeSourceInfo(const RecordData &R, unsigned &I) {
60       return Reader.GetTypeSourceInfo(F, R, I);
61     }
62     
63     serialization::DeclID ReadDeclID(const RecordData &R, unsigned &I) {
64       return Reader.ReadDeclID(F, R, I);
65     }
66     
67     Decl *ReadDecl(const RecordData &R, unsigned &I) {
68       return Reader.ReadDecl(F, R, I);
69     }
70
71     template<typename T>
72     T *ReadDeclAs(const RecordData &R, unsigned &I) {
73       return Reader.ReadDeclAs<T>(F, R, I);
74     }
75
76     void ReadQualifierInfo(QualifierInfo &Info,
77                            const RecordData &R, unsigned &I) {
78       Reader.ReadQualifierInfo(F, Info, R, I);
79     }
80     
81     void ReadDeclarationNameLoc(DeclarationNameLoc &DNLoc, DeclarationName Name,
82                                 const RecordData &R, unsigned &I) {
83       Reader.ReadDeclarationNameLoc(F, DNLoc, Name, R, I);
84     }
85     
86     void ReadDeclarationNameInfo(DeclarationNameInfo &NameInfo,
87                                 const RecordData &R, unsigned &I) {
88       Reader.ReadDeclarationNameInfo(F, NameInfo, R, I);
89     }
90
91     serialization::SubmoduleID readSubmoduleID(const RecordData &R, 
92                                                unsigned &I) {
93       if (I >= R.size())
94         return 0;
95       
96       return Reader.getGlobalSubmoduleID(F, R[I++]);
97     }
98     
99     Module *readModule(const RecordData &R, unsigned &I) {
100       return Reader.getSubmodule(readSubmoduleID(R, I));
101     }
102     
103     void ReadCXXDefinitionData(struct CXXRecordDecl::DefinitionData &Data,
104                                const RecordData &R, unsigned &I);
105
106     /// \brief RAII class used to capture the first ID within a redeclaration
107     /// chain and to introduce it into the list of pending redeclaration chains
108     /// on destruction.
109     ///
110     /// The caller can choose not to introduce this ID into the redeclaration
111     /// chain by calling \c suppress().
112     class RedeclarableResult {
113       ASTReader &Reader;
114       GlobalDeclID FirstID;
115       mutable bool Owning;
116       Decl::Kind DeclKind;
117       
118       void operator=(RedeclarableResult &) LLVM_DELETED_FUNCTION;
119       
120     public:
121       RedeclarableResult(ASTReader &Reader, GlobalDeclID FirstID,
122                          Decl::Kind DeclKind)
123         : Reader(Reader), FirstID(FirstID), Owning(true), DeclKind(DeclKind) { }
124
125       RedeclarableResult(const RedeclarableResult &Other)
126         : Reader(Other.Reader), FirstID(Other.FirstID), Owning(Other.Owning) ,
127           DeclKind(Other.DeclKind)
128       { 
129         Other.Owning = false;
130       }
131
132       ~RedeclarableResult() {
133         if (FirstID && Owning && isRedeclarableDeclKind(DeclKind) &&
134             Reader.PendingDeclChainsKnown.insert(FirstID))
135           Reader.PendingDeclChains.push_back(FirstID);
136       }
137       
138       /// \brief Retrieve the first ID.
139       GlobalDeclID getFirstID() const { return FirstID; }
140       
141       /// \brief Do not introduce this declaration ID into the set of pending
142       /// declaration chains.
143       void suppress() {
144         Owning = false;
145       }
146     };
147
148     /// \brief Class used to capture the result of searching for an existing
149     /// declaration of a specific kind and name, along with the ability
150     /// to update the place where this result was found (the declaration
151     /// chain hanging off an identifier or the DeclContext we searched in)
152     /// if requested.
153     class FindExistingResult {
154       ASTReader &Reader;
155       NamedDecl *New;
156       NamedDecl *Existing;
157       mutable bool AddResult;
158       
159       void operator=(FindExistingResult&) LLVM_DELETED_FUNCTION;
160       
161     public:
162       FindExistingResult(ASTReader &Reader)
163         : Reader(Reader), New(0), Existing(0), AddResult(false) { }
164       
165       FindExistingResult(ASTReader &Reader, NamedDecl *New, NamedDecl *Existing)
166         : Reader(Reader), New(New), Existing(Existing), AddResult(true) { }
167       
168       FindExistingResult(const FindExistingResult &Other)
169         : Reader(Other.Reader), New(Other.New), Existing(Other.Existing), 
170           AddResult(Other.AddResult)
171       {
172         Other.AddResult = false;
173       }
174       
175       ~FindExistingResult();
176       
177       /// \brief Suppress the addition of this result into the known set of
178       /// names.
179       void suppress() { AddResult = false; }
180       
181       operator NamedDecl*() const { return Existing; }
182       
183       template<typename T>
184       operator T*() const { return dyn_cast_or_null<T>(Existing); }
185     };
186     
187     FindExistingResult findExisting(NamedDecl *D);
188     
189   public:
190     ASTDeclReader(ASTReader &Reader, ModuleFile &F,
191                   DeclID thisDeclID,
192                   unsigned RawLocation,
193                   const RecordData &Record, unsigned &Idx)
194       : Reader(Reader), F(F), ThisDeclID(thisDeclID),
195         RawLocation(RawLocation), Record(Record), Idx(Idx),
196         TypeIDForTypeDecl(0), HasPendingBody(false) { }
197
198     static void attachPreviousDecl(Decl *D, Decl *previous);
199     static void attachLatestDecl(Decl *D, Decl *latest);
200
201     /// \brief Determine whether this declaration has a pending body.
202     bool hasPendingBody() const { return HasPendingBody; }
203
204     void Visit(Decl *D);
205
206     void UpdateDecl(Decl *D, ModuleFile &ModuleFile,
207                     const RecordData &Record);
208
209     static void setNextObjCCategory(ObjCCategoryDecl *Cat,
210                                     ObjCCategoryDecl *Next) {
211       Cat->NextClassCategory = Next;
212     }
213
214     void VisitDecl(Decl *D);
215     void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
216     void VisitNamedDecl(NamedDecl *ND);
217     void VisitLabelDecl(LabelDecl *LD);
218     void VisitNamespaceDecl(NamespaceDecl *D);
219     void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
220     void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
221     void VisitTypeDecl(TypeDecl *TD);
222     void VisitTypedefNameDecl(TypedefNameDecl *TD);
223     void VisitTypedefDecl(TypedefDecl *TD);
224     void VisitTypeAliasDecl(TypeAliasDecl *TD);
225     void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
226     void VisitTagDecl(TagDecl *TD);
227     void VisitEnumDecl(EnumDecl *ED);
228     void VisitRecordDecl(RecordDecl *RD);
229     void VisitCXXRecordDecl(CXXRecordDecl *D);
230     void VisitClassTemplateSpecializationDecl(
231                                             ClassTemplateSpecializationDecl *D);
232     void VisitClassTemplatePartialSpecializationDecl(
233                                      ClassTemplatePartialSpecializationDecl *D);
234     void VisitClassScopeFunctionSpecializationDecl(
235                                        ClassScopeFunctionSpecializationDecl *D);
236     void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
237     void VisitValueDecl(ValueDecl *VD);
238     void VisitEnumConstantDecl(EnumConstantDecl *ECD);
239     void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
240     void VisitDeclaratorDecl(DeclaratorDecl *DD);
241     void VisitFunctionDecl(FunctionDecl *FD);
242     void VisitCXXMethodDecl(CXXMethodDecl *D);
243     void VisitCXXConstructorDecl(CXXConstructorDecl *D);
244     void VisitCXXDestructorDecl(CXXDestructorDecl *D);
245     void VisitCXXConversionDecl(CXXConversionDecl *D);
246     void VisitFieldDecl(FieldDecl *FD);
247     void VisitMSPropertyDecl(MSPropertyDecl *FD);
248     void VisitIndirectFieldDecl(IndirectFieldDecl *FD);
249     void VisitVarDecl(VarDecl *VD);
250     void VisitImplicitParamDecl(ImplicitParamDecl *PD);
251     void VisitParmVarDecl(ParmVarDecl *PD);
252     void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
253     void VisitTemplateDecl(TemplateDecl *D);
254     RedeclarableResult VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);
255     void VisitClassTemplateDecl(ClassTemplateDecl *D);
256     void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
257     void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
258     void VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
259     void VisitUsingDecl(UsingDecl *D);
260     void VisitUsingShadowDecl(UsingShadowDecl *D);
261     void VisitLinkageSpecDecl(LinkageSpecDecl *D);
262     void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);
263     void VisitImportDecl(ImportDecl *D);
264     void VisitAccessSpecDecl(AccessSpecDecl *D);
265     void VisitFriendDecl(FriendDecl *D);
266     void VisitFriendTemplateDecl(FriendTemplateDecl *D);
267     void VisitStaticAssertDecl(StaticAssertDecl *D);
268     void VisitBlockDecl(BlockDecl *BD);
269     void VisitCapturedDecl(CapturedDecl *CD);
270     void VisitEmptyDecl(EmptyDecl *D);
271
272     std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
273     
274     template<typename T> 
275     RedeclarableResult VisitRedeclarable(Redeclarable<T> *D);
276
277     template<typename T>
278     void mergeRedeclarable(Redeclarable<T> *D, RedeclarableResult &Redecl);
279     
280     // FIXME: Reorder according to DeclNodes.td?
281     void VisitObjCMethodDecl(ObjCMethodDecl *D);
282     void VisitObjCContainerDecl(ObjCContainerDecl *D);
283     void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
284     void VisitObjCIvarDecl(ObjCIvarDecl *D);
285     void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
286     void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
287     void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
288     void VisitObjCImplDecl(ObjCImplDecl *D);
289     void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
290     void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
291     void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
292     void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
293     void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
294     void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D);
295   };
296 }
297
298 uint64_t ASTDeclReader::GetCurrentCursorOffset() {
299   return F.DeclsCursor.GetCurrentBitNo() + F.GlobalBitOffset;
300 }
301
302 void ASTDeclReader::Visit(Decl *D) {
303   DeclVisitor<ASTDeclReader, void>::Visit(D);
304
305   if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
306     if (DD->DeclInfo) {
307       DeclaratorDecl::ExtInfo *Info =
308           DD->DeclInfo.get<DeclaratorDecl::ExtInfo *>();
309       Info->TInfo =
310           GetTypeSourceInfo(Record, Idx);
311     }
312     else {
313       DD->DeclInfo = GetTypeSourceInfo(Record, Idx);
314     }
315   }
316
317   if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
318     // if we have a fully initialized TypeDecl, we can safely read its type now.
319     TD->setTypeForDecl(Reader.GetType(TypeIDForTypeDecl).getTypePtrOrNull());
320   } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
321     // if we have a fully initialized TypeDecl, we can safely read its type now.
322     ID->TypeForDecl = Reader.GetType(TypeIDForTypeDecl).getTypePtrOrNull();
323   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
324     // FunctionDecl's body was written last after all other Stmts/Exprs.
325     // We only read it if FD doesn't already have a body (e.g., from another
326     // module).
327     // FIXME: Also consider = default and = delete.
328     // FIXME: Can we diagnose ODR violations somehow?
329     if (Record[Idx++]) {
330       Reader.PendingBodies[FD] = GetCurrentCursorOffset();
331       HasPendingBody = true;
332     }
333   }
334 }
335
336 void ASTDeclReader::VisitDecl(Decl *D) {
337   if (D->isTemplateParameter()) {
338     // We don't want to deserialize the DeclContext of a template
339     // parameter immediately, because the template parameter might be
340     // used in the formulation of its DeclContext. Use the translation
341     // unit DeclContext as a placeholder.
342     GlobalDeclID SemaDCIDForTemplateParmDecl = ReadDeclID(Record, Idx);
343     GlobalDeclID LexicalDCIDForTemplateParmDecl = ReadDeclID(Record, Idx);
344     Reader.addPendingDeclContextInfo(D,
345                                      SemaDCIDForTemplateParmDecl,
346                                      LexicalDCIDForTemplateParmDecl);
347     D->setDeclContext(Reader.getContext().getTranslationUnitDecl()); 
348   } else {
349     DeclContext *SemaDC = ReadDeclAs<DeclContext>(Record, Idx);
350     DeclContext *LexicalDC = ReadDeclAs<DeclContext>(Record, Idx);
351     // Avoid calling setLexicalDeclContext() directly because it uses
352     // Decl::getASTContext() internally which is unsafe during derialization.
353     D->setDeclContextsImpl(SemaDC, LexicalDC, Reader.getContext());
354   }
355   D->setLocation(Reader.ReadSourceLocation(F, RawLocation));
356   D->setInvalidDecl(Record[Idx++]);
357   if (Record[Idx++]) { // hasAttrs
358     AttrVec Attrs;
359     Reader.ReadAttributes(F, Attrs, Record, Idx);
360     // Avoid calling setAttrs() directly because it uses Decl::getASTContext()
361     // internally which is unsafe during derialization.
362     D->setAttrsImpl(Attrs, Reader.getContext());
363   }
364   D->setImplicit(Record[Idx++]);
365   D->setUsed(Record[Idx++]);
366   D->setReferenced(Record[Idx++]);
367   D->setTopLevelDeclInObjCContainer(Record[Idx++]);
368   D->setAccess((AccessSpecifier)Record[Idx++]);
369   D->FromASTFile = true;
370   D->setModulePrivate(Record[Idx++]);
371   D->Hidden = D->isModulePrivate();
372   
373   // Determine whether this declaration is part of a (sub)module. If so, it
374   // may not yet be visible.
375   if (unsigned SubmoduleID = readSubmoduleID(Record, Idx)) {
376     // Store the owning submodule ID in the declaration.
377     D->setOwningModuleID(SubmoduleID);
378     
379     // Module-private declarations are never visible, so there is no work to do.
380     if (!D->isModulePrivate()) {
381       if (Module *Owner = Reader.getSubmodule(SubmoduleID)) {
382         if (Owner->NameVisibility != Module::AllVisible) {
383           // The owning module is not visible. Mark this declaration as hidden.
384           D->Hidden = true;
385           
386           // Note that this declaration was hidden because its owning module is 
387           // not yet visible.
388           Reader.HiddenNamesMap[Owner].push_back(D);
389         }
390       }
391     }
392   }
393 }
394
395 void ASTDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
396   llvm_unreachable("Translation units are not serialized");
397 }
398
399 void ASTDeclReader::VisitNamedDecl(NamedDecl *ND) {
400   VisitDecl(ND);
401   ND->setDeclName(Reader.ReadDeclarationName(F, Record, Idx));
402 }
403
404 void ASTDeclReader::VisitTypeDecl(TypeDecl *TD) {
405   VisitNamedDecl(TD);
406   TD->setLocStart(ReadSourceLocation(Record, Idx));
407   // Delay type reading until after we have fully initialized the decl.
408   TypeIDForTypeDecl = Reader.getGlobalTypeID(F, Record[Idx++]);
409 }
410
411 void ASTDeclReader::VisitTypedefNameDecl(TypedefNameDecl *TD) {
412   RedeclarableResult Redecl = VisitRedeclarable(TD);
413   VisitTypeDecl(TD);
414   
415   TD->setTypeSourceInfo(GetTypeSourceInfo(Record, Idx));
416   mergeRedeclarable(TD, Redecl);
417 }
418
419 void ASTDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
420   VisitTypedefNameDecl(TD);
421 }
422
423 void ASTDeclReader::VisitTypeAliasDecl(TypeAliasDecl *TD) {
424   VisitTypedefNameDecl(TD);
425 }
426
427 void ASTDeclReader::VisitTagDecl(TagDecl *TD) {
428   RedeclarableResult Redecl = VisitRedeclarable(TD);
429   VisitTypeDecl(TD);
430   
431   TD->IdentifierNamespace = Record[Idx++];
432   TD->setTagKind((TagDecl::TagKind)Record[Idx++]);
433   TD->setCompleteDefinition(Record[Idx++]);
434   TD->setEmbeddedInDeclarator(Record[Idx++]);
435   TD->setFreeStanding(Record[Idx++]);
436   TD->setRBraceLoc(ReadSourceLocation(Record, Idx));
437   
438   if (Record[Idx++]) { // hasExtInfo
439     TagDecl::ExtInfo *Info = new (Reader.getContext()) TagDecl::ExtInfo();
440     ReadQualifierInfo(*Info, Record, Idx);
441     TD->TypedefNameDeclOrQualifier = Info;
442   } else
443     TD->setTypedefNameForAnonDecl(ReadDeclAs<TypedefNameDecl>(Record, Idx));
444
445   mergeRedeclarable(TD, Redecl);  
446 }
447
448 void ASTDeclReader::VisitEnumDecl(EnumDecl *ED) {
449   VisitTagDecl(ED);
450   if (TypeSourceInfo *TI = Reader.GetTypeSourceInfo(F, Record, Idx))
451     ED->setIntegerTypeSourceInfo(TI);
452   else
453     ED->setIntegerType(Reader.readType(F, Record, Idx));
454   ED->setPromotionType(Reader.readType(F, Record, Idx));
455   ED->setNumPositiveBits(Record[Idx++]);
456   ED->setNumNegativeBits(Record[Idx++]);
457   ED->IsScoped = Record[Idx++];
458   ED->IsScopedUsingClassTag = Record[Idx++];
459   ED->IsFixed = Record[Idx++];
460
461   if (EnumDecl *InstED = ReadDeclAs<EnumDecl>(Record, Idx)) {
462     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
463     SourceLocation POI = ReadSourceLocation(Record, Idx);
464     ED->setInstantiationOfMemberEnum(Reader.getContext(), InstED, TSK);
465     ED->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
466   }
467 }
468
469 void ASTDeclReader::VisitRecordDecl(RecordDecl *RD) {
470   VisitTagDecl(RD);
471   RD->setHasFlexibleArrayMember(Record[Idx++]);
472   RD->setAnonymousStructOrUnion(Record[Idx++]);
473   RD->setHasObjectMember(Record[Idx++]);
474   RD->setHasVolatileMember(Record[Idx++]);
475 }
476
477 void ASTDeclReader::VisitValueDecl(ValueDecl *VD) {
478   VisitNamedDecl(VD);
479   VD->setType(Reader.readType(F, Record, Idx));
480 }
481
482 void ASTDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
483   VisitValueDecl(ECD);
484   if (Record[Idx++])
485     ECD->setInitExpr(Reader.ReadExpr(F));
486   ECD->setInitVal(Reader.ReadAPSInt(Record, Idx));
487 }
488
489 void ASTDeclReader::VisitDeclaratorDecl(DeclaratorDecl *DD) {
490   VisitValueDecl(DD);
491   DD->setInnerLocStart(ReadSourceLocation(Record, Idx));
492   if (Record[Idx++]) { // hasExtInfo
493     DeclaratorDecl::ExtInfo *Info
494         = new (Reader.getContext()) DeclaratorDecl::ExtInfo();
495     ReadQualifierInfo(*Info, Record, Idx);
496     DD->DeclInfo = Info;
497   }
498 }
499
500 void ASTDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
501   RedeclarableResult Redecl = VisitRedeclarable(FD);
502   VisitDeclaratorDecl(FD);
503
504   ReadDeclarationNameLoc(FD->DNLoc, FD->getDeclName(), Record, Idx);
505   FD->IdentifierNamespace = Record[Idx++];
506   
507   // FunctionDecl's body is handled last at ASTDeclReader::Visit,
508   // after everything else is read.
509
510   FD->SClass = (StorageClass)Record[Idx++];
511   FD->IsInline = Record[Idx++];
512   FD->IsInlineSpecified = Record[Idx++];
513   FD->IsVirtualAsWritten = Record[Idx++];
514   FD->IsPure = Record[Idx++];
515   FD->HasInheritedPrototype = Record[Idx++];
516   FD->HasWrittenPrototype = Record[Idx++];
517   FD->IsDeleted = Record[Idx++];
518   FD->IsTrivial = Record[Idx++];
519   FD->IsDefaulted = Record[Idx++];
520   FD->IsExplicitlyDefaulted = Record[Idx++];
521   FD->HasImplicitReturnZero = Record[Idx++];
522   FD->IsConstexpr = Record[Idx++];
523   FD->HasSkippedBody = Record[Idx++];
524   FD->HasCachedLinkage = true;
525   FD->CachedLinkage = Record[Idx++];
526   FD->EndRangeLoc = ReadSourceLocation(Record, Idx);
527
528   switch ((FunctionDecl::TemplatedKind)Record[Idx++]) {
529   case FunctionDecl::TK_NonTemplate:
530     mergeRedeclarable(FD, Redecl);      
531     break;
532   case FunctionDecl::TK_FunctionTemplate:
533     FD->setDescribedFunctionTemplate(ReadDeclAs<FunctionTemplateDecl>(Record, 
534                                                                       Idx));
535     break;
536   case FunctionDecl::TK_MemberSpecialization: {
537     FunctionDecl *InstFD = ReadDeclAs<FunctionDecl>(Record, Idx);
538     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
539     SourceLocation POI = ReadSourceLocation(Record, Idx);
540     FD->setInstantiationOfMemberFunction(Reader.getContext(), InstFD, TSK);
541     FD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
542     break;
543   }
544   case FunctionDecl::TK_FunctionTemplateSpecialization: {
545     FunctionTemplateDecl *Template = ReadDeclAs<FunctionTemplateDecl>(Record, 
546                                                                       Idx);
547     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
548     
549     // Template arguments.
550     SmallVector<TemplateArgument, 8> TemplArgs;
551     Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
552     
553     // Template args as written.
554     SmallVector<TemplateArgumentLoc, 8> TemplArgLocs;
555     SourceLocation LAngleLoc, RAngleLoc;
556     bool HasTemplateArgumentsAsWritten = Record[Idx++];
557     if (HasTemplateArgumentsAsWritten) {
558       unsigned NumTemplateArgLocs = Record[Idx++];
559       TemplArgLocs.reserve(NumTemplateArgLocs);
560       for (unsigned i=0; i != NumTemplateArgLocs; ++i)
561         TemplArgLocs.push_back(
562             Reader.ReadTemplateArgumentLoc(F, Record, Idx));
563   
564       LAngleLoc = ReadSourceLocation(Record, Idx);
565       RAngleLoc = ReadSourceLocation(Record, Idx);
566     }
567     
568     SourceLocation POI = ReadSourceLocation(Record, Idx);
569
570     ASTContext &C = Reader.getContext();
571     TemplateArgumentList *TemplArgList
572       = TemplateArgumentList::CreateCopy(C, TemplArgs.data(), TemplArgs.size());
573     TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
574     for (unsigned i=0, e = TemplArgLocs.size(); i != e; ++i)
575       TemplArgsInfo.addArgument(TemplArgLocs[i]);
576     FunctionTemplateSpecializationInfo *FTInfo
577         = FunctionTemplateSpecializationInfo::Create(C, FD, Template, TSK,
578                                                      TemplArgList,
579                              HasTemplateArgumentsAsWritten ? &TemplArgsInfo : 0,
580                                                      POI);
581     FD->TemplateOrSpecialization = FTInfo;
582
583     if (FD->isCanonicalDecl()) { // if canonical add to template's set.
584       // The template that contains the specializations set. It's not safe to
585       // use getCanonicalDecl on Template since it may still be initializing.
586       FunctionTemplateDecl *CanonTemplate
587         = ReadDeclAs<FunctionTemplateDecl>(Record, Idx);
588       // Get the InsertPos by FindNodeOrInsertPos() instead of calling
589       // InsertNode(FTInfo) directly to avoid the getASTContext() call in
590       // FunctionTemplateSpecializationInfo's Profile().
591       // We avoid getASTContext because a decl in the parent hierarchy may
592       // be initializing.
593       llvm::FoldingSetNodeID ID;
594       FunctionTemplateSpecializationInfo::Profile(ID, TemplArgs.data(),
595                                                   TemplArgs.size(), C);
596       void *InsertPos = 0;
597       CanonTemplate->getSpecializations().FindNodeOrInsertPos(ID, InsertPos);
598       if (InsertPos)
599         CanonTemplate->getSpecializations().InsertNode(FTInfo, InsertPos);
600       else
601         assert(0 && "Another specialization already inserted!");
602     }
603     break;
604   }
605   case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
606     // Templates.
607     UnresolvedSet<8> TemplDecls;
608     unsigned NumTemplates = Record[Idx++];
609     while (NumTemplates--)
610       TemplDecls.addDecl(ReadDeclAs<NamedDecl>(Record, Idx));
611     
612     // Templates args.
613     TemplateArgumentListInfo TemplArgs;
614     unsigned NumArgs = Record[Idx++];
615     while (NumArgs--)
616       TemplArgs.addArgument(Reader.ReadTemplateArgumentLoc(F, Record, Idx));
617     TemplArgs.setLAngleLoc(ReadSourceLocation(Record, Idx));
618     TemplArgs.setRAngleLoc(ReadSourceLocation(Record, Idx));
619     
620     FD->setDependentTemplateSpecialization(Reader.getContext(),
621                                            TemplDecls, TemplArgs);
622     break;
623   }
624   }
625
626   // Read in the parameters.
627   unsigned NumParams = Record[Idx++];
628   SmallVector<ParmVarDecl *, 16> Params;
629   Params.reserve(NumParams);
630   for (unsigned I = 0; I != NumParams; ++I)
631     Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
632   FD->setParams(Reader.getContext(), Params);
633 }
634
635 void ASTDeclReader::VisitObjCMethodDecl(ObjCMethodDecl *MD) {
636   VisitNamedDecl(MD);
637   if (Record[Idx++]) {
638     // Load the body on-demand. Most clients won't care, because method
639     // definitions rarely show up in headers.
640     Reader.PendingBodies[MD] = GetCurrentCursorOffset();
641     HasPendingBody = true;
642     MD->setSelfDecl(ReadDeclAs<ImplicitParamDecl>(Record, Idx));
643     MD->setCmdDecl(ReadDeclAs<ImplicitParamDecl>(Record, Idx));
644   }
645   MD->setInstanceMethod(Record[Idx++]);
646   MD->setVariadic(Record[Idx++]);
647   MD->setPropertyAccessor(Record[Idx++]);
648   MD->setDefined(Record[Idx++]);
649   MD->IsOverriding = Record[Idx++];
650   MD->HasSkippedBody = Record[Idx++];
651
652   MD->IsRedeclaration = Record[Idx++];
653   MD->HasRedeclaration = Record[Idx++];
654   if (MD->HasRedeclaration)
655     Reader.getContext().setObjCMethodRedeclaration(MD,
656                                        ReadDeclAs<ObjCMethodDecl>(Record, Idx));
657
658   MD->setDeclImplementation((ObjCMethodDecl::ImplementationControl)Record[Idx++]);
659   MD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record[Idx++]);
660   MD->SetRelatedResultType(Record[Idx++]);
661   MD->setResultType(Reader.readType(F, Record, Idx));
662   MD->setResultTypeSourceInfo(GetTypeSourceInfo(Record, Idx));
663   MD->DeclEndLoc = ReadSourceLocation(Record, Idx);
664   unsigned NumParams = Record[Idx++];
665   SmallVector<ParmVarDecl *, 16> Params;
666   Params.reserve(NumParams);
667   for (unsigned I = 0; I != NumParams; ++I)
668     Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
669
670   MD->SelLocsKind = Record[Idx++];
671   unsigned NumStoredSelLocs = Record[Idx++];
672   SmallVector<SourceLocation, 16> SelLocs;
673   SelLocs.reserve(NumStoredSelLocs);
674   for (unsigned i = 0; i != NumStoredSelLocs; ++i)
675     SelLocs.push_back(ReadSourceLocation(Record, Idx));
676
677   MD->setParamsAndSelLocs(Reader.getContext(), Params, SelLocs);
678 }
679
680 void ASTDeclReader::VisitObjCContainerDecl(ObjCContainerDecl *CD) {
681   VisitNamedDecl(CD);
682   CD->setAtStartLoc(ReadSourceLocation(Record, Idx));
683   CD->setAtEndRange(ReadSourceRange(Record, Idx));
684 }
685
686 void ASTDeclReader::VisitObjCInterfaceDecl(ObjCInterfaceDecl *ID) {
687   RedeclarableResult Redecl = VisitRedeclarable(ID);
688   VisitObjCContainerDecl(ID);
689   TypeIDForTypeDecl = Reader.getGlobalTypeID(F, Record[Idx++]);
690   mergeRedeclarable(ID, Redecl);
691   
692   if (Record[Idx++]) {
693     // Read the definition.
694     ID->allocateDefinitionData();
695     
696     // Set the definition data of the canonical declaration, so other
697     // redeclarations will see it.
698     ID->getCanonicalDecl()->Data = ID->Data;
699     
700     ObjCInterfaceDecl::DefinitionData &Data = ID->data();
701     
702     // Read the superclass.
703     Data.SuperClass = ReadDeclAs<ObjCInterfaceDecl>(Record, Idx);
704     Data.SuperClassLoc = ReadSourceLocation(Record, Idx);
705
706     Data.EndLoc = ReadSourceLocation(Record, Idx);
707     
708     // Read the directly referenced protocols and their SourceLocations.
709     unsigned NumProtocols = Record[Idx++];
710     SmallVector<ObjCProtocolDecl *, 16> Protocols;
711     Protocols.reserve(NumProtocols);
712     for (unsigned I = 0; I != NumProtocols; ++I)
713       Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
714     SmallVector<SourceLocation, 16> ProtoLocs;
715     ProtoLocs.reserve(NumProtocols);
716     for (unsigned I = 0; I != NumProtocols; ++I)
717       ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
718     ID->setProtocolList(Protocols.data(), NumProtocols, ProtoLocs.data(),
719                         Reader.getContext());
720   
721     // Read the transitive closure of protocols referenced by this class.
722     NumProtocols = Record[Idx++];
723     Protocols.clear();
724     Protocols.reserve(NumProtocols);
725     for (unsigned I = 0; I != NumProtocols; ++I)
726       Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
727     ID->data().AllReferencedProtocols.set(Protocols.data(), NumProtocols,
728                                           Reader.getContext());
729   
730     // We will rebuild this list lazily.
731     ID->setIvarList(0);
732     
733     // Note that we have deserialized a definition.
734     Reader.PendingDefinitions.insert(ID);
735     
736     // Note that we've loaded this Objective-C class.
737     Reader.ObjCClassesLoaded.push_back(ID);
738   } else {
739     ID->Data = ID->getCanonicalDecl()->Data;
740   }
741 }
742
743 void ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) {
744   VisitFieldDecl(IVD);
745   IVD->setAccessControl((ObjCIvarDecl::AccessControl)Record[Idx++]);
746   // This field will be built lazily.
747   IVD->setNextIvar(0);
748   bool synth = Record[Idx++];
749   IVD->setSynthesize(synth);
750 }
751
752 void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {
753   RedeclarableResult Redecl = VisitRedeclarable(PD);
754   VisitObjCContainerDecl(PD);
755   mergeRedeclarable(PD, Redecl);
756   
757   if (Record[Idx++]) {
758     // Read the definition.
759     PD->allocateDefinitionData();
760     
761     // Set the definition data of the canonical declaration, so other
762     // redeclarations will see it.
763     PD->getCanonicalDecl()->Data = PD->Data;
764
765     unsigned NumProtoRefs = Record[Idx++];
766     SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
767     ProtoRefs.reserve(NumProtoRefs);
768     for (unsigned I = 0; I != NumProtoRefs; ++I)
769       ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
770     SmallVector<SourceLocation, 16> ProtoLocs;
771     ProtoLocs.reserve(NumProtoRefs);
772     for (unsigned I = 0; I != NumProtoRefs; ++I)
773       ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
774     PD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
775                         Reader.getContext());
776     
777     // Note that we have deserialized a definition.
778     Reader.PendingDefinitions.insert(PD);
779   } else {
780     PD->Data = PD->getCanonicalDecl()->Data;
781   }
782 }
783
784 void ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {
785   VisitFieldDecl(FD);
786 }
787
788 void ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {
789   VisitObjCContainerDecl(CD);
790   CD->setCategoryNameLoc(ReadSourceLocation(Record, Idx));
791   CD->setIvarLBraceLoc(ReadSourceLocation(Record, Idx));
792   CD->setIvarRBraceLoc(ReadSourceLocation(Record, Idx));
793   
794   // Note that this category has been deserialized. We do this before
795   // deserializing the interface declaration, so that it will consider this
796   /// category.
797   Reader.CategoriesDeserialized.insert(CD);
798
799   CD->ClassInterface = ReadDeclAs<ObjCInterfaceDecl>(Record, Idx);
800   unsigned NumProtoRefs = Record[Idx++];
801   SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
802   ProtoRefs.reserve(NumProtoRefs);
803   for (unsigned I = 0; I != NumProtoRefs; ++I)
804     ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>(Record, Idx));
805   SmallVector<SourceLocation, 16> ProtoLocs;
806   ProtoLocs.reserve(NumProtoRefs);
807   for (unsigned I = 0; I != NumProtoRefs; ++I)
808     ProtoLocs.push_back(ReadSourceLocation(Record, Idx));
809   CD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
810                       Reader.getContext());
811 }
812
813 void ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
814   VisitNamedDecl(CAD);
815   CAD->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
816 }
817
818 void ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
819   VisitNamedDecl(D);
820   D->setAtLoc(ReadSourceLocation(Record, Idx));
821   D->setLParenLoc(ReadSourceLocation(Record, Idx));
822   D->setType(GetTypeSourceInfo(Record, Idx));
823   // FIXME: stable encoding
824   D->setPropertyAttributes(
825                       (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
826   D->setPropertyAttributesAsWritten(
827                       (ObjCPropertyDecl::PropertyAttributeKind)Record[Idx++]);
828   // FIXME: stable encoding
829   D->setPropertyImplementation(
830                             (ObjCPropertyDecl::PropertyControl)Record[Idx++]);
831   D->setGetterName(Reader.ReadDeclarationName(F,Record, Idx).getObjCSelector());
832   D->setSetterName(Reader.ReadDeclarationName(F,Record, Idx).getObjCSelector());
833   D->setGetterMethodDecl(ReadDeclAs<ObjCMethodDecl>(Record, Idx));
834   D->setSetterMethodDecl(ReadDeclAs<ObjCMethodDecl>(Record, Idx));
835   D->setPropertyIvarDecl(ReadDeclAs<ObjCIvarDecl>(Record, Idx));
836 }
837
838 void ASTDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) {
839   VisitObjCContainerDecl(D);
840   D->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
841 }
842
843 void ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
844   VisitObjCImplDecl(D);
845   D->setIdentifier(Reader.GetIdentifierInfo(F, Record, Idx));
846   D->CategoryNameLoc = ReadSourceLocation(Record, Idx);
847 }
848
849 void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
850   VisitObjCImplDecl(D);
851   D->setSuperClass(ReadDeclAs<ObjCInterfaceDecl>(Record, Idx));
852   D->SuperLoc = ReadSourceLocation(Record, Idx);
853   D->setIvarLBraceLoc(ReadSourceLocation(Record, Idx));
854   D->setIvarRBraceLoc(ReadSourceLocation(Record, Idx));
855   D->setHasNonZeroConstructors(Record[Idx++]);
856   D->setHasDestructors(Record[Idx++]);
857   llvm::tie(D->IvarInitializers, D->NumIvarInitializers)
858       = Reader.ReadCXXCtorInitializers(F, Record, Idx);
859 }
860
861
862 void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
863   VisitDecl(D);
864   D->setAtLoc(ReadSourceLocation(Record, Idx));
865   D->setPropertyDecl(ReadDeclAs<ObjCPropertyDecl>(Record, Idx));
866   D->PropertyIvarDecl = ReadDeclAs<ObjCIvarDecl>(Record, Idx);
867   D->IvarLoc = ReadSourceLocation(Record, Idx);
868   D->setGetterCXXConstructor(Reader.ReadExpr(F));
869   D->setSetterCXXAssignment(Reader.ReadExpr(F));
870 }
871
872 void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {
873   VisitDeclaratorDecl(FD);
874   FD->Mutable = Record[Idx++];
875   if (int BitWidthOrInitializer = Record[Idx++]) {
876     FD->InitializerOrBitWidth.setInt(BitWidthOrInitializer - 1);
877     FD->InitializerOrBitWidth.setPointer(Reader.ReadExpr(F));
878   }
879   if (!FD->getDeclName()) {
880     if (FieldDecl *Tmpl = ReadDeclAs<FieldDecl>(Record, Idx))
881       Reader.getContext().setInstantiatedFromUnnamedFieldDecl(FD, Tmpl);
882   }
883 }
884
885 void ASTDeclReader::VisitMSPropertyDecl(MSPropertyDecl *PD) {
886   VisitDeclaratorDecl(PD);
887   PD->GetterId = Reader.GetIdentifierInfo(F, Record, Idx);
888   PD->SetterId = Reader.GetIdentifierInfo(F, Record, Idx);
889 }
890
891 void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
892   VisitValueDecl(FD);
893
894   FD->ChainingSize = Record[Idx++];
895   assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2");
896   FD->Chaining = new (Reader.getContext())NamedDecl*[FD->ChainingSize];
897
898   for (unsigned I = 0; I != FD->ChainingSize; ++I)
899     FD->Chaining[I] = ReadDeclAs<NamedDecl>(Record, Idx);
900 }
901
902 void ASTDeclReader::VisitVarDecl(VarDecl *VD) {
903   RedeclarableResult Redecl = VisitRedeclarable(VD);
904   VisitDeclaratorDecl(VD);
905
906   VD->VarDeclBits.SClass = (StorageClass)Record[Idx++];
907   VD->VarDeclBits.TSCSpec = Record[Idx++];
908   VD->VarDeclBits.InitStyle = Record[Idx++];
909   VD->VarDeclBits.ExceptionVar = Record[Idx++];
910   VD->VarDeclBits.NRVOVariable = Record[Idx++];
911   VD->VarDeclBits.CXXForRangeDecl = Record[Idx++];
912   VD->VarDeclBits.ARCPseudoStrong = Record[Idx++];
913   VD->VarDeclBits.IsConstexpr = Record[Idx++];
914   VD->HasCachedLinkage = true;
915   VD->CachedLinkage = Record[Idx++];
916   
917   // Only true variables (not parameters or implicit parameters) can be merged.
918   if (VD->getKind() == Decl::Var)
919     mergeRedeclarable(VD, Redecl);
920   
921   if (uint64_t Val = Record[Idx++]) {
922     VD->setInit(Reader.ReadExpr(F));
923     if (Val > 1) {
924       EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
925       Eval->CheckedICE = true;
926       Eval->IsICE = Val == 3;
927     }
928   }
929
930   if (Record[Idx++]) { // HasMemberSpecializationInfo.
931     VarDecl *Tmpl = ReadDeclAs<VarDecl>(Record, Idx);
932     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
933     SourceLocation POI = ReadSourceLocation(Record, Idx);
934     Reader.getContext().setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);
935   }
936 }
937
938 void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
939   VisitVarDecl(PD);
940 }
941
942 void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
943   VisitVarDecl(PD);
944   unsigned isObjCMethodParam = Record[Idx++];
945   unsigned scopeDepth = Record[Idx++];
946   unsigned scopeIndex = Record[Idx++];
947   unsigned declQualifier = Record[Idx++];
948   if (isObjCMethodParam) {
949     assert(scopeDepth == 0);
950     PD->setObjCMethodScopeInfo(scopeIndex);
951     PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier;
952   } else {
953     PD->setScopeInfo(scopeDepth, scopeIndex);
954   }
955   PD->ParmVarDeclBits.IsKNRPromoted = Record[Idx++];
956   PD->ParmVarDeclBits.HasInheritedDefaultArg = Record[Idx++];
957   if (Record[Idx++]) // hasUninstantiatedDefaultArg.
958     PD->setUninstantiatedDefaultArg(Reader.ReadExpr(F));
959 }
960
961 void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
962   VisitDecl(AD);
963   AD->setAsmString(cast<StringLiteral>(Reader.ReadExpr(F)));
964   AD->setRParenLoc(ReadSourceLocation(Record, Idx));
965 }
966
967 void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
968   VisitDecl(BD);
969   BD->setBody(cast_or_null<CompoundStmt>(Reader.ReadStmt(F)));
970   BD->setSignatureAsWritten(GetTypeSourceInfo(Record, Idx));
971   unsigned NumParams = Record[Idx++];
972   SmallVector<ParmVarDecl *, 16> Params;
973   Params.reserve(NumParams);
974   for (unsigned I = 0; I != NumParams; ++I)
975     Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
976   BD->setParams(Params);
977
978   BD->setIsVariadic(Record[Idx++]);
979   BD->setBlockMissingReturnType(Record[Idx++]);
980   BD->setIsConversionFromLambda(Record[Idx++]);
981
982   bool capturesCXXThis = Record[Idx++];
983   unsigned numCaptures = Record[Idx++];
984   SmallVector<BlockDecl::Capture, 16> captures;
985   captures.reserve(numCaptures);
986   for (unsigned i = 0; i != numCaptures; ++i) {
987     VarDecl *decl = ReadDeclAs<VarDecl>(Record, Idx);
988     unsigned flags = Record[Idx++];
989     bool byRef = (flags & 1);
990     bool nested = (flags & 2);
991     Expr *copyExpr = ((flags & 4) ? Reader.ReadExpr(F) : 0);
992
993     captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr));
994   }
995   BD->setCaptures(Reader.getContext(), captures.begin(),
996                   captures.end(), capturesCXXThis);
997 }
998
999 void ASTDeclReader::VisitCapturedDecl(CapturedDecl *CD) {
1000   VisitDecl(CD);
1001   // Body is set by VisitCapturedStmt.
1002   for (unsigned i = 0; i < CD->NumParams; ++i)
1003     CD->setParam(i, ReadDeclAs<ImplicitParamDecl>(Record, Idx));
1004 }
1005
1006 void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1007   VisitDecl(D);
1008   D->setLanguage((LinkageSpecDecl::LanguageIDs)Record[Idx++]);
1009   D->setExternLoc(ReadSourceLocation(Record, Idx));
1010   D->setRBraceLoc(ReadSourceLocation(Record, Idx));
1011 }
1012
1013 void ASTDeclReader::VisitLabelDecl(LabelDecl *D) {
1014   VisitNamedDecl(D);
1015   D->setLocStart(ReadSourceLocation(Record, Idx));
1016 }
1017
1018
1019 void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
1020   RedeclarableResult Redecl = VisitRedeclarable(D);
1021   VisitNamedDecl(D);
1022   D->setInline(Record[Idx++]);
1023   D->LocStart = ReadSourceLocation(Record, Idx);
1024   D->RBraceLoc = ReadSourceLocation(Record, Idx);
1025   mergeRedeclarable(D, Redecl);
1026
1027   if (Redecl.getFirstID() == ThisDeclID) {
1028     // Each module has its own anonymous namespace, which is disjoint from
1029     // any other module's anonymous namespaces, so don't attach the anonymous
1030     // namespace at all.
1031     NamespaceDecl *Anon = ReadDeclAs<NamespaceDecl>(Record, Idx);
1032     if (F.Kind != MK_Module)
1033       D->setAnonymousNamespace(Anon);
1034   } else {
1035     // Link this namespace back to the first declaration, which has already
1036     // been deserialized.
1037     D->AnonOrFirstNamespaceAndInline.setPointer(D->getFirstDeclaration());
1038   }
1039 }
1040
1041 void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1042   VisitNamedDecl(D);
1043   D->NamespaceLoc = ReadSourceLocation(Record, Idx);
1044   D->IdentLoc = ReadSourceLocation(Record, Idx);
1045   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1046   D->Namespace = ReadDeclAs<NamedDecl>(Record, Idx);
1047 }
1048
1049 void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
1050   VisitNamedDecl(D);
1051   D->setUsingLocation(ReadSourceLocation(Record, Idx));
1052   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1053   ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
1054   D->FirstUsingShadow.setPointer(ReadDeclAs<UsingShadowDecl>(Record, Idx));
1055   D->setTypeName(Record[Idx++]);
1056   if (NamedDecl *Pattern = ReadDeclAs<NamedDecl>(Record, Idx))
1057     Reader.getContext().setInstantiatedFromUsingDecl(D, Pattern);
1058 }
1059
1060 void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
1061   VisitNamedDecl(D);
1062   D->setTargetDecl(ReadDeclAs<NamedDecl>(Record, Idx));
1063   D->UsingOrNextShadow = ReadDeclAs<NamedDecl>(Record, Idx);
1064   UsingShadowDecl *Pattern = ReadDeclAs<UsingShadowDecl>(Record, Idx);
1065   if (Pattern)
1066     Reader.getContext().setInstantiatedFromUsingShadowDecl(D, Pattern);
1067 }
1068
1069 void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1070   VisitNamedDecl(D);
1071   D->UsingLoc = ReadSourceLocation(Record, Idx);
1072   D->NamespaceLoc = ReadSourceLocation(Record, Idx);
1073   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1074   D->NominatedNamespace = ReadDeclAs<NamedDecl>(Record, Idx);
1075   D->CommonAncestor = ReadDeclAs<DeclContext>(Record, Idx);
1076 }
1077
1078 void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1079   VisitValueDecl(D);
1080   D->setUsingLoc(ReadSourceLocation(Record, Idx));
1081   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1082   ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
1083 }
1084
1085 void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
1086                                                UnresolvedUsingTypenameDecl *D) {
1087   VisitTypeDecl(D);
1088   D->TypenameLocation = ReadSourceLocation(Record, Idx);
1089   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1090 }
1091
1092 void ASTDeclReader::ReadCXXDefinitionData(
1093                                    struct CXXRecordDecl::DefinitionData &Data,
1094                                    const RecordData &Record, unsigned &Idx) {
1095   // Note: the caller has deserialized the IsLambda bit already.
1096   Data.UserDeclaredConstructor = Record[Idx++];
1097   Data.UserDeclaredSpecialMembers = Record[Idx++];
1098   Data.Aggregate = Record[Idx++];
1099   Data.PlainOldData = Record[Idx++];
1100   Data.Empty = Record[Idx++];
1101   Data.Polymorphic = Record[Idx++];
1102   Data.Abstract = Record[Idx++];
1103   Data.IsStandardLayout = Record[Idx++];
1104   Data.HasNoNonEmptyBases = Record[Idx++];
1105   Data.HasPrivateFields = Record[Idx++];
1106   Data.HasProtectedFields = Record[Idx++];
1107   Data.HasPublicFields = Record[Idx++];
1108   Data.HasMutableFields = Record[Idx++];
1109   Data.HasOnlyCMembers = Record[Idx++];
1110   Data.HasInClassInitializer = Record[Idx++];
1111   Data.HasUninitializedReferenceMember = Record[Idx++];
1112   Data.NeedOverloadResolutionForMoveConstructor = Record[Idx++];
1113   Data.NeedOverloadResolutionForMoveAssignment = Record[Idx++];
1114   Data.NeedOverloadResolutionForDestructor = Record[Idx++];
1115   Data.DefaultedMoveConstructorIsDeleted = Record[Idx++];
1116   Data.DefaultedMoveAssignmentIsDeleted = Record[Idx++];
1117   Data.DefaultedDestructorIsDeleted = Record[Idx++];
1118   Data.HasTrivialSpecialMembers = Record[Idx++];
1119   Data.HasIrrelevantDestructor = Record[Idx++];
1120   Data.HasConstexprNonCopyMoveConstructor = Record[Idx++];
1121   Data.DefaultedDefaultConstructorIsConstexpr = Record[Idx++];
1122   Data.HasConstexprDefaultConstructor = Record[Idx++];
1123   Data.HasNonLiteralTypeFieldsOrBases = Record[Idx++];
1124   Data.ComputedVisibleConversions = Record[Idx++];
1125   Data.UserProvidedDefaultConstructor = Record[Idx++];
1126   Data.DeclaredSpecialMembers = Record[Idx++];
1127   Data.ImplicitCopyConstructorHasConstParam = Record[Idx++];
1128   Data.ImplicitCopyAssignmentHasConstParam = Record[Idx++];
1129   Data.HasDeclaredCopyConstructorWithConstParam = Record[Idx++];
1130   Data.HasDeclaredCopyAssignmentWithConstParam = Record[Idx++];
1131   Data.FailedImplicitMoveConstructor = Record[Idx++];
1132   Data.FailedImplicitMoveAssignment = Record[Idx++];
1133
1134   Data.NumBases = Record[Idx++];
1135   if (Data.NumBases)
1136     Data.Bases = Reader.readCXXBaseSpecifiers(F, Record, Idx);
1137   Data.NumVBases = Record[Idx++];
1138   if (Data.NumVBases)
1139     Data.VBases = Reader.readCXXBaseSpecifiers(F, Record, Idx);
1140   
1141   Reader.ReadUnresolvedSet(F, Data.Conversions, Record, Idx);
1142   Reader.ReadUnresolvedSet(F, Data.VisibleConversions, Record, Idx);
1143   assert(Data.Definition && "Data.Definition should be already set!");
1144   Data.FirstFriend = ReadDeclAs<FriendDecl>(Record, Idx);
1145   
1146   if (Data.IsLambda) {
1147     typedef LambdaExpr::Capture Capture;
1148     CXXRecordDecl::LambdaDefinitionData &Lambda
1149       = static_cast<CXXRecordDecl::LambdaDefinitionData &>(Data);
1150     Lambda.Dependent = Record[Idx++];
1151     Lambda.NumCaptures = Record[Idx++];
1152     Lambda.NumExplicitCaptures = Record[Idx++];
1153     Lambda.ManglingNumber = Record[Idx++];
1154     Lambda.ContextDecl = ReadDecl(Record, Idx);
1155     Lambda.Captures 
1156       = (Capture*)Reader.Context.Allocate(sizeof(Capture)*Lambda.NumCaptures);
1157     Capture *ToCapture = Lambda.Captures;
1158     Lambda.MethodTyInfo = GetTypeSourceInfo(Record, Idx);
1159     for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
1160       SourceLocation Loc = ReadSourceLocation(Record, Idx);
1161       bool IsImplicit = Record[Idx++];
1162       LambdaCaptureKind Kind = static_cast<LambdaCaptureKind>(Record[Idx++]);
1163       VarDecl *Var = ReadDeclAs<VarDecl>(Record, Idx);
1164       SourceLocation EllipsisLoc = ReadSourceLocation(Record, Idx);
1165       *ToCapture++ = Capture(Loc, IsImplicit, Kind, Var, EllipsisLoc);
1166     }
1167   }
1168 }
1169
1170 void ASTDeclReader::VisitCXXRecordDecl(CXXRecordDecl *D) {
1171   VisitRecordDecl(D);
1172
1173   ASTContext &C = Reader.getContext();
1174   if (Record[Idx++]) {
1175     // Determine whether this is a lambda closure type, so that we can
1176     // allocate the appropriate DefinitionData structure.
1177     bool IsLambda = Record[Idx++];
1178     if (IsLambda)
1179       D->DefinitionData = new (C) CXXRecordDecl::LambdaDefinitionData(D, 0,
1180                                                                       false);
1181     else
1182       D->DefinitionData = new (C) struct CXXRecordDecl::DefinitionData(D);
1183     
1184     // Propagate the DefinitionData pointer to the canonical declaration, so
1185     // that all other deserialized declarations will see it.
1186     // FIXME: Complain if there already is a DefinitionData!
1187     D->getCanonicalDecl()->DefinitionData = D->DefinitionData;
1188     
1189     ReadCXXDefinitionData(*D->DefinitionData, Record, Idx);
1190     
1191     // Note that we have deserialized a definition. Any declarations 
1192     // deserialized before this one will be be given the DefinitionData pointer
1193     // at the end.
1194     Reader.PendingDefinitions.insert(D);
1195   } else {
1196     // Propagate DefinitionData pointer from the canonical declaration.
1197     D->DefinitionData = D->getCanonicalDecl()->DefinitionData;    
1198   }
1199
1200   enum CXXRecKind {
1201     CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
1202   };
1203   switch ((CXXRecKind)Record[Idx++]) {
1204   case CXXRecNotTemplate:
1205     break;
1206   case CXXRecTemplate:
1207     D->TemplateOrInstantiation = ReadDeclAs<ClassTemplateDecl>(Record, Idx);
1208     break;
1209   case CXXRecMemberSpecialization: {
1210     CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(Record, Idx);
1211     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
1212     SourceLocation POI = ReadSourceLocation(Record, Idx);
1213     MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
1214     MSI->setPointOfInstantiation(POI);
1215     D->TemplateOrInstantiation = MSI;
1216     break;
1217   }
1218   }
1219
1220   // Load the key function to avoid deserializing every method so we can
1221   // compute it.
1222   if (D->IsCompleteDefinition) {
1223     if (CXXMethodDecl *Key = ReadDeclAs<CXXMethodDecl>(Record, Idx))
1224       C.KeyFunctions[D] = Key;
1225   }
1226 }
1227
1228 void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
1229   VisitFunctionDecl(D);
1230   unsigned NumOverridenMethods = Record[Idx++];
1231   while (NumOverridenMethods--) {
1232     // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
1233     // MD may be initializing.
1234     if (CXXMethodDecl *MD = ReadDeclAs<CXXMethodDecl>(Record, Idx))
1235       Reader.getContext().addOverriddenMethod(D, MD);
1236   }
1237 }
1238
1239 void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1240   VisitCXXMethodDecl(D);
1241   
1242   D->IsExplicitSpecified = Record[Idx++];
1243   D->ImplicitlyDefined = Record[Idx++];
1244   llvm::tie(D->CtorInitializers, D->NumCtorInitializers)
1245       = Reader.ReadCXXCtorInitializers(F, Record, Idx);
1246 }
1247
1248 void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1249   VisitCXXMethodDecl(D);
1250
1251   D->ImplicitlyDefined = Record[Idx++];
1252   D->OperatorDelete = ReadDeclAs<FunctionDecl>(Record, Idx);
1253 }
1254
1255 void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
1256   VisitCXXMethodDecl(D);
1257   D->IsExplicitSpecified = Record[Idx++];
1258 }
1259
1260 void ASTDeclReader::VisitImportDecl(ImportDecl *D) {
1261   VisitDecl(D);
1262   D->ImportedAndComplete.setPointer(readModule(Record, Idx));
1263   D->ImportedAndComplete.setInt(Record[Idx++]);
1264   SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(D + 1);
1265   for (unsigned I = 0, N = Record.back(); I != N; ++I)
1266     StoredLocs[I] = ReadSourceLocation(Record, Idx);
1267   ++Idx; // The number of stored source locations.
1268 }
1269
1270 void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
1271   VisitDecl(D);
1272   D->setColonLoc(ReadSourceLocation(Record, Idx));
1273 }
1274
1275 void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
1276   VisitDecl(D);
1277   if (Record[Idx++]) // hasFriendDecl
1278     D->Friend = ReadDeclAs<NamedDecl>(Record, Idx);
1279   else
1280     D->Friend = GetTypeSourceInfo(Record, Idx);
1281   for (unsigned i = 0; i != D->NumTPLists; ++i)
1282     D->getTPLists()[i] = Reader.ReadTemplateParameterList(F, Record, Idx);
1283   D->NextFriend = Record[Idx++];
1284   D->UnsupportedFriend = (Record[Idx++] != 0);
1285   D->FriendLoc = ReadSourceLocation(Record, Idx);
1286 }
1287
1288 void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
1289   VisitDecl(D);
1290   unsigned NumParams = Record[Idx++];
1291   D->NumParams = NumParams;
1292   D->Params = new TemplateParameterList*[NumParams];
1293   for (unsigned i = 0; i != NumParams; ++i)
1294     D->Params[i] = Reader.ReadTemplateParameterList(F, Record, Idx);
1295   if (Record[Idx++]) // HasFriendDecl
1296     D->Friend = ReadDeclAs<NamedDecl>(Record, Idx);
1297   else
1298     D->Friend = GetTypeSourceInfo(Record, Idx);
1299   D->FriendLoc = ReadSourceLocation(Record, Idx);
1300 }
1301
1302 void ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
1303   VisitNamedDecl(D);
1304
1305   NamedDecl *TemplatedDecl = ReadDeclAs<NamedDecl>(Record, Idx);
1306   TemplateParameterList* TemplateParams
1307       = Reader.ReadTemplateParameterList(F, Record, Idx); 
1308   D->init(TemplatedDecl, TemplateParams);
1309 }
1310
1311 ASTDeclReader::RedeclarableResult 
1312 ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
1313   RedeclarableResult Redecl = VisitRedeclarable(D);
1314
1315   // Make sure we've allocated the Common pointer first. We do this before
1316   // VisitTemplateDecl so that getCommonPtr() can be used during initialization.
1317   RedeclarableTemplateDecl *CanonD = D->getCanonicalDecl();
1318   if (!CanonD->Common) {
1319     CanonD->Common = CanonD->newCommon(Reader.getContext());
1320     Reader.PendingDefinitions.insert(CanonD);
1321   }
1322   D->Common = CanonD->Common;
1323
1324   // If this is the first declaration of the template, fill in the information
1325   // for the 'common' pointer.
1326   if (ThisDeclID == Redecl.getFirstID()) {
1327     if (RedeclarableTemplateDecl *RTD
1328           = ReadDeclAs<RedeclarableTemplateDecl>(Record, Idx)) {
1329       assert(RTD->getKind() == D->getKind() &&
1330              "InstantiatedFromMemberTemplate kind mismatch");
1331       D->setInstantiatedFromMemberTemplate(RTD);
1332       if (Record[Idx++])
1333         D->setMemberSpecialization();
1334     }
1335   }
1336
1337   VisitTemplateDecl(D);
1338   D->IdentifierNamespace = Record[Idx++];
1339
1340   mergeRedeclarable(D, Redecl);
1341
1342   return Redecl;
1343 }
1344
1345 void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1346   RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
1347
1348   if (ThisDeclID == Redecl.getFirstID()) {
1349     // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
1350     // the specializations.
1351     SmallVector<serialization::DeclID, 2> SpecIDs;
1352     SpecIDs.push_back(0);
1353     
1354     // Specializations.
1355     unsigned Size = Record[Idx++];
1356     SpecIDs[0] += Size;
1357     for (unsigned I = 0; I != Size; ++I)
1358       SpecIDs.push_back(ReadDeclID(Record, Idx));
1359
1360     // Partial specializations.
1361     Size = Record[Idx++];
1362     SpecIDs[0] += Size;
1363     for (unsigned I = 0; I != Size; ++I)
1364       SpecIDs.push_back(ReadDeclID(Record, Idx));
1365
1366     ClassTemplateDecl::Common *CommonPtr = D->getCommonPtr();
1367     if (SpecIDs[0]) {
1368       typedef serialization::DeclID DeclID;
1369       
1370       // FIXME: Append specializations!
1371       CommonPtr->LazySpecializations
1372         = new (Reader.getContext()) DeclID [SpecIDs.size()];
1373       memcpy(CommonPtr->LazySpecializations, SpecIDs.data(), 
1374              SpecIDs.size() * sizeof(DeclID));
1375     }
1376     
1377     CommonPtr->InjectedClassNameType = Reader.readType(F, Record, Idx);
1378   }
1379 }
1380
1381 void ASTDeclReader::VisitClassTemplateSpecializationDecl(
1382                                            ClassTemplateSpecializationDecl *D) {
1383   VisitCXXRecordDecl(D);
1384   
1385   ASTContext &C = Reader.getContext();
1386   if (Decl *InstD = ReadDecl(Record, Idx)) {
1387     if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
1388       D->SpecializedTemplate = CTD;
1389     } else {
1390       SmallVector<TemplateArgument, 8> TemplArgs;
1391       Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1392       TemplateArgumentList *ArgList
1393         = TemplateArgumentList::CreateCopy(C, TemplArgs.data(), 
1394                                            TemplArgs.size());
1395       ClassTemplateSpecializationDecl::SpecializedPartialSpecialization *PS
1396           = new (C) ClassTemplateSpecializationDecl::
1397                                              SpecializedPartialSpecialization();
1398       PS->PartialSpecialization
1399           = cast<ClassTemplatePartialSpecializationDecl>(InstD);
1400       PS->TemplateArgs = ArgList;
1401       D->SpecializedTemplate = PS;
1402     }
1403   }
1404
1405   // Explicit info.
1406   if (TypeSourceInfo *TyInfo = GetTypeSourceInfo(Record, Idx)) {
1407     ClassTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo
1408         = new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
1409     ExplicitInfo->TypeAsWritten = TyInfo;
1410     ExplicitInfo->ExternLoc = ReadSourceLocation(Record, Idx);
1411     ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation(Record, Idx);
1412     D->ExplicitInfo = ExplicitInfo;
1413   }
1414
1415   SmallVector<TemplateArgument, 8> TemplArgs;
1416   Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1417   D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs.data(), 
1418                                                      TemplArgs.size());
1419   D->PointOfInstantiation = ReadSourceLocation(Record, Idx);
1420   D->SpecializationKind = (TemplateSpecializationKind)Record[Idx++];
1421
1422   bool writtenAsCanonicalDecl = Record[Idx++];
1423   if (writtenAsCanonicalDecl) {
1424     ClassTemplateDecl *CanonPattern = ReadDeclAs<ClassTemplateDecl>(Record,Idx);
1425     if (D->isCanonicalDecl()) { // It's kept in the folding set.
1426       if (ClassTemplatePartialSpecializationDecl *Partial
1427                         = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
1428   CanonPattern->getCommonPtr()->PartialSpecializations.GetOrInsertNode(Partial);
1429       } else {
1430         CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
1431       }
1432     }
1433   }
1434 }
1435
1436 void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
1437                                     ClassTemplatePartialSpecializationDecl *D) {
1438   VisitClassTemplateSpecializationDecl(D);
1439
1440   ASTContext &C = Reader.getContext();
1441   D->TemplateParams = Reader.ReadTemplateParameterList(F, Record, Idx);
1442
1443   unsigned NumArgs = Record[Idx++];
1444   if (NumArgs) {
1445     D->NumArgsAsWritten = NumArgs;
1446     D->ArgsAsWritten = new (C) TemplateArgumentLoc[NumArgs];
1447     for (unsigned i=0; i != NumArgs; ++i)
1448       D->ArgsAsWritten[i] = Reader.ReadTemplateArgumentLoc(F, Record, Idx);
1449   }
1450
1451   D->SequenceNumber = Record[Idx++];
1452
1453   // These are read/set from/to the first declaration.
1454   if (D->getPreviousDecl() == 0) {
1455     D->InstantiatedFromMember.setPointer(
1456       ReadDeclAs<ClassTemplatePartialSpecializationDecl>(Record, Idx));
1457     D->InstantiatedFromMember.setInt(Record[Idx++]);
1458   }
1459 }
1460
1461 void ASTDeclReader::VisitClassScopeFunctionSpecializationDecl(
1462                                     ClassScopeFunctionSpecializationDecl *D) {
1463   VisitDecl(D);
1464   D->Specialization = ReadDeclAs<CXXMethodDecl>(Record, Idx);
1465 }
1466
1467 void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1468   RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
1469
1470   if (ThisDeclID == Redecl.getFirstID()) {
1471     // This FunctionTemplateDecl owns a CommonPtr; read it.
1472
1473     // Read the function specialization declarations.
1474     // FunctionTemplateDecl's FunctionTemplateSpecializationInfos are filled
1475     // when reading the specialized FunctionDecl.
1476     unsigned NumSpecs = Record[Idx++];
1477     while (NumSpecs--)
1478       (void)ReadDecl(Record, Idx);
1479   }
1480 }
1481
1482 void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
1483   VisitTypeDecl(D);
1484
1485   D->setDeclaredWithTypename(Record[Idx++]);
1486
1487   bool Inherited = Record[Idx++];
1488   TypeSourceInfo *DefArg = GetTypeSourceInfo(Record, Idx);
1489   D->setDefaultArgument(DefArg, Inherited);
1490 }
1491
1492 void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1493   VisitDeclaratorDecl(D);
1494   // TemplateParmPosition.
1495   D->setDepth(Record[Idx++]);
1496   D->setPosition(Record[Idx++]);
1497   if (D->isExpandedParameterPack()) {
1498     void **Data = reinterpret_cast<void **>(D + 1);
1499     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1500       Data[2*I] = Reader.readType(F, Record, Idx).getAsOpaquePtr();
1501       Data[2*I + 1] = GetTypeSourceInfo(Record, Idx);
1502     }
1503   } else {
1504     // Rest of NonTypeTemplateParmDecl.
1505     D->ParameterPack = Record[Idx++];
1506     if (Record[Idx++]) {
1507       Expr *DefArg = Reader.ReadExpr(F);
1508       bool Inherited = Record[Idx++];
1509       D->setDefaultArgument(DefArg, Inherited);
1510    }
1511   }
1512 }
1513
1514 void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
1515   VisitTemplateDecl(D);
1516   // TemplateParmPosition.
1517   D->setDepth(Record[Idx++]);
1518   D->setPosition(Record[Idx++]);
1519   if (D->isExpandedParameterPack()) {
1520     void **Data = reinterpret_cast<void **>(D + 1);
1521     for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
1522          I != N; ++I)
1523       Data[I] = Reader.ReadTemplateParameterList(F, Record, Idx);
1524   } else {
1525     // Rest of TemplateTemplateParmDecl.
1526     TemplateArgumentLoc Arg = Reader.ReadTemplateArgumentLoc(F, Record, Idx);
1527     bool IsInherited = Record[Idx++];
1528     D->setDefaultArgument(Arg, IsInherited);
1529     D->ParameterPack = Record[Idx++];
1530   }
1531 }
1532
1533 void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1534   VisitRedeclarableTemplateDecl(D);
1535 }
1536
1537 void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
1538   VisitDecl(D);
1539   D->AssertExprAndFailed.setPointer(Reader.ReadExpr(F));
1540   D->AssertExprAndFailed.setInt(Record[Idx++]);
1541   D->Message = cast<StringLiteral>(Reader.ReadExpr(F));
1542   D->RParenLoc = ReadSourceLocation(Record, Idx);
1543 }
1544
1545 void ASTDeclReader::VisitEmptyDecl(EmptyDecl *D) {
1546   VisitDecl(D);
1547 }
1548
1549 std::pair<uint64_t, uint64_t>
1550 ASTDeclReader::VisitDeclContext(DeclContext *DC) {
1551   uint64_t LexicalOffset = Record[Idx++];
1552   uint64_t VisibleOffset = Record[Idx++];
1553   return std::make_pair(LexicalOffset, VisibleOffset);
1554 }
1555
1556 template <typename T>
1557 ASTDeclReader::RedeclarableResult 
1558 ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
1559   DeclID FirstDeclID = ReadDeclID(Record, Idx);
1560   
1561   // 0 indicates that this declaration was the only declaration of its entity,
1562   // and is used for space optimization.
1563   if (FirstDeclID == 0)
1564     FirstDeclID = ThisDeclID;
1565   
1566   T *FirstDecl = cast_or_null<T>(Reader.GetDecl(FirstDeclID));
1567   if (FirstDecl != D) {
1568     // We delay loading of the redeclaration chain to avoid deeply nested calls.
1569     // We temporarily set the first (canonical) declaration as the previous one
1570     // which is the one that matters and mark the real previous DeclID to be
1571     // loaded & attached later on.
1572     D->RedeclLink = Redeclarable<T>::PreviousDeclLink(FirstDecl);
1573   }    
1574   
1575   // Note that this declaration has been deserialized.
1576   Reader.RedeclsDeserialized.insert(static_cast<T *>(D));
1577                              
1578   // The result structure takes care to note that we need to load the 
1579   // other declaration chains for this ID.
1580   return RedeclarableResult(Reader, FirstDeclID,
1581                             static_cast<T *>(D)->getKind());
1582 }
1583
1584 /// \brief Attempts to merge the given declaration (D) with another declaration
1585 /// of the same entity.
1586 template<typename T>
1587 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *D, 
1588                                       RedeclarableResult &Redecl) {
1589   // If modules are not available, there is no reason to perform this merge.
1590   if (!Reader.getContext().getLangOpts().Modules)
1591     return;
1592   
1593   if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D))) {
1594     if (T *Existing = ExistingRes) {
1595       T *ExistingCanon = Existing->getCanonicalDecl();
1596       T *DCanon = static_cast<T*>(D)->getCanonicalDecl();
1597       if (ExistingCanon != DCanon) {
1598         // Have our redeclaration link point back at the canonical declaration
1599         // of the existing declaration, so that this declaration has the 
1600         // appropriate canonical declaration.
1601         D->RedeclLink = Redeclarable<T>::PreviousDeclLink(ExistingCanon);
1602         
1603         // When we merge a namespace, update its pointer to the first namespace.
1604         if (NamespaceDecl *Namespace
1605               = dyn_cast<NamespaceDecl>(static_cast<T*>(D))) {
1606           Namespace->AnonOrFirstNamespaceAndInline.setPointer(
1607             static_cast<NamespaceDecl *>(static_cast<void*>(ExistingCanon)));
1608         }
1609         
1610         // Don't introduce DCanon into the set of pending declaration chains.
1611         Redecl.suppress();
1612         
1613         // Introduce ExistingCanon into the set of pending declaration chains,
1614         // if in fact it came from a module file.
1615         if (ExistingCanon->isFromASTFile()) {
1616           GlobalDeclID ExistingCanonID = ExistingCanon->getGlobalID();
1617           assert(ExistingCanonID && "Unrecorded canonical declaration ID?");
1618           if (Reader.PendingDeclChainsKnown.insert(ExistingCanonID))
1619             Reader.PendingDeclChains.push_back(ExistingCanonID);
1620         }
1621         
1622         // If this declaration was the canonical declaration, make a note of 
1623         // that. We accept the linear algorithm here because the number of 
1624         // unique canonical declarations of an entity should always be tiny.
1625         if (DCanon == static_cast<T*>(D)) {
1626           SmallVectorImpl<DeclID> &Merged = Reader.MergedDecls[ExistingCanon];
1627           if (std::find(Merged.begin(), Merged.end(), Redecl.getFirstID())
1628                 == Merged.end())
1629             Merged.push_back(Redecl.getFirstID());
1630           
1631           // If ExistingCanon did not come from a module file, introduce the
1632           // first declaration that *does* come from a module file to the 
1633           // set of pending declaration chains, so that we merge this 
1634           // declaration.
1635           if (!ExistingCanon->isFromASTFile() &&
1636               Reader.PendingDeclChainsKnown.insert(Redecl.getFirstID()))
1637             Reader.PendingDeclChains.push_back(Merged[0]);
1638         }
1639       }
1640     }
1641   }
1642 }
1643
1644 void ASTDeclReader::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
1645   VisitDecl(D);
1646   unsigned NumVars = D->varlist_size();
1647   SmallVector<DeclRefExpr *, 16> Vars;
1648   Vars.reserve(NumVars);
1649   for (unsigned i = 0; i != NumVars; ++i) {
1650     Vars.push_back(cast<DeclRefExpr>(Reader.ReadExpr(F)));
1651   }
1652   D->setVars(Vars);
1653 }
1654
1655 //===----------------------------------------------------------------------===//
1656 // Attribute Reading
1657 //===----------------------------------------------------------------------===//
1658
1659 /// \brief Reads attributes from the current stream position.
1660 void ASTReader::ReadAttributes(ModuleFile &F, AttrVec &Attrs,
1661                                const RecordData &Record, unsigned &Idx) {
1662   for (unsigned i = 0, e = Record[Idx++]; i != e; ++i) {
1663     Attr *New = 0;
1664     attr::Kind Kind = (attr::Kind)Record[Idx++];
1665     SourceRange Range = ReadSourceRange(F, Record, Idx);
1666
1667 #include "clang/Serialization/AttrPCHRead.inc"
1668
1669     assert(New && "Unable to decode attribute?");
1670     Attrs.push_back(New);
1671   }
1672 }
1673
1674 //===----------------------------------------------------------------------===//
1675 // ASTReader Implementation
1676 //===----------------------------------------------------------------------===//
1677
1678 /// \brief Note that we have loaded the declaration with the given
1679 /// Index.
1680 ///
1681 /// This routine notes that this declaration has already been loaded,
1682 /// so that future GetDecl calls will return this declaration rather
1683 /// than trying to load a new declaration.
1684 inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
1685   assert(!DeclsLoaded[Index] && "Decl loaded twice?");
1686   DeclsLoaded[Index] = D;
1687 }
1688
1689
1690 /// \brief Determine whether the consumer will be interested in seeing
1691 /// this declaration (via HandleTopLevelDecl).
1692 ///
1693 /// This routine should return true for anything that might affect
1694 /// code generation, e.g., inline function definitions, Objective-C
1695 /// declarations with metadata, etc.
1696 static bool isConsumerInterestedIn(Decl *D, bool HasBody) {
1697   // An ObjCMethodDecl is never considered as "interesting" because its
1698   // implementation container always is.
1699
1700   if (isa<FileScopeAsmDecl>(D) || 
1701       isa<ObjCProtocolDecl>(D) || 
1702       isa<ObjCImplDecl>(D))
1703     return true;
1704   if (VarDecl *Var = dyn_cast<VarDecl>(D))
1705     return Var->isFileVarDecl() &&
1706            Var->isThisDeclarationADefinition() == VarDecl::Definition;
1707   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
1708     return Func->doesThisDeclarationHaveABody() || HasBody;
1709   
1710   return false;
1711 }
1712
1713 /// \brief Get the correct cursor and offset for loading a declaration.
1714 ASTReader::RecordLocation
1715 ASTReader::DeclCursorForID(DeclID ID, unsigned &RawLocation) {
1716   // See if there's an override.
1717   DeclReplacementMap::iterator It = ReplacedDecls.find(ID);
1718   if (It != ReplacedDecls.end()) {
1719     RawLocation = It->second.RawLoc;
1720     return RecordLocation(It->second.Mod, It->second.Offset);
1721   }
1722
1723   GlobalDeclMapType::iterator I = GlobalDeclMap.find(ID);
1724   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
1725   ModuleFile *M = I->second;
1726   const DeclOffset &
1727     DOffs =  M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS];
1728   RawLocation = DOffs.Loc;
1729   return RecordLocation(M, DOffs.BitOffset);
1730 }
1731
1732 ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
1733   ContinuousRangeMap<uint64_t, ModuleFile*, 4>::iterator I
1734     = GlobalBitOffsetsMap.find(GlobalOffset);
1735
1736   assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map");
1737   return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
1738 }
1739
1740 uint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset) {
1741   return LocalOffset + M.GlobalBitOffset;
1742 }
1743
1744 /// \brief Determine whether the two declarations refer to the same entity.
1745 static bool isSameEntity(NamedDecl *X, NamedDecl *Y) {
1746   assert(X->getDeclName() == Y->getDeclName() && "Declaration name mismatch!");
1747   
1748   if (X == Y)
1749     return true;
1750   
1751   // Must be in the same context.
1752   if (!X->getDeclContext()->getRedeclContext()->Equals(
1753          Y->getDeclContext()->getRedeclContext()))
1754     return false;
1755
1756   // Two typedefs refer to the same entity if they have the same underlying
1757   // type.
1758   if (TypedefNameDecl *TypedefX = dyn_cast<TypedefNameDecl>(X))
1759     if (TypedefNameDecl *TypedefY = dyn_cast<TypedefNameDecl>(Y))
1760       return X->getASTContext().hasSameType(TypedefX->getUnderlyingType(),
1761                                             TypedefY->getUnderlyingType());
1762   
1763   // Must have the same kind.
1764   if (X->getKind() != Y->getKind())
1765     return false;
1766     
1767   // Objective-C classes and protocols with the same name always match.
1768   if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
1769     return true;
1770   
1771   // Compatible tags match.
1772   if (TagDecl *TagX = dyn_cast<TagDecl>(X)) {
1773     TagDecl *TagY = cast<TagDecl>(Y);
1774     return (TagX->getTagKind() == TagY->getTagKind()) ||
1775       ((TagX->getTagKind() == TTK_Struct || TagX->getTagKind() == TTK_Class ||
1776         TagX->getTagKind() == TTK_Interface) &&
1777        (TagY->getTagKind() == TTK_Struct || TagY->getTagKind() == TTK_Class ||
1778         TagY->getTagKind() == TTK_Interface));
1779   }
1780   
1781   // Functions with the same type and linkage match.
1782   // FIXME: This needs to cope with function templates, merging of 
1783   //prototyped/non-prototyped functions, etc.
1784   if (FunctionDecl *FuncX = dyn_cast<FunctionDecl>(X)) {
1785     FunctionDecl *FuncY = cast<FunctionDecl>(Y);
1786     return (FuncX->getLinkage() == FuncY->getLinkage()) &&
1787       FuncX->getASTContext().hasSameType(FuncX->getType(), FuncY->getType());
1788   }
1789
1790   // Variables with the same type and linkage match.
1791   if (VarDecl *VarX = dyn_cast<VarDecl>(X)) {
1792     VarDecl *VarY = cast<VarDecl>(Y);
1793     return (VarX->getLinkage() == VarY->getLinkage()) &&
1794       VarX->getASTContext().hasSameType(VarX->getType(), VarY->getType());
1795   }
1796   
1797   // Namespaces with the same name and inlinedness match.
1798   if (NamespaceDecl *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
1799     NamespaceDecl *NamespaceY = cast<NamespaceDecl>(Y);
1800     return NamespaceX->isInline() == NamespaceY->isInline();
1801   }
1802
1803   // Identical template names and kinds match.
1804   if (isa<TemplateDecl>(X))
1805     return true;
1806
1807   // FIXME: Many other cases to implement.
1808   return false;
1809 }
1810
1811 ASTDeclReader::FindExistingResult::~FindExistingResult() {
1812   if (!AddResult || Existing)
1813     return;
1814   
1815   if (New->getDeclContext()->getRedeclContext()->isTranslationUnit()
1816       && Reader.SemaObj) {
1817     Reader.SemaObj->IdResolver.tryAddTopLevelDecl(New, New->getDeclName());
1818   } else {
1819     DeclContext *DC = New->getLexicalDeclContext();
1820     if (DC->isNamespace())
1821       DC->addDecl(New);
1822   }
1823 }
1824
1825 ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) {
1826   DeclarationName Name = D->getDeclName();
1827   if (!Name) {
1828     // Don't bother trying to find unnamed declarations.
1829     FindExistingResult Result(Reader, D, /*Existing=*/0);
1830     Result.suppress();
1831     return Result;
1832   }
1833   
1834   DeclContext *DC = D->getDeclContext()->getRedeclContext();
1835   if (!DC->isFileContext())
1836     return FindExistingResult(Reader);
1837   
1838   if (DC->isTranslationUnit() && Reader.SemaObj) {
1839     IdentifierResolver &IdResolver = Reader.SemaObj->IdResolver;
1840
1841     // Temporarily consider the identifier to be up-to-date. We don't want to
1842     // cause additional lookups here.
1843     class UpToDateIdentifierRAII {
1844       IdentifierInfo *II;
1845       bool WasOutToDate;
1846
1847     public:
1848       explicit UpToDateIdentifierRAII(IdentifierInfo *II)
1849         : II(II), WasOutToDate(false)
1850       {
1851         if (II) {
1852           WasOutToDate = II->isOutOfDate();
1853           if (WasOutToDate)
1854             II->setOutOfDate(false);
1855         }
1856       }
1857
1858       ~UpToDateIdentifierRAII() {
1859         if (WasOutToDate)
1860           II->setOutOfDate(true);
1861       }
1862     } UpToDate(Name.getAsIdentifierInfo());
1863
1864     for (IdentifierResolver::iterator I = IdResolver.begin(Name), 
1865                                    IEnd = IdResolver.end();
1866          I != IEnd; ++I) {
1867       if (isSameEntity(*I, D))
1868         return FindExistingResult(Reader, D, *I);
1869     }
1870   }
1871
1872   if (DC->isNamespace()) {
1873     DeclContext::lookup_result R = DC->lookup(Name);
1874     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; 
1875          ++I) {
1876       if (isSameEntity(*I, D))
1877         return FindExistingResult(Reader, D, *I);
1878     }
1879   }
1880   
1881   return FindExistingResult(Reader, D, /*Existing=*/0);
1882 }
1883
1884 void ASTDeclReader::attachPreviousDecl(Decl *D, Decl *previous) {
1885   assert(D && previous);
1886   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
1887     TD->RedeclLink.setNext(cast<TagDecl>(previous));
1888   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1889     FD->RedeclLink.setNext(cast<FunctionDecl>(previous));
1890   } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1891     VD->RedeclLink.setNext(cast<VarDecl>(previous));
1892   } else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
1893     TD->RedeclLink.setNext(cast<TypedefNameDecl>(previous));
1894   } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
1895     ID->RedeclLink.setNext(cast<ObjCInterfaceDecl>(previous));
1896   } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
1897     PD->RedeclLink.setNext(cast<ObjCProtocolDecl>(previous));
1898   } else if (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(D)) {
1899     ND->RedeclLink.setNext(cast<NamespaceDecl>(previous));
1900   } else {
1901     RedeclarableTemplateDecl *TD = cast<RedeclarableTemplateDecl>(D);
1902     TD->RedeclLink.setNext(cast<RedeclarableTemplateDecl>(previous));
1903   }
1904 }
1905
1906 void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {
1907   assert(D && Latest);
1908   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
1909     TD->RedeclLink
1910       = Redeclarable<TagDecl>::LatestDeclLink(cast<TagDecl>(Latest));
1911   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1912     FD->RedeclLink 
1913       = Redeclarable<FunctionDecl>::LatestDeclLink(cast<FunctionDecl>(Latest));
1914   } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1915     VD->RedeclLink
1916       = Redeclarable<VarDecl>::LatestDeclLink(cast<VarDecl>(Latest));
1917   } else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
1918     TD->RedeclLink
1919       = Redeclarable<TypedefNameDecl>::LatestDeclLink(
1920                                                 cast<TypedefNameDecl>(Latest));
1921   } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
1922     ID->RedeclLink
1923       = Redeclarable<ObjCInterfaceDecl>::LatestDeclLink(
1924                                               cast<ObjCInterfaceDecl>(Latest));
1925   } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
1926     PD->RedeclLink
1927       = Redeclarable<ObjCProtocolDecl>::LatestDeclLink(
1928                                                 cast<ObjCProtocolDecl>(Latest));
1929   } else if (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(D)) {
1930     ND->RedeclLink
1931       = Redeclarable<NamespaceDecl>::LatestDeclLink(
1932                                                    cast<NamespaceDecl>(Latest));
1933   } else {
1934     RedeclarableTemplateDecl *TD = cast<RedeclarableTemplateDecl>(D);
1935     TD->RedeclLink
1936       = Redeclarable<RedeclarableTemplateDecl>::LatestDeclLink(
1937                                         cast<RedeclarableTemplateDecl>(Latest));
1938   }
1939 }
1940
1941 ASTReader::MergedDeclsMap::iterator
1942 ASTReader::combineStoredMergedDecls(Decl *Canon, GlobalDeclID CanonID) {
1943   // If we don't have any stored merged declarations, just look in the
1944   // merged declarations set.
1945   StoredMergedDeclsMap::iterator StoredPos = StoredMergedDecls.find(CanonID);
1946   if (StoredPos == StoredMergedDecls.end())
1947     return MergedDecls.find(Canon);
1948
1949   // Append the stored merged declarations to the merged declarations set.
1950   MergedDeclsMap::iterator Pos = MergedDecls.find(Canon);
1951   if (Pos == MergedDecls.end())
1952     Pos = MergedDecls.insert(std::make_pair(Canon, 
1953                                             SmallVector<DeclID, 2>())).first;
1954   Pos->second.append(StoredPos->second.begin(), StoredPos->second.end());
1955   StoredMergedDecls.erase(StoredPos);
1956   
1957   // Sort and uniquify the set of merged declarations.
1958   llvm::array_pod_sort(Pos->second.begin(), Pos->second.end());
1959   Pos->second.erase(std::unique(Pos->second.begin(), Pos->second.end()),
1960                     Pos->second.end());
1961   return Pos;
1962 }
1963
1964 void ASTReader::loadAndAttachPreviousDecl(Decl *D, serialization::DeclID ID) {
1965   Decl *previous = GetDecl(ID);
1966   ASTDeclReader::attachPreviousDecl(D, previous);
1967 }
1968
1969 /// \brief Read the declaration at the given offset from the AST file.
1970 Decl *ASTReader::ReadDeclRecord(DeclID ID) {
1971   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
1972   unsigned RawLocation = 0;
1973   RecordLocation Loc = DeclCursorForID(ID, RawLocation);
1974   llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
1975   // Keep track of where we are in the stream, then jump back there
1976   // after reading this declaration.
1977   SavedStreamPosition SavedPosition(DeclsCursor);
1978
1979   ReadingKindTracker ReadingKind(Read_Decl, *this);
1980
1981   // Note that we are loading a declaration record.
1982   Deserializing ADecl(this);
1983
1984   DeclsCursor.JumpToBit(Loc.Offset);
1985   RecordData Record;
1986   unsigned Code = DeclsCursor.ReadCode();
1987   unsigned Idx = 0;
1988   ASTDeclReader Reader(*this, *Loc.F, ID, RawLocation, Record,Idx);
1989
1990   Decl *D = 0;
1991   switch ((DeclCode)DeclsCursor.readRecord(Code, Record)) {
1992   case DECL_CONTEXT_LEXICAL:
1993   case DECL_CONTEXT_VISIBLE:
1994     llvm_unreachable("Record cannot be de-serialized with ReadDeclRecord");
1995   case DECL_TYPEDEF:
1996     D = TypedefDecl::CreateDeserialized(Context, ID);
1997     break;
1998   case DECL_TYPEALIAS:
1999     D = TypeAliasDecl::CreateDeserialized(Context, ID);
2000     break;
2001   case DECL_ENUM:
2002     D = EnumDecl::CreateDeserialized(Context, ID);
2003     break;
2004   case DECL_RECORD:
2005     D = RecordDecl::CreateDeserialized(Context, ID);
2006     break;
2007   case DECL_ENUM_CONSTANT:
2008     D = EnumConstantDecl::CreateDeserialized(Context, ID);
2009     break;
2010   case DECL_FUNCTION:
2011     D = FunctionDecl::CreateDeserialized(Context, ID);
2012     break;
2013   case DECL_LINKAGE_SPEC:
2014     D = LinkageSpecDecl::CreateDeserialized(Context, ID);
2015     break;
2016   case DECL_LABEL:
2017     D = LabelDecl::CreateDeserialized(Context, ID);
2018     break;
2019   case DECL_NAMESPACE:
2020     D = NamespaceDecl::CreateDeserialized(Context, ID);
2021     break;
2022   case DECL_NAMESPACE_ALIAS:
2023     D = NamespaceAliasDecl::CreateDeserialized(Context, ID);
2024     break;
2025   case DECL_USING:
2026     D = UsingDecl::CreateDeserialized(Context, ID);
2027     break;
2028   case DECL_USING_SHADOW:
2029     D = UsingShadowDecl::CreateDeserialized(Context, ID);
2030     break;
2031   case DECL_USING_DIRECTIVE:
2032     D = UsingDirectiveDecl::CreateDeserialized(Context, ID);
2033     break;
2034   case DECL_UNRESOLVED_USING_VALUE:
2035     D = UnresolvedUsingValueDecl::CreateDeserialized(Context, ID);
2036     break;
2037   case DECL_UNRESOLVED_USING_TYPENAME:
2038     D = UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID);
2039     break;
2040   case DECL_CXX_RECORD:
2041     D = CXXRecordDecl::CreateDeserialized(Context, ID);
2042     break;
2043   case DECL_CXX_METHOD:
2044     D = CXXMethodDecl::CreateDeserialized(Context, ID);
2045     break;
2046   case DECL_CXX_CONSTRUCTOR:
2047     D = CXXConstructorDecl::CreateDeserialized(Context, ID);
2048     break;
2049   case DECL_CXX_DESTRUCTOR:
2050     D = CXXDestructorDecl::CreateDeserialized(Context, ID);
2051     break;
2052   case DECL_CXX_CONVERSION:
2053     D = CXXConversionDecl::CreateDeserialized(Context, ID);
2054     break;
2055   case DECL_ACCESS_SPEC:
2056     D = AccessSpecDecl::CreateDeserialized(Context, ID);
2057     break;
2058   case DECL_FRIEND:
2059     D = FriendDecl::CreateDeserialized(Context, ID, Record[Idx++]);
2060     break;
2061   case DECL_FRIEND_TEMPLATE:
2062     D = FriendTemplateDecl::CreateDeserialized(Context, ID);
2063     break;
2064   case DECL_CLASS_TEMPLATE:
2065     D = ClassTemplateDecl::CreateDeserialized(Context, ID);
2066     break;
2067   case DECL_CLASS_TEMPLATE_SPECIALIZATION:
2068     D = ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID);
2069     break;
2070   case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
2071     D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
2072     break;
2073   case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
2074     D = ClassScopeFunctionSpecializationDecl::CreateDeserialized(Context, ID);
2075     break;
2076   case DECL_FUNCTION_TEMPLATE:
2077     D = FunctionTemplateDecl::CreateDeserialized(Context, ID);
2078     break;
2079   case DECL_TEMPLATE_TYPE_PARM:
2080     D = TemplateTypeParmDecl::CreateDeserialized(Context, ID);
2081     break;
2082   case DECL_NON_TYPE_TEMPLATE_PARM:
2083     D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID);
2084     break;
2085   case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK:
2086     D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID, Record[Idx++]);
2087     break;
2088   case DECL_TEMPLATE_TEMPLATE_PARM:
2089     D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID);
2090     break;
2091   case DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK:
2092     D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID,
2093                                                      Record[Idx++]);
2094     break;
2095   case DECL_TYPE_ALIAS_TEMPLATE:
2096     D = TypeAliasTemplateDecl::CreateDeserialized(Context, ID);
2097     break;
2098   case DECL_STATIC_ASSERT:
2099     D = StaticAssertDecl::CreateDeserialized(Context, ID);
2100     break;
2101   case DECL_OBJC_METHOD:
2102     D = ObjCMethodDecl::CreateDeserialized(Context, ID);
2103     break;
2104   case DECL_OBJC_INTERFACE:
2105     D = ObjCInterfaceDecl::CreateDeserialized(Context, ID);
2106     break;
2107   case DECL_OBJC_IVAR:
2108     D = ObjCIvarDecl::CreateDeserialized(Context, ID);
2109     break;
2110   case DECL_OBJC_PROTOCOL:
2111     D = ObjCProtocolDecl::CreateDeserialized(Context, ID);
2112     break;
2113   case DECL_OBJC_AT_DEFS_FIELD:
2114     D = ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID);
2115     break;
2116   case DECL_OBJC_CATEGORY:
2117     D = ObjCCategoryDecl::CreateDeserialized(Context, ID);
2118     break;
2119   case DECL_OBJC_CATEGORY_IMPL:
2120     D = ObjCCategoryImplDecl::CreateDeserialized(Context, ID);
2121     break;
2122   case DECL_OBJC_IMPLEMENTATION:
2123     D = ObjCImplementationDecl::CreateDeserialized(Context, ID);
2124     break;
2125   case DECL_OBJC_COMPATIBLE_ALIAS:
2126     D = ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID);
2127     break;
2128   case DECL_OBJC_PROPERTY:
2129     D = ObjCPropertyDecl::CreateDeserialized(Context, ID);
2130     break;
2131   case DECL_OBJC_PROPERTY_IMPL:
2132     D = ObjCPropertyImplDecl::CreateDeserialized(Context, ID);
2133     break;
2134   case DECL_FIELD:
2135     D = FieldDecl::CreateDeserialized(Context, ID);
2136     break;
2137   case DECL_INDIRECTFIELD:
2138     D = IndirectFieldDecl::CreateDeserialized(Context, ID);
2139     break;
2140   case DECL_VAR:
2141     D = VarDecl::CreateDeserialized(Context, ID);
2142     break;
2143   case DECL_IMPLICIT_PARAM:
2144     D = ImplicitParamDecl::CreateDeserialized(Context, ID);
2145     break;
2146   case DECL_PARM_VAR:
2147     D = ParmVarDecl::CreateDeserialized(Context, ID);
2148     break;
2149   case DECL_FILE_SCOPE_ASM:
2150     D = FileScopeAsmDecl::CreateDeserialized(Context, ID);
2151     break;
2152   case DECL_BLOCK:
2153     D = BlockDecl::CreateDeserialized(Context, ID);
2154     break;
2155   case DECL_MS_PROPERTY:
2156     D = MSPropertyDecl::CreateDeserialized(Context, ID);
2157     break;
2158   case DECL_CAPTURED:
2159     D = CapturedDecl::CreateDeserialized(Context, ID, Record[Idx++]);
2160     break;
2161   case DECL_CXX_BASE_SPECIFIERS:
2162     Error("attempt to read a C++ base-specifier record as a declaration");
2163     return 0;
2164   case DECL_IMPORT:
2165     // Note: last entry of the ImportDecl record is the number of stored source 
2166     // locations.
2167     D = ImportDecl::CreateDeserialized(Context, ID, Record.back());
2168     break;
2169   case DECL_OMP_THREADPRIVATE:
2170     D = OMPThreadPrivateDecl::CreateDeserialized(Context, ID, Record[Idx++]);
2171     break;
2172   case DECL_EMPTY:
2173     D = EmptyDecl::CreateDeserialized(Context, ID);
2174     break;
2175   }
2176
2177   assert(D && "Unknown declaration reading AST file");
2178   LoadedDecl(Index, D);
2179   // Set the DeclContext before doing any deserialization, to make sure internal
2180   // calls to Decl::getASTContext() by Decl's methods will find the
2181   // TranslationUnitDecl without crashing.
2182   D->setDeclContext(Context.getTranslationUnitDecl());
2183   Reader.Visit(D);
2184
2185   // If this declaration is also a declaration context, get the
2186   // offsets for its tables of lexical and visible declarations.
2187   if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
2188     // FIXME: This should really be
2189     //     DeclContext *LookupDC = DC->getPrimaryContext();
2190     // but that can walk the redeclaration chain, which might not work yet.
2191     DeclContext *LookupDC = DC;
2192     if (isa<NamespaceDecl>(DC))
2193       LookupDC = DC->getPrimaryContext();
2194     std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
2195     if (Offsets.first || Offsets.second) {
2196       if (Offsets.first != 0)
2197         DC->setHasExternalLexicalStorage(true);
2198       if (Offsets.second != 0)
2199         LookupDC->setHasExternalVisibleStorage(true);
2200       if (ReadDeclContextStorage(*Loc.F, DeclsCursor, Offsets, 
2201                                  Loc.F->DeclContextInfos[DC]))
2202         return 0;
2203     }
2204
2205     // Now add the pending visible updates for this decl context, if it has any.
2206     DeclContextVisibleUpdatesPending::iterator I =
2207         PendingVisibleUpdates.find(ID);
2208     if (I != PendingVisibleUpdates.end()) {
2209       // There are updates. This means the context has external visible
2210       // storage, even if the original stored version didn't.
2211       LookupDC->setHasExternalVisibleStorage(true);
2212       DeclContextVisibleUpdates &U = I->second;
2213       for (DeclContextVisibleUpdates::iterator UI = U.begin(), UE = U.end();
2214            UI != UE; ++UI) {
2215         DeclContextInfo &Info = UI->second->DeclContextInfos[DC];
2216         delete Info.NameLookupTableData;
2217         Info.NameLookupTableData = UI->first;
2218       }
2219       PendingVisibleUpdates.erase(I);
2220     }
2221   }
2222   assert(Idx == Record.size());
2223
2224   // Load any relevant update records.
2225   loadDeclUpdateRecords(ID, D);
2226
2227   // Load the categories after recursive loading is finished.
2228   if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2229     if (Class->isThisDeclarationADefinition())
2230       loadObjCCategories(ID, Class);
2231   
2232   // If we have deserialized a declaration that has a definition the
2233   // AST consumer might need to know about, queue it.
2234   // We don't pass it to the consumer immediately because we may be in recursive
2235   // loading, and some declarations may still be initializing.
2236   if (isConsumerInterestedIn(D, Reader.hasPendingBody()))
2237     InterestingDecls.push_back(D);
2238
2239   return D;
2240 }
2241
2242 void ASTReader::loadDeclUpdateRecords(serialization::DeclID ID, Decl *D) {
2243   // The declaration may have been modified by files later in the chain.
2244   // If this is the case, read the record containing the updates from each file
2245   // and pass it to ASTDeclReader to make the modifications.
2246   DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
2247   if (UpdI != DeclUpdateOffsets.end()) {
2248     FileOffsetsTy &UpdateOffsets = UpdI->second;
2249     for (FileOffsetsTy::iterator
2250          I = UpdateOffsets.begin(), E = UpdateOffsets.end(); I != E; ++I) {
2251       ModuleFile *F = I->first;
2252       uint64_t Offset = I->second;
2253       llvm::BitstreamCursor &Cursor = F->DeclsCursor;
2254       SavedStreamPosition SavedPosition(Cursor);
2255       Cursor.JumpToBit(Offset);
2256       RecordData Record;
2257       unsigned Code = Cursor.ReadCode();
2258       unsigned RecCode = Cursor.readRecord(Code, Record);
2259       (void)RecCode;
2260       assert(RecCode == DECL_UPDATES && "Expected DECL_UPDATES record!");
2261       
2262       unsigned Idx = 0;
2263       ASTDeclReader Reader(*this, *F, ID, 0, Record, Idx);
2264       Reader.UpdateDecl(D, *F, Record);
2265     }
2266   }
2267 }
2268
2269 namespace {
2270   struct CompareLocalRedeclarationsInfoToID {
2271     bool operator()(const LocalRedeclarationsInfo &X, DeclID Y) {
2272       return X.FirstID < Y;
2273     }
2274
2275     bool operator()(DeclID X, const LocalRedeclarationsInfo &Y) {
2276       return X < Y.FirstID;
2277     }
2278
2279     bool operator()(const LocalRedeclarationsInfo &X, 
2280                     const LocalRedeclarationsInfo &Y) {
2281       return X.FirstID < Y.FirstID;
2282     }
2283     bool operator()(DeclID X, DeclID Y) {
2284       return X < Y;
2285     }
2286   };
2287   
2288   /// \brief Module visitor class that finds all of the redeclarations of a 
2289   /// 
2290   class RedeclChainVisitor {
2291     ASTReader &Reader;
2292     SmallVectorImpl<DeclID> &SearchDecls;
2293     llvm::SmallPtrSet<Decl *, 16> &Deserialized;
2294     GlobalDeclID CanonID;
2295     SmallVector<Decl *, 4> Chain;
2296     
2297   public:
2298     RedeclChainVisitor(ASTReader &Reader, SmallVectorImpl<DeclID> &SearchDecls,
2299                        llvm::SmallPtrSet<Decl *, 16> &Deserialized,
2300                        GlobalDeclID CanonID)
2301       : Reader(Reader), SearchDecls(SearchDecls), Deserialized(Deserialized),
2302         CanonID(CanonID) { 
2303       for (unsigned I = 0, N = SearchDecls.size(); I != N; ++I)
2304         addToChain(Reader.GetDecl(SearchDecls[I]));
2305     }
2306     
2307     static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
2308       if (Preorder)
2309         return false;
2310       
2311       return static_cast<RedeclChainVisitor *>(UserData)->visit(M);
2312     }
2313     
2314     void addToChain(Decl *D) {
2315       if (!D)
2316         return;
2317       
2318       if (Deserialized.erase(D))
2319         Chain.push_back(D);
2320     }
2321     
2322     void searchForID(ModuleFile &M, GlobalDeclID GlobalID) {
2323       // Map global ID of the first declaration down to the local ID
2324       // used in this module file.
2325       DeclID ID = Reader.mapGlobalIDToModuleFileGlobalID(M, GlobalID);
2326       if (!ID)
2327         return;
2328       
2329       // Perform a binary search to find the local redeclarations for this
2330       // declaration (if any).
2331       const LocalRedeclarationsInfo *Result
2332         = std::lower_bound(M.RedeclarationsMap,
2333                            M.RedeclarationsMap + M.LocalNumRedeclarationsInMap, 
2334                            ID, CompareLocalRedeclarationsInfoToID());
2335       if (Result == M.RedeclarationsMap + M.LocalNumRedeclarationsInMap ||
2336           Result->FirstID != ID) {
2337         // If we have a previously-canonical singleton declaration that was 
2338         // merged into another redeclaration chain, create a trivial chain
2339         // for this single declaration so that it will get wired into the 
2340         // complete redeclaration chain.
2341         if (GlobalID != CanonID && 
2342             GlobalID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID && 
2343             GlobalID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls) {
2344           addToChain(Reader.GetDecl(GlobalID));
2345         }
2346         
2347         return;
2348       }
2349       
2350       // Dig out all of the redeclarations.
2351       unsigned Offset = Result->Offset;
2352       unsigned N = M.RedeclarationChains[Offset];
2353       M.RedeclarationChains[Offset++] = 0; // Don't try to deserialize again
2354       for (unsigned I = 0; I != N; ++I)
2355         addToChain(Reader.GetLocalDecl(M, M.RedeclarationChains[Offset++]));
2356     }
2357     
2358     bool visit(ModuleFile &M) {
2359       // Visit each of the declarations.
2360       for (unsigned I = 0, N = SearchDecls.size(); I != N; ++I)
2361         searchForID(M, SearchDecls[I]);
2362       return false;
2363     }
2364     
2365     ArrayRef<Decl *> getChain() const {
2366       return Chain;
2367     }
2368   };
2369 }
2370
2371 void ASTReader::loadPendingDeclChain(serialization::GlobalDeclID ID) {
2372   Decl *D = GetDecl(ID);  
2373   Decl *CanonDecl = D->getCanonicalDecl();
2374   
2375   // Determine the set of declaration IDs we'll be searching for.
2376   SmallVector<DeclID, 1> SearchDecls;
2377   GlobalDeclID CanonID = 0;
2378   if (D == CanonDecl) {
2379     SearchDecls.push_back(ID); // Always first.
2380     CanonID = ID;
2381   }
2382   MergedDeclsMap::iterator MergedPos = combineStoredMergedDecls(CanonDecl, ID);
2383   if (MergedPos != MergedDecls.end())
2384     SearchDecls.append(MergedPos->second.begin(), MergedPos->second.end());
2385   
2386   // Build up the list of redeclarations.
2387   RedeclChainVisitor Visitor(*this, SearchDecls, RedeclsDeserialized, CanonID);
2388   ModuleMgr.visitDepthFirst(&RedeclChainVisitor::visit, &Visitor);
2389   
2390   // Retrieve the chains.
2391   ArrayRef<Decl *> Chain = Visitor.getChain();
2392   if (Chain.empty())
2393     return;
2394     
2395   // Hook up the chains.
2396   Decl *MostRecent = CanonDecl->getMostRecentDecl();
2397   for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2398     if (Chain[I] == CanonDecl)
2399       continue;
2400     
2401     ASTDeclReader::attachPreviousDecl(Chain[I], MostRecent);
2402     MostRecent = Chain[I];
2403   }
2404   
2405   ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent);  
2406 }
2407
2408 namespace {
2409   struct CompareObjCCategoriesInfo {
2410     bool operator()(const ObjCCategoriesInfo &X, DeclID Y) {
2411       return X.DefinitionID < Y;
2412     }
2413     
2414     bool operator()(DeclID X, const ObjCCategoriesInfo &Y) {
2415       return X < Y.DefinitionID;
2416     }
2417     
2418     bool operator()(const ObjCCategoriesInfo &X, 
2419                     const ObjCCategoriesInfo &Y) {
2420       return X.DefinitionID < Y.DefinitionID;
2421     }
2422     bool operator()(DeclID X, DeclID Y) {
2423       return X < Y;
2424     }
2425   };
2426
2427   /// \brief Given an ObjC interface, goes through the modules and links to the
2428   /// interface all the categories for it.
2429   class ObjCCategoriesVisitor {
2430     ASTReader &Reader;
2431     serialization::GlobalDeclID InterfaceID;
2432     ObjCInterfaceDecl *Interface;
2433     llvm::SmallPtrSet<ObjCCategoryDecl *, 16> &Deserialized;
2434     unsigned PreviousGeneration;
2435     ObjCCategoryDecl *Tail;
2436     llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
2437     
2438     void add(ObjCCategoryDecl *Cat) {
2439       // Only process each category once.
2440       if (!Deserialized.erase(Cat))
2441         return;
2442       
2443       // Check for duplicate categories.
2444       if (Cat->getDeclName()) {
2445         ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
2446         if (Existing && 
2447             Reader.getOwningModuleFile(Existing) 
2448                                           != Reader.getOwningModuleFile(Cat)) {
2449           // FIXME: We should not warn for duplicates in diamond:
2450           //
2451           //   MT     //
2452           //  /  \    //
2453           // ML  MR   //
2454           //  \  /    //
2455           //   MB     //
2456           //
2457           // If there are duplicates in ML/MR, there will be warning when 
2458           // creating MB *and* when importing MB. We should not warn when 
2459           // importing.
2460           Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
2461             << Interface->getDeclName() << Cat->getDeclName();
2462           Reader.Diag(Existing->getLocation(), diag::note_previous_definition);
2463         } else if (!Existing) {
2464           // Record this category.
2465           Existing = Cat;
2466         }
2467       }
2468       
2469       // Add this category to the end of the chain.
2470       if (Tail)
2471         ASTDeclReader::setNextObjCCategory(Tail, Cat);
2472       else
2473         Interface->setCategoryListRaw(Cat);
2474       Tail = Cat;
2475     }
2476     
2477   public:
2478     ObjCCategoriesVisitor(ASTReader &Reader,
2479                           serialization::GlobalDeclID InterfaceID,
2480                           ObjCInterfaceDecl *Interface,
2481                         llvm::SmallPtrSet<ObjCCategoryDecl *, 16> &Deserialized,
2482                           unsigned PreviousGeneration)
2483       : Reader(Reader), InterfaceID(InterfaceID), Interface(Interface),
2484         Deserialized(Deserialized), PreviousGeneration(PreviousGeneration),
2485         Tail(0) 
2486     {
2487       // Populate the name -> category map with the set of known categories.
2488       for (ObjCInterfaceDecl::known_categories_iterator
2489              Cat = Interface->known_categories_begin(),
2490              CatEnd = Interface->known_categories_end();
2491            Cat != CatEnd; ++Cat) {
2492         if (Cat->getDeclName())
2493           NameCategoryMap[Cat->getDeclName()] = *Cat;
2494         
2495         // Keep track of the tail of the category list.
2496         Tail = *Cat;
2497       }
2498     }
2499
2500     static bool visit(ModuleFile &M, void *UserData) {
2501       return static_cast<ObjCCategoriesVisitor *>(UserData)->visit(M);
2502     }
2503
2504     bool visit(ModuleFile &M) {
2505       // If we've loaded all of the category information we care about from
2506       // this module file, we're done.
2507       if (M.Generation <= PreviousGeneration)
2508         return true;
2509       
2510       // Map global ID of the definition down to the local ID used in this 
2511       // module file. If there is no such mapping, we'll find nothing here
2512       // (or in any module it imports).
2513       DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID);
2514       if (!LocalID)
2515         return true;
2516
2517       // Perform a binary search to find the local redeclarations for this
2518       // declaration (if any).
2519       const ObjCCategoriesInfo *Result
2520         = std::lower_bound(M.ObjCCategoriesMap,
2521                            M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap, 
2522                            LocalID, CompareObjCCategoriesInfo());
2523       if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap ||
2524           Result->DefinitionID != LocalID) {
2525         // We didn't find anything. If the class definition is in this module
2526         // file, then the module files it depends on cannot have any categories,
2527         // so suppress further lookup.
2528         return Reader.isDeclIDFromModule(InterfaceID, M);
2529       }
2530       
2531       // We found something. Dig out all of the categories.
2532       unsigned Offset = Result->Offset;
2533       unsigned N = M.ObjCCategories[Offset];
2534       M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again
2535       for (unsigned I = 0; I != N; ++I)
2536         add(cast_or_null<ObjCCategoryDecl>(
2537               Reader.GetLocalDecl(M, M.ObjCCategories[Offset++])));
2538       return true;
2539     }
2540   };
2541 }
2542
2543 void ASTReader::loadObjCCategories(serialization::GlobalDeclID ID,
2544                                    ObjCInterfaceDecl *D,
2545                                    unsigned PreviousGeneration) {
2546   ObjCCategoriesVisitor Visitor(*this, ID, D, CategoriesDeserialized,
2547                                 PreviousGeneration);
2548   ModuleMgr.visit(ObjCCategoriesVisitor::visit, &Visitor);
2549 }
2550
2551 void ASTDeclReader::UpdateDecl(Decl *D, ModuleFile &ModuleFile,
2552                                const RecordData &Record) {
2553   unsigned Idx = 0;
2554   while (Idx < Record.size()) {
2555     switch ((DeclUpdateKind)Record[Idx++]) {
2556     case UPD_CXX_ADDED_IMPLICIT_MEMBER:
2557       cast<CXXRecordDecl>(D)->addedMember(Reader.ReadDecl(ModuleFile, Record, Idx));
2558       break;
2559
2560     case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
2561       // It will be added to the template's specializations set when loaded.
2562       (void)Reader.ReadDecl(ModuleFile, Record, Idx);
2563       break;
2564
2565     case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
2566       NamespaceDecl *Anon
2567         = Reader.ReadDeclAs<NamespaceDecl>(ModuleFile, Record, Idx);
2568       
2569       // Each module has its own anonymous namespace, which is disjoint from
2570       // any other module's anonymous namespaces, so don't attach the anonymous
2571       // namespace at all.
2572       if (ModuleFile.Kind != MK_Module) {
2573         if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(D))
2574           TU->setAnonymousNamespace(Anon);
2575         else
2576           cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon);
2577       }
2578       break;
2579     }
2580
2581     case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
2582       cast<VarDecl>(D)->getMemberSpecializationInfo()->setPointOfInstantiation(
2583           Reader.ReadSourceLocation(ModuleFile, Record, Idx));
2584       break;
2585     }
2586   }
2587 }