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->setIvarLBraceLoc(ReadSourceLocation(Record, Idx));
853   D->setIvarRBraceLoc(ReadSourceLocation(Record, Idx));
854   D->setHasNonZeroConstructors(Record[Idx++]);
855   D->setHasDestructors(Record[Idx++]);
856   llvm::tie(D->IvarInitializers, D->NumIvarInitializers)
857       = Reader.ReadCXXCtorInitializers(F, Record, Idx);
858 }
859 
860 
861 void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
862   VisitDecl(D);
863   D->setAtLoc(ReadSourceLocation(Record, Idx));
864   D->setPropertyDecl(ReadDeclAs<ObjCPropertyDecl>(Record, Idx));
865   D->PropertyIvarDecl = ReadDeclAs<ObjCIvarDecl>(Record, Idx);
866   D->IvarLoc = ReadSourceLocation(Record, Idx);
867   D->setGetterCXXConstructor(Reader.ReadExpr(F));
868   D->setSetterCXXAssignment(Reader.ReadExpr(F));
869 }
870 
871 void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {
872   VisitDeclaratorDecl(FD);
873   FD->Mutable = Record[Idx++];
874   if (int BitWidthOrInitializer = Record[Idx++]) {
875     FD->InitializerOrBitWidth.setInt(BitWidthOrInitializer - 1);
876     FD->InitializerOrBitWidth.setPointer(Reader.ReadExpr(F));
877   }
878   if (!FD->getDeclName()) {
879     if (FieldDecl *Tmpl = ReadDeclAs<FieldDecl>(Record, Idx))
880       Reader.getContext().setInstantiatedFromUnnamedFieldDecl(FD, Tmpl);
881   }
882 }
883 
884 void ASTDeclReader::VisitMSPropertyDecl(MSPropertyDecl *PD) {
885   VisitDeclaratorDecl(PD);
886   PD->GetterId = Reader.GetIdentifierInfo(F, Record, Idx);
887   PD->SetterId = Reader.GetIdentifierInfo(F, Record, Idx);
888 }
889 
890 void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
891   VisitValueDecl(FD);
892 
893   FD->ChainingSize = Record[Idx++];
894   assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2");
895   FD->Chaining = new (Reader.getContext())NamedDecl*[FD->ChainingSize];
896 
897   for (unsigned I = 0; I != FD->ChainingSize; ++I)
898     FD->Chaining[I] = ReadDeclAs<NamedDecl>(Record, Idx);
899 }
900 
901 void ASTDeclReader::VisitVarDecl(VarDecl *VD) {
902   RedeclarableResult Redecl = VisitRedeclarable(VD);
903   VisitDeclaratorDecl(VD);
904 
905   VD->VarDeclBits.SClass = (StorageClass)Record[Idx++];
906   VD->VarDeclBits.TLSKind = Record[Idx++];
907   VD->VarDeclBits.InitStyle = Record[Idx++];
908   VD->VarDeclBits.ExceptionVar = Record[Idx++];
909   VD->VarDeclBits.NRVOVariable = Record[Idx++];
910   VD->VarDeclBits.CXXForRangeDecl = Record[Idx++];
911   VD->VarDeclBits.ARCPseudoStrong = Record[Idx++];
912   VD->VarDeclBits.IsConstexpr = Record[Idx++];
913   VD->HasCachedLinkage = true;
914   VD->CachedLinkage = Record[Idx++];
915 
916   // Only true variables (not parameters or implicit parameters) can be merged.
917   if (VD->getKind() == Decl::Var)
918     mergeRedeclarable(VD, Redecl);
919 
920   if (uint64_t Val = Record[Idx++]) {
921     VD->setInit(Reader.ReadExpr(F));
922     if (Val > 1) {
923       EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
924       Eval->CheckedICE = true;
925       Eval->IsICE = Val == 3;
926     }
927   }
928 
929   if (Record[Idx++]) { // HasMemberSpecializationInfo.
930     VarDecl *Tmpl = ReadDeclAs<VarDecl>(Record, Idx);
931     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
932     SourceLocation POI = ReadSourceLocation(Record, Idx);
933     Reader.getContext().setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);
934   }
935 }
936 
937 void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
938   VisitVarDecl(PD);
939 }
940 
941 void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
942   VisitVarDecl(PD);
943   unsigned isObjCMethodParam = Record[Idx++];
944   unsigned scopeDepth = Record[Idx++];
945   unsigned scopeIndex = Record[Idx++];
946   unsigned declQualifier = Record[Idx++];
947   if (isObjCMethodParam) {
948     assert(scopeDepth == 0);
949     PD->setObjCMethodScopeInfo(scopeIndex);
950     PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier;
951   } else {
952     PD->setScopeInfo(scopeDepth, scopeIndex);
953   }
954   PD->ParmVarDeclBits.IsKNRPromoted = Record[Idx++];
955   PD->ParmVarDeclBits.HasInheritedDefaultArg = Record[Idx++];
956   if (Record[Idx++]) // hasUninstantiatedDefaultArg.
957     PD->setUninstantiatedDefaultArg(Reader.ReadExpr(F));
958 }
959 
960 void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
961   VisitDecl(AD);
962   AD->setAsmString(cast<StringLiteral>(Reader.ReadExpr(F)));
963   AD->setRParenLoc(ReadSourceLocation(Record, Idx));
964 }
965 
966 void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
967   VisitDecl(BD);
968   BD->setBody(cast_or_null<CompoundStmt>(Reader.ReadStmt(F)));
969   BD->setSignatureAsWritten(GetTypeSourceInfo(Record, Idx));
970   unsigned NumParams = Record[Idx++];
971   SmallVector<ParmVarDecl *, 16> Params;
972   Params.reserve(NumParams);
973   for (unsigned I = 0; I != NumParams; ++I)
974     Params.push_back(ReadDeclAs<ParmVarDecl>(Record, Idx));
975   BD->setParams(Params);
976 
977   BD->setIsVariadic(Record[Idx++]);
978   BD->setBlockMissingReturnType(Record[Idx++]);
979   BD->setIsConversionFromLambda(Record[Idx++]);
980 
981   bool capturesCXXThis = Record[Idx++];
982   unsigned numCaptures = Record[Idx++];
983   SmallVector<BlockDecl::Capture, 16> captures;
984   captures.reserve(numCaptures);
985   for (unsigned i = 0; i != numCaptures; ++i) {
986     VarDecl *decl = ReadDeclAs<VarDecl>(Record, Idx);
987     unsigned flags = Record[Idx++];
988     bool byRef = (flags & 1);
989     bool nested = (flags & 2);
990     Expr *copyExpr = ((flags & 4) ? Reader.ReadExpr(F) : 0);
991 
992     captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr));
993   }
994   BD->setCaptures(Reader.getContext(), captures.begin(),
995                   captures.end(), capturesCXXThis);
996 }
997 
998 void ASTDeclReader::VisitCapturedDecl(CapturedDecl *) {
999   llvm_unreachable("not implemented yet");
1000 }
1001 
1002 void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1003   VisitDecl(D);
1004   D->setLanguage((LinkageSpecDecl::LanguageIDs)Record[Idx++]);
1005   D->setExternLoc(ReadSourceLocation(Record, Idx));
1006   D->setRBraceLoc(ReadSourceLocation(Record, Idx));
1007 }
1008 
1009 void ASTDeclReader::VisitLabelDecl(LabelDecl *D) {
1010   VisitNamedDecl(D);
1011   D->setLocStart(ReadSourceLocation(Record, Idx));
1012 }
1013 
1014 
1015 void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
1016   RedeclarableResult Redecl = VisitRedeclarable(D);
1017   VisitNamedDecl(D);
1018   D->setInline(Record[Idx++]);
1019   D->LocStart = ReadSourceLocation(Record, Idx);
1020   D->RBraceLoc = ReadSourceLocation(Record, Idx);
1021   mergeRedeclarable(D, Redecl);
1022 
1023   if (Redecl.getFirstID() == ThisDeclID) {
1024     // Each module has its own anonymous namespace, which is disjoint from
1025     // any other module's anonymous namespaces, so don't attach the anonymous
1026     // namespace at all.
1027     NamespaceDecl *Anon = ReadDeclAs<NamespaceDecl>(Record, Idx);
1028     if (F.Kind != MK_Module)
1029       D->setAnonymousNamespace(Anon);
1030   } else {
1031     // Link this namespace back to the first declaration, which has already
1032     // been deserialized.
1033     D->AnonOrFirstNamespaceAndInline.setPointer(D->getFirstDeclaration());
1034   }
1035 }
1036 
1037 void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1038   VisitNamedDecl(D);
1039   D->NamespaceLoc = ReadSourceLocation(Record, Idx);
1040   D->IdentLoc = ReadSourceLocation(Record, Idx);
1041   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1042   D->Namespace = ReadDeclAs<NamedDecl>(Record, Idx);
1043 }
1044 
1045 void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
1046   VisitNamedDecl(D);
1047   D->setUsingLocation(ReadSourceLocation(Record, Idx));
1048   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1049   ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
1050   D->FirstUsingShadow.setPointer(ReadDeclAs<UsingShadowDecl>(Record, Idx));
1051   D->setTypeName(Record[Idx++]);
1052   if (NamedDecl *Pattern = ReadDeclAs<NamedDecl>(Record, Idx))
1053     Reader.getContext().setInstantiatedFromUsingDecl(D, Pattern);
1054 }
1055 
1056 void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
1057   VisitNamedDecl(D);
1058   D->setTargetDecl(ReadDeclAs<NamedDecl>(Record, Idx));
1059   D->UsingOrNextShadow = ReadDeclAs<NamedDecl>(Record, Idx);
1060   UsingShadowDecl *Pattern = ReadDeclAs<UsingShadowDecl>(Record, Idx);
1061   if (Pattern)
1062     Reader.getContext().setInstantiatedFromUsingShadowDecl(D, Pattern);
1063 }
1064 
1065 void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1066   VisitNamedDecl(D);
1067   D->UsingLoc = ReadSourceLocation(Record, Idx);
1068   D->NamespaceLoc = ReadSourceLocation(Record, Idx);
1069   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1070   D->NominatedNamespace = ReadDeclAs<NamedDecl>(Record, Idx);
1071   D->CommonAncestor = ReadDeclAs<DeclContext>(Record, Idx);
1072 }
1073 
1074 void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1075   VisitValueDecl(D);
1076   D->setUsingLoc(ReadSourceLocation(Record, Idx));
1077   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1078   ReadDeclarationNameLoc(D->DNLoc, D->getDeclName(), Record, Idx);
1079 }
1080 
1081 void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
1082                                                UnresolvedUsingTypenameDecl *D) {
1083   VisitTypeDecl(D);
1084   D->TypenameLocation = ReadSourceLocation(Record, Idx);
1085   D->QualifierLoc = Reader.ReadNestedNameSpecifierLoc(F, Record, Idx);
1086 }
1087 
1088 void ASTDeclReader::ReadCXXDefinitionData(
1089                                    struct CXXRecordDecl::DefinitionData &Data,
1090                                    const RecordData &Record, unsigned &Idx) {
1091   // Note: the caller has deserialized the IsLambda bit already.
1092   Data.UserDeclaredConstructor = Record[Idx++];
1093   Data.UserDeclaredSpecialMembers = Record[Idx++];
1094   Data.Aggregate = Record[Idx++];
1095   Data.PlainOldData = Record[Idx++];
1096   Data.Empty = Record[Idx++];
1097   Data.Polymorphic = Record[Idx++];
1098   Data.Abstract = Record[Idx++];
1099   Data.IsStandardLayout = Record[Idx++];
1100   Data.HasNoNonEmptyBases = Record[Idx++];
1101   Data.HasPrivateFields = Record[Idx++];
1102   Data.HasProtectedFields = Record[Idx++];
1103   Data.HasPublicFields = Record[Idx++];
1104   Data.HasMutableFields = Record[Idx++];
1105   Data.HasOnlyCMembers = Record[Idx++];
1106   Data.HasInClassInitializer = Record[Idx++];
1107   Data.HasUninitializedReferenceMember = Record[Idx++];
1108   Data.NeedOverloadResolutionForMoveConstructor = Record[Idx++];
1109   Data.NeedOverloadResolutionForMoveAssignment = Record[Idx++];
1110   Data.NeedOverloadResolutionForDestructor = Record[Idx++];
1111   Data.DefaultedMoveConstructorIsDeleted = Record[Idx++];
1112   Data.DefaultedMoveAssignmentIsDeleted = Record[Idx++];
1113   Data.DefaultedDestructorIsDeleted = Record[Idx++];
1114   Data.HasTrivialSpecialMembers = Record[Idx++];
1115   Data.HasIrrelevantDestructor = Record[Idx++];
1116   Data.HasConstexprNonCopyMoveConstructor = Record[Idx++];
1117   Data.DefaultedDefaultConstructorIsConstexpr = Record[Idx++];
1118   Data.HasConstexprDefaultConstructor = Record[Idx++];
1119   Data.HasNonLiteralTypeFieldsOrBases = Record[Idx++];
1120   Data.ComputedVisibleConversions = Record[Idx++];
1121   Data.UserProvidedDefaultConstructor = Record[Idx++];
1122   Data.DeclaredSpecialMembers = Record[Idx++];
1123   Data.ImplicitCopyConstructorHasConstParam = Record[Idx++];
1124   Data.ImplicitCopyAssignmentHasConstParam = Record[Idx++];
1125   Data.HasDeclaredCopyConstructorWithConstParam = Record[Idx++];
1126   Data.HasDeclaredCopyAssignmentWithConstParam = Record[Idx++];
1127   Data.FailedImplicitMoveConstructor = Record[Idx++];
1128   Data.FailedImplicitMoveAssignment = Record[Idx++];
1129 
1130   Data.NumBases = Record[Idx++];
1131   if (Data.NumBases)
1132     Data.Bases = Reader.readCXXBaseSpecifiers(F, Record, Idx);
1133   Data.NumVBases = Record[Idx++];
1134   if (Data.NumVBases)
1135     Data.VBases = Reader.readCXXBaseSpecifiers(F, Record, Idx);
1136 
1137   Reader.ReadUnresolvedSet(F, Data.Conversions, Record, Idx);
1138   Reader.ReadUnresolvedSet(F, Data.VisibleConversions, Record, Idx);
1139   assert(Data.Definition && "Data.Definition should be already set!");
1140   Data.FirstFriend = ReadDeclAs<FriendDecl>(Record, Idx);
1141 
1142   if (Data.IsLambda) {
1143     typedef LambdaExpr::Capture Capture;
1144     CXXRecordDecl::LambdaDefinitionData &Lambda
1145       = static_cast<CXXRecordDecl::LambdaDefinitionData &>(Data);
1146     Lambda.Dependent = Record[Idx++];
1147     Lambda.NumCaptures = Record[Idx++];
1148     Lambda.NumExplicitCaptures = Record[Idx++];
1149     Lambda.ManglingNumber = Record[Idx++];
1150     Lambda.ContextDecl = ReadDecl(Record, Idx);
1151     Lambda.Captures
1152       = (Capture*)Reader.Context.Allocate(sizeof(Capture)*Lambda.NumCaptures);
1153     Capture *ToCapture = Lambda.Captures;
1154     Lambda.MethodTyInfo = GetTypeSourceInfo(Record, Idx);
1155     for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
1156       SourceLocation Loc = ReadSourceLocation(Record, Idx);
1157       bool IsImplicit = Record[Idx++];
1158       LambdaCaptureKind Kind = static_cast<LambdaCaptureKind>(Record[Idx++]);
1159       VarDecl *Var = ReadDeclAs<VarDecl>(Record, Idx);
1160       SourceLocation EllipsisLoc = ReadSourceLocation(Record, Idx);
1161       *ToCapture++ = Capture(Loc, IsImplicit, Kind, Var, EllipsisLoc);
1162     }
1163   }
1164 }
1165 
1166 void ASTDeclReader::VisitCXXRecordDecl(CXXRecordDecl *D) {
1167   VisitRecordDecl(D);
1168 
1169   ASTContext &C = Reader.getContext();
1170   if (Record[Idx++]) {
1171     // Determine whether this is a lambda closure type, so that we can
1172     // allocate the appropriate DefinitionData structure.
1173     bool IsLambda = Record[Idx++];
1174     if (IsLambda)
1175       D->DefinitionData = new (C) CXXRecordDecl::LambdaDefinitionData(D, 0,
1176                                                                       false);
1177     else
1178       D->DefinitionData = new (C) struct CXXRecordDecl::DefinitionData(D);
1179 
1180     // Propagate the DefinitionData pointer to the canonical declaration, so
1181     // that all other deserialized declarations will see it.
1182     // FIXME: Complain if there already is a DefinitionData!
1183     D->getCanonicalDecl()->DefinitionData = D->DefinitionData;
1184 
1185     ReadCXXDefinitionData(*D->DefinitionData, Record, Idx);
1186 
1187     // Note that we have deserialized a definition. Any declarations
1188     // deserialized before this one will be be given the DefinitionData pointer
1189     // at the end.
1190     Reader.PendingDefinitions.insert(D);
1191   } else {
1192     // Propagate DefinitionData pointer from the canonical declaration.
1193     D->DefinitionData = D->getCanonicalDecl()->DefinitionData;
1194   }
1195 
1196   enum CXXRecKind {
1197     CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
1198   };
1199   switch ((CXXRecKind)Record[Idx++]) {
1200   case CXXRecNotTemplate:
1201     break;
1202   case CXXRecTemplate:
1203     D->TemplateOrInstantiation = ReadDeclAs<ClassTemplateDecl>(Record, Idx);
1204     break;
1205   case CXXRecMemberSpecialization: {
1206     CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>(Record, Idx);
1207     TemplateSpecializationKind TSK = (TemplateSpecializationKind)Record[Idx++];
1208     SourceLocation POI = ReadSourceLocation(Record, Idx);
1209     MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
1210     MSI->setPointOfInstantiation(POI);
1211     D->TemplateOrInstantiation = MSI;
1212     break;
1213   }
1214   }
1215 
1216   // Load the key function to avoid deserializing every method so we can
1217   // compute it.
1218   if (D->IsCompleteDefinition) {
1219     if (CXXMethodDecl *Key = ReadDeclAs<CXXMethodDecl>(Record, Idx))
1220       C.KeyFunctions[D] = Key;
1221   }
1222 }
1223 
1224 void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
1225   VisitFunctionDecl(D);
1226   unsigned NumOverridenMethods = Record[Idx++];
1227   while (NumOverridenMethods--) {
1228     // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
1229     // MD may be initializing.
1230     if (CXXMethodDecl *MD = ReadDeclAs<CXXMethodDecl>(Record, Idx))
1231       Reader.getContext().addOverriddenMethod(D, MD);
1232   }
1233 }
1234 
1235 void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1236   VisitCXXMethodDecl(D);
1237 
1238   D->IsExplicitSpecified = Record[Idx++];
1239   D->ImplicitlyDefined = Record[Idx++];
1240   llvm::tie(D->CtorInitializers, D->NumCtorInitializers)
1241       = Reader.ReadCXXCtorInitializers(F, Record, Idx);
1242 }
1243 
1244 void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1245   VisitCXXMethodDecl(D);
1246 
1247   D->ImplicitlyDefined = Record[Idx++];
1248   D->OperatorDelete = ReadDeclAs<FunctionDecl>(Record, Idx);
1249 }
1250 
1251 void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
1252   VisitCXXMethodDecl(D);
1253   D->IsExplicitSpecified = Record[Idx++];
1254 }
1255 
1256 void ASTDeclReader::VisitImportDecl(ImportDecl *D) {
1257   VisitDecl(D);
1258   D->ImportedAndComplete.setPointer(readModule(Record, Idx));
1259   D->ImportedAndComplete.setInt(Record[Idx++]);
1260   SourceLocation *StoredLocs = reinterpret_cast<SourceLocation *>(D + 1);
1261   for (unsigned I = 0, N = Record.back(); I != N; ++I)
1262     StoredLocs[I] = ReadSourceLocation(Record, Idx);
1263   ++Idx; // The number of stored source locations.
1264 }
1265 
1266 void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
1267   VisitDecl(D);
1268   D->setColonLoc(ReadSourceLocation(Record, Idx));
1269 }
1270 
1271 void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
1272   VisitDecl(D);
1273   if (Record[Idx++]) // hasFriendDecl
1274     D->Friend = ReadDeclAs<NamedDecl>(Record, Idx);
1275   else
1276     D->Friend = GetTypeSourceInfo(Record, Idx);
1277   for (unsigned i = 0; i != D->NumTPLists; ++i)
1278     D->getTPLists()[i] = Reader.ReadTemplateParameterList(F, Record, Idx);
1279   D->NextFriend = Record[Idx++];
1280   D->UnsupportedFriend = (Record[Idx++] != 0);
1281   D->FriendLoc = ReadSourceLocation(Record, Idx);
1282 }
1283 
1284 void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
1285   VisitDecl(D);
1286   unsigned NumParams = Record[Idx++];
1287   D->NumParams = NumParams;
1288   D->Params = new TemplateParameterList*[NumParams];
1289   for (unsigned i = 0; i != NumParams; ++i)
1290     D->Params[i] = Reader.ReadTemplateParameterList(F, Record, Idx);
1291   if (Record[Idx++]) // HasFriendDecl
1292     D->Friend = ReadDeclAs<NamedDecl>(Record, Idx);
1293   else
1294     D->Friend = GetTypeSourceInfo(Record, Idx);
1295   D->FriendLoc = ReadSourceLocation(Record, Idx);
1296 }
1297 
1298 void ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
1299   VisitNamedDecl(D);
1300 
1301   NamedDecl *TemplatedDecl = ReadDeclAs<NamedDecl>(Record, Idx);
1302   TemplateParameterList* TemplateParams
1303       = Reader.ReadTemplateParameterList(F, Record, Idx);
1304   D->init(TemplatedDecl, TemplateParams);
1305 }
1306 
1307 ASTDeclReader::RedeclarableResult
1308 ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
1309   RedeclarableResult Redecl = VisitRedeclarable(D);
1310 
1311   // Make sure we've allocated the Common pointer first. We do this before
1312   // VisitTemplateDecl so that getCommonPtr() can be used during initialization.
1313   RedeclarableTemplateDecl *CanonD = D->getCanonicalDecl();
1314   if (!CanonD->Common) {
1315     CanonD->Common = CanonD->newCommon(Reader.getContext());
1316     Reader.PendingDefinitions.insert(CanonD);
1317   }
1318   D->Common = CanonD->Common;
1319 
1320   // If this is the first declaration of the template, fill in the information
1321   // for the 'common' pointer.
1322   if (ThisDeclID == Redecl.getFirstID()) {
1323     if (RedeclarableTemplateDecl *RTD
1324           = ReadDeclAs<RedeclarableTemplateDecl>(Record, Idx)) {
1325       assert(RTD->getKind() == D->getKind() &&
1326              "InstantiatedFromMemberTemplate kind mismatch");
1327       D->setInstantiatedFromMemberTemplate(RTD);
1328       if (Record[Idx++])
1329         D->setMemberSpecialization();
1330     }
1331   }
1332 
1333   VisitTemplateDecl(D);
1334   D->IdentifierNamespace = Record[Idx++];
1335 
1336   mergeRedeclarable(D, Redecl);
1337 
1338   return Redecl;
1339 }
1340 
1341 void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1342   RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
1343 
1344   if (ThisDeclID == Redecl.getFirstID()) {
1345     // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
1346     // the specializations.
1347     SmallVector<serialization::DeclID, 2> SpecIDs;
1348     SpecIDs.push_back(0);
1349 
1350     // Specializations.
1351     unsigned Size = Record[Idx++];
1352     SpecIDs[0] += Size;
1353     for (unsigned I = 0; I != Size; ++I)
1354       SpecIDs.push_back(ReadDeclID(Record, Idx));
1355 
1356     // Partial specializations.
1357     Size = Record[Idx++];
1358     SpecIDs[0] += Size;
1359     for (unsigned I = 0; I != Size; ++I)
1360       SpecIDs.push_back(ReadDeclID(Record, Idx));
1361 
1362     ClassTemplateDecl::Common *CommonPtr = D->getCommonPtr();
1363     if (SpecIDs[0]) {
1364       typedef serialization::DeclID DeclID;
1365 
1366       // FIXME: Append specializations!
1367       CommonPtr->LazySpecializations
1368         = new (Reader.getContext()) DeclID [SpecIDs.size()];
1369       memcpy(CommonPtr->LazySpecializations, SpecIDs.data(),
1370              SpecIDs.size() * sizeof(DeclID));
1371     }
1372 
1373     CommonPtr->InjectedClassNameType = Reader.readType(F, Record, Idx);
1374   }
1375 }
1376 
1377 void ASTDeclReader::VisitClassTemplateSpecializationDecl(
1378                                            ClassTemplateSpecializationDecl *D) {
1379   VisitCXXRecordDecl(D);
1380 
1381   ASTContext &C = Reader.getContext();
1382   if (Decl *InstD = ReadDecl(Record, Idx)) {
1383     if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
1384       D->SpecializedTemplate = CTD;
1385     } else {
1386       SmallVector<TemplateArgument, 8> TemplArgs;
1387       Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1388       TemplateArgumentList *ArgList
1389         = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
1390                                            TemplArgs.size());
1391       ClassTemplateSpecializationDecl::SpecializedPartialSpecialization *PS
1392           = new (C) ClassTemplateSpecializationDecl::
1393                                              SpecializedPartialSpecialization();
1394       PS->PartialSpecialization
1395           = cast<ClassTemplatePartialSpecializationDecl>(InstD);
1396       PS->TemplateArgs = ArgList;
1397       D->SpecializedTemplate = PS;
1398     }
1399   }
1400 
1401   // Explicit info.
1402   if (TypeSourceInfo *TyInfo = GetTypeSourceInfo(Record, Idx)) {
1403     ClassTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo
1404         = new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
1405     ExplicitInfo->TypeAsWritten = TyInfo;
1406     ExplicitInfo->ExternLoc = ReadSourceLocation(Record, Idx);
1407     ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation(Record, Idx);
1408     D->ExplicitInfo = ExplicitInfo;
1409   }
1410 
1411   SmallVector<TemplateArgument, 8> TemplArgs;
1412   Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1413   D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
1414                                                      TemplArgs.size());
1415   D->PointOfInstantiation = ReadSourceLocation(Record, Idx);
1416   D->SpecializationKind = (TemplateSpecializationKind)Record[Idx++];
1417 
1418   bool writtenAsCanonicalDecl = Record[Idx++];
1419   if (writtenAsCanonicalDecl) {
1420     ClassTemplateDecl *CanonPattern = ReadDeclAs<ClassTemplateDecl>(Record,Idx);
1421     if (D->isCanonicalDecl()) { // It's kept in the folding set.
1422       if (ClassTemplatePartialSpecializationDecl *Partial
1423                         = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
1424   CanonPattern->getCommonPtr()->PartialSpecializations.GetOrInsertNode(Partial);
1425       } else {
1426         CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
1427       }
1428     }
1429   }
1430 }
1431 
1432 void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
1433                                     ClassTemplatePartialSpecializationDecl *D) {
1434   VisitClassTemplateSpecializationDecl(D);
1435 
1436   ASTContext &C = Reader.getContext();
1437   D->TemplateParams = Reader.ReadTemplateParameterList(F, Record, Idx);
1438 
1439   unsigned NumArgs = Record[Idx++];
1440   if (NumArgs) {
1441     D->NumArgsAsWritten = NumArgs;
1442     D->ArgsAsWritten = new (C) TemplateArgumentLoc[NumArgs];
1443     for (unsigned i=0; i != NumArgs; ++i)
1444       D->ArgsAsWritten[i] = Reader.ReadTemplateArgumentLoc(F, Record, Idx);
1445   }
1446 
1447   D->SequenceNumber = Record[Idx++];
1448 
1449   // These are read/set from/to the first declaration.
1450   if (D->getPreviousDecl() == 0) {
1451     D->InstantiatedFromMember.setPointer(
1452       ReadDeclAs<ClassTemplatePartialSpecializationDecl>(Record, Idx));
1453     D->InstantiatedFromMember.setInt(Record[Idx++]);
1454   }
1455 }
1456 
1457 void ASTDeclReader::VisitClassScopeFunctionSpecializationDecl(
1458                                     ClassScopeFunctionSpecializationDecl *D) {
1459   VisitDecl(D);
1460   D->Specialization = ReadDeclAs<CXXMethodDecl>(Record, Idx);
1461 }
1462 
1463 void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1464   RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
1465 
1466   if (ThisDeclID == Redecl.getFirstID()) {
1467     // This FunctionTemplateDecl owns a CommonPtr; read it.
1468 
1469     // Read the function specialization declarations.
1470     // FunctionTemplateDecl's FunctionTemplateSpecializationInfos are filled
1471     // when reading the specialized FunctionDecl.
1472     unsigned NumSpecs = Record[Idx++];
1473     while (NumSpecs--)
1474       (void)ReadDecl(Record, Idx);
1475   }
1476 }
1477 
1478 void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
1479   VisitTypeDecl(D);
1480 
1481   D->setDeclaredWithTypename(Record[Idx++]);
1482 
1483   bool Inherited = Record[Idx++];
1484   TypeSourceInfo *DefArg = GetTypeSourceInfo(Record, Idx);
1485   D->setDefaultArgument(DefArg, Inherited);
1486 }
1487 
1488 void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1489   VisitDeclaratorDecl(D);
1490   // TemplateParmPosition.
1491   D->setDepth(Record[Idx++]);
1492   D->setPosition(Record[Idx++]);
1493   if (D->isExpandedParameterPack()) {
1494     void **Data = reinterpret_cast<void **>(D + 1);
1495     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1496       Data[2*I] = Reader.readType(F, Record, Idx).getAsOpaquePtr();
1497       Data[2*I + 1] = GetTypeSourceInfo(Record, Idx);
1498     }
1499   } else {
1500     // Rest of NonTypeTemplateParmDecl.
1501     D->ParameterPack = Record[Idx++];
1502     if (Record[Idx++]) {
1503       Expr *DefArg = Reader.ReadExpr(F);
1504       bool Inherited = Record[Idx++];
1505       D->setDefaultArgument(DefArg, Inherited);
1506    }
1507   }
1508 }
1509 
1510 void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
1511   VisitTemplateDecl(D);
1512   // TemplateParmPosition.
1513   D->setDepth(Record[Idx++]);
1514   D->setPosition(Record[Idx++]);
1515   if (D->isExpandedParameterPack()) {
1516     void **Data = reinterpret_cast<void **>(D + 1);
1517     for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
1518          I != N; ++I)
1519       Data[I] = Reader.ReadTemplateParameterList(F, Record, Idx);
1520   } else {
1521     // Rest of TemplateTemplateParmDecl.
1522     TemplateArgumentLoc Arg = Reader.ReadTemplateArgumentLoc(F, Record, Idx);
1523     bool IsInherited = Record[Idx++];
1524     D->setDefaultArgument(Arg, IsInherited);
1525     D->ParameterPack = Record[Idx++];
1526   }
1527 }
1528 
1529 void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1530   VisitRedeclarableTemplateDecl(D);
1531 }
1532 
1533 void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
1534   VisitDecl(D);
1535   D->AssertExprAndFailed.setPointer(Reader.ReadExpr(F));
1536   D->AssertExprAndFailed.setInt(Record[Idx++]);
1537   D->Message = cast<StringLiteral>(Reader.ReadExpr(F));
1538   D->RParenLoc = ReadSourceLocation(Record, Idx);
1539 }
1540 
1541 void ASTDeclReader::VisitEmptyDecl(EmptyDecl *D) {
1542   VisitDecl(D);
1543 }
1544 
1545 std::pair<uint64_t, uint64_t>
1546 ASTDeclReader::VisitDeclContext(DeclContext *DC) {
1547   uint64_t LexicalOffset = Record[Idx++];
1548   uint64_t VisibleOffset = Record[Idx++];
1549   return std::make_pair(LexicalOffset, VisibleOffset);
1550 }
1551 
1552 template <typename T>
1553 ASTDeclReader::RedeclarableResult
1554 ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
1555   DeclID FirstDeclID = ReadDeclID(Record, Idx);
1556 
1557   // 0 indicates that this declaration was the only declaration of its entity,
1558   // and is used for space optimization.
1559   if (FirstDeclID == 0)
1560     FirstDeclID = ThisDeclID;
1561 
1562   T *FirstDecl = cast_or_null<T>(Reader.GetDecl(FirstDeclID));
1563   if (FirstDecl != D) {
1564     // We delay loading of the redeclaration chain to avoid deeply nested calls.
1565     // We temporarily set the first (canonical) declaration as the previous one
1566     // which is the one that matters and mark the real previous DeclID to be
1567     // loaded & attached later on.
1568     D->RedeclLink = Redeclarable<T>::PreviousDeclLink(FirstDecl);
1569   }
1570 
1571   // Note that this declaration has been deserialized.
1572   Reader.RedeclsDeserialized.insert(static_cast<T *>(D));
1573 
1574   // The result structure takes care to note that we need to load the
1575   // other declaration chains for this ID.
1576   return RedeclarableResult(Reader, FirstDeclID,
1577                             static_cast<T *>(D)->getKind());
1578 }
1579 
1580 /// \brief Attempts to merge the given declaration (D) with another declaration
1581 /// of the same entity.
1582 template<typename T>
1583 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *D,
1584                                       RedeclarableResult &Redecl) {
1585   // If modules are not available, there is no reason to perform this merge.
1586   if (!Reader.getContext().getLangOpts().Modules)
1587     return;
1588 
1589   if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D))) {
1590     if (T *Existing = ExistingRes) {
1591       T *ExistingCanon = Existing->getCanonicalDecl();
1592       T *DCanon = static_cast<T*>(D)->getCanonicalDecl();
1593       if (ExistingCanon != DCanon) {
1594         // Have our redeclaration link point back at the canonical declaration
1595         // of the existing declaration, so that this declaration has the
1596         // appropriate canonical declaration.
1597         D->RedeclLink = Redeclarable<T>::PreviousDeclLink(ExistingCanon);
1598 
1599         // When we merge a namespace, update its pointer to the first namespace.
1600         if (NamespaceDecl *Namespace
1601               = dyn_cast<NamespaceDecl>(static_cast<T*>(D))) {
1602           Namespace->AnonOrFirstNamespaceAndInline.setPointer(
1603             static_cast<NamespaceDecl *>(static_cast<void*>(ExistingCanon)));
1604         }
1605 
1606         // Don't introduce DCanon into the set of pending declaration chains.
1607         Redecl.suppress();
1608 
1609         // Introduce ExistingCanon into the set of pending declaration chains,
1610         // if in fact it came from a module file.
1611         if (ExistingCanon->isFromASTFile()) {
1612           GlobalDeclID ExistingCanonID = ExistingCanon->getGlobalID();
1613           assert(ExistingCanonID && "Unrecorded canonical declaration ID?");
1614           if (Reader.PendingDeclChainsKnown.insert(ExistingCanonID))
1615             Reader.PendingDeclChains.push_back(ExistingCanonID);
1616         }
1617 
1618         // If this declaration was the canonical declaration, make a note of
1619         // that. We accept the linear algorithm here because the number of
1620         // unique canonical declarations of an entity should always be tiny.
1621         if (DCanon == static_cast<T*>(D)) {
1622           SmallVectorImpl<DeclID> &Merged = Reader.MergedDecls[ExistingCanon];
1623           if (std::find(Merged.begin(), Merged.end(), Redecl.getFirstID())
1624                 == Merged.end())
1625             Merged.push_back(Redecl.getFirstID());
1626 
1627           // If ExistingCanon did not come from a module file, introduce the
1628           // first declaration that *does* come from a module file to the
1629           // set of pending declaration chains, so that we merge this
1630           // declaration.
1631           if (!ExistingCanon->isFromASTFile() &&
1632               Reader.PendingDeclChainsKnown.insert(Redecl.getFirstID()))
1633             Reader.PendingDeclChains.push_back(Merged[0]);
1634         }
1635       }
1636     }
1637   }
1638 }
1639 
1640 void ASTDeclReader::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
1641   VisitDecl(D);
1642   unsigned NumVars = D->varlist_size();
1643   SmallVector<DeclRefExpr *, 16> Vars;
1644   Vars.reserve(NumVars);
1645   for (unsigned i = 0; i != NumVars; ++i) {
1646     Vars.push_back(cast<DeclRefExpr>(Reader.ReadExpr(F)));
1647   }
1648   D->setVars(Vars);
1649 }
1650 
1651 //===----------------------------------------------------------------------===//
1652 // Attribute Reading
1653 //===----------------------------------------------------------------------===//
1654 
1655 /// \brief Reads attributes from the current stream position.
1656 void ASTReader::ReadAttributes(ModuleFile &F, AttrVec &Attrs,
1657                                const RecordData &Record, unsigned &Idx) {
1658   for (unsigned i = 0, e = Record[Idx++]; i != e; ++i) {
1659     Attr *New = 0;
1660     attr::Kind Kind = (attr::Kind)Record[Idx++];
1661     SourceRange Range = ReadSourceRange(F, Record, Idx);
1662 
1663 #include "clang/Serialization/AttrPCHRead.inc"
1664 
1665     assert(New && "Unable to decode attribute?");
1666     Attrs.push_back(New);
1667   }
1668 }
1669 
1670 //===----------------------------------------------------------------------===//
1671 // ASTReader Implementation
1672 //===----------------------------------------------------------------------===//
1673 
1674 /// \brief Note that we have loaded the declaration with the given
1675 /// Index.
1676 ///
1677 /// This routine notes that this declaration has already been loaded,
1678 /// so that future GetDecl calls will return this declaration rather
1679 /// than trying to load a new declaration.
1680 inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
1681   assert(!DeclsLoaded[Index] && "Decl loaded twice?");
1682   DeclsLoaded[Index] = D;
1683 }
1684 
1685 
1686 /// \brief Determine whether the consumer will be interested in seeing
1687 /// this declaration (via HandleTopLevelDecl).
1688 ///
1689 /// This routine should return true for anything that might affect
1690 /// code generation, e.g., inline function definitions, Objective-C
1691 /// declarations with metadata, etc.
1692 static bool isConsumerInterestedIn(Decl *D, bool HasBody) {
1693   // An ObjCMethodDecl is never considered as "interesting" because its
1694   // implementation container always is.
1695 
1696   if (isa<FileScopeAsmDecl>(D) ||
1697       isa<ObjCProtocolDecl>(D) ||
1698       isa<ObjCImplDecl>(D))
1699     return true;
1700   if (VarDecl *Var = dyn_cast<VarDecl>(D))
1701     return Var->isFileVarDecl() &&
1702            Var->isThisDeclarationADefinition() == VarDecl::Definition;
1703   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
1704     return Func->doesThisDeclarationHaveABody() || HasBody;
1705 
1706   return false;
1707 }
1708 
1709 /// \brief Get the correct cursor and offset for loading a declaration.
1710 ASTReader::RecordLocation
1711 ASTReader::DeclCursorForID(DeclID ID, unsigned &RawLocation) {
1712   // See if there's an override.
1713   DeclReplacementMap::iterator It = ReplacedDecls.find(ID);
1714   if (It != ReplacedDecls.end()) {
1715     RawLocation = It->second.RawLoc;
1716     return RecordLocation(It->second.Mod, It->second.Offset);
1717   }
1718 
1719   GlobalDeclMapType::iterator I = GlobalDeclMap.find(ID);
1720   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
1721   ModuleFile *M = I->second;
1722   const DeclOffset &
1723     DOffs =  M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS];
1724   RawLocation = DOffs.Loc;
1725   return RecordLocation(M, DOffs.BitOffset);
1726 }
1727 
1728 ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
1729   ContinuousRangeMap<uint64_t, ModuleFile*, 4>::iterator I
1730     = GlobalBitOffsetsMap.find(GlobalOffset);
1731 
1732   assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map");
1733   return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
1734 }
1735 
1736 uint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset) {
1737   return LocalOffset + M.GlobalBitOffset;
1738 }
1739 
1740 /// \brief Determine whether the two declarations refer to the same entity.
1741 static bool isSameEntity(NamedDecl *X, NamedDecl *Y) {
1742   assert(X->getDeclName() == Y->getDeclName() && "Declaration name mismatch!");
1743 
1744   if (X == Y)
1745     return true;
1746 
1747   // Must be in the same context.
1748   if (!X->getDeclContext()->getRedeclContext()->Equals(
1749          Y->getDeclContext()->getRedeclContext()))
1750     return false;
1751 
1752   // Two typedefs refer to the same entity if they have the same underlying
1753   // type.
1754   if (TypedefNameDecl *TypedefX = dyn_cast<TypedefNameDecl>(X))
1755     if (TypedefNameDecl *TypedefY = dyn_cast<TypedefNameDecl>(Y))
1756       return X->getASTContext().hasSameType(TypedefX->getUnderlyingType(),
1757                                             TypedefY->getUnderlyingType());
1758 
1759   // Must have the same kind.
1760   if (X->getKind() != Y->getKind())
1761     return false;
1762 
1763   // Objective-C classes and protocols with the same name always match.
1764   if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
1765     return true;
1766 
1767   // Compatible tags match.
1768   if (TagDecl *TagX = dyn_cast<TagDecl>(X)) {
1769     TagDecl *TagY = cast<TagDecl>(Y);
1770     return (TagX->getTagKind() == TagY->getTagKind()) ||
1771       ((TagX->getTagKind() == TTK_Struct || TagX->getTagKind() == TTK_Class ||
1772         TagX->getTagKind() == TTK_Interface) &&
1773        (TagY->getTagKind() == TTK_Struct || TagY->getTagKind() == TTK_Class ||
1774         TagY->getTagKind() == TTK_Interface));
1775   }
1776 
1777   // Functions with the same type and linkage match.
1778   // FIXME: This needs to cope with function templates, merging of
1779   //prototyped/non-prototyped functions, etc.
1780   if (FunctionDecl *FuncX = dyn_cast<FunctionDecl>(X)) {
1781     FunctionDecl *FuncY = cast<FunctionDecl>(Y);
1782     return (FuncX->getLinkage() == FuncY->getLinkage()) &&
1783       FuncX->getASTContext().hasSameType(FuncX->getType(), FuncY->getType());
1784   }
1785 
1786   // Variables with the same type and linkage match.
1787   if (VarDecl *VarX = dyn_cast<VarDecl>(X)) {
1788     VarDecl *VarY = cast<VarDecl>(Y);
1789     return (VarX->getLinkage() == VarY->getLinkage()) &&
1790       VarX->getASTContext().hasSameType(VarX->getType(), VarY->getType());
1791   }
1792 
1793   // Namespaces with the same name and inlinedness match.
1794   if (NamespaceDecl *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
1795     NamespaceDecl *NamespaceY = cast<NamespaceDecl>(Y);
1796     return NamespaceX->isInline() == NamespaceY->isInline();
1797   }
1798 
1799   // Identical template names and kinds match.
1800   if (isa<TemplateDecl>(X))
1801     return true;
1802 
1803   // FIXME: Many other cases to implement.
1804   return false;
1805 }
1806 
1807 ASTDeclReader::FindExistingResult::~FindExistingResult() {
1808   if (!AddResult || Existing)
1809     return;
1810 
1811   if (New->getDeclContext()->getRedeclContext()->isTranslationUnit()
1812       && Reader.SemaObj) {
1813     Reader.SemaObj->IdResolver.tryAddTopLevelDecl(New, New->getDeclName());
1814   } else {
1815     DeclContext *DC = New->getLexicalDeclContext();
1816     if (DC->isNamespace())
1817       DC->addDecl(New);
1818   }
1819 }
1820 
1821 ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) {
1822   DeclarationName Name = D->getDeclName();
1823   if (!Name) {
1824     // Don't bother trying to find unnamed declarations.
1825     FindExistingResult Result(Reader, D, /*Existing=*/0);
1826     Result.suppress();
1827     return Result;
1828   }
1829 
1830   DeclContext *DC = D->getDeclContext()->getRedeclContext();
1831   if (!DC->isFileContext())
1832     return FindExistingResult(Reader);
1833 
1834   if (DC->isTranslationUnit() && Reader.SemaObj) {
1835     IdentifierResolver &IdResolver = Reader.SemaObj->IdResolver;
1836 
1837     // Temporarily consider the identifier to be up-to-date. We don't want to
1838     // cause additional lookups here.
1839     class UpToDateIdentifierRAII {
1840       IdentifierInfo *II;
1841       bool WasOutToDate;
1842 
1843     public:
1844       explicit UpToDateIdentifierRAII(IdentifierInfo *II)
1845         : II(II), WasOutToDate(false)
1846       {
1847         if (II) {
1848           WasOutToDate = II->isOutOfDate();
1849           if (WasOutToDate)
1850             II->setOutOfDate(false);
1851         }
1852       }
1853 
1854       ~UpToDateIdentifierRAII() {
1855         if (WasOutToDate)
1856           II->setOutOfDate(true);
1857       }
1858     } UpToDate(Name.getAsIdentifierInfo());
1859 
1860     for (IdentifierResolver::iterator I = IdResolver.begin(Name),
1861                                    IEnd = IdResolver.end();
1862          I != IEnd; ++I) {
1863       if (isSameEntity(*I, D))
1864         return FindExistingResult(Reader, D, *I);
1865     }
1866   }
1867 
1868   if (DC->isNamespace()) {
1869     DeclContext::lookup_result R = DC->lookup(Name);
1870     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
1871          ++I) {
1872       if (isSameEntity(*I, D))
1873         return FindExistingResult(Reader, D, *I);
1874     }
1875   }
1876 
1877   return FindExistingResult(Reader, D, /*Existing=*/0);
1878 }
1879 
1880 void ASTDeclReader::attachPreviousDecl(Decl *D, Decl *previous) {
1881   assert(D && previous);
1882   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
1883     TD->RedeclLink.setNext(cast<TagDecl>(previous));
1884   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1885     FD->RedeclLink.setNext(cast<FunctionDecl>(previous));
1886   } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1887     VD->RedeclLink.setNext(cast<VarDecl>(previous));
1888   } else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
1889     TD->RedeclLink.setNext(cast<TypedefNameDecl>(previous));
1890   } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
1891     ID->RedeclLink.setNext(cast<ObjCInterfaceDecl>(previous));
1892   } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
1893     PD->RedeclLink.setNext(cast<ObjCProtocolDecl>(previous));
1894   } else if (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(D)) {
1895     ND->RedeclLink.setNext(cast<NamespaceDecl>(previous));
1896   } else {
1897     RedeclarableTemplateDecl *TD = cast<RedeclarableTemplateDecl>(D);
1898     TD->RedeclLink.setNext(cast<RedeclarableTemplateDecl>(previous));
1899   }
1900 }
1901 
1902 void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {
1903   assert(D && Latest);
1904   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
1905     TD->RedeclLink
1906       = Redeclarable<TagDecl>::LatestDeclLink(cast<TagDecl>(Latest));
1907   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
1908     FD->RedeclLink
1909       = Redeclarable<FunctionDecl>::LatestDeclLink(cast<FunctionDecl>(Latest));
1910   } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
1911     VD->RedeclLink
1912       = Redeclarable<VarDecl>::LatestDeclLink(cast<VarDecl>(Latest));
1913   } else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
1914     TD->RedeclLink
1915       = Redeclarable<TypedefNameDecl>::LatestDeclLink(
1916                                                 cast<TypedefNameDecl>(Latest));
1917   } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
1918     ID->RedeclLink
1919       = Redeclarable<ObjCInterfaceDecl>::LatestDeclLink(
1920                                               cast<ObjCInterfaceDecl>(Latest));
1921   } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
1922     PD->RedeclLink
1923       = Redeclarable<ObjCProtocolDecl>::LatestDeclLink(
1924                                                 cast<ObjCProtocolDecl>(Latest));
1925   } else if (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(D)) {
1926     ND->RedeclLink
1927       = Redeclarable<NamespaceDecl>::LatestDeclLink(
1928                                                    cast<NamespaceDecl>(Latest));
1929   } else {
1930     RedeclarableTemplateDecl *TD = cast<RedeclarableTemplateDecl>(D);
1931     TD->RedeclLink
1932       = Redeclarable<RedeclarableTemplateDecl>::LatestDeclLink(
1933                                         cast<RedeclarableTemplateDecl>(Latest));
1934   }
1935 }
1936 
1937 ASTReader::MergedDeclsMap::iterator
1938 ASTReader::combineStoredMergedDecls(Decl *Canon, GlobalDeclID CanonID) {
1939   // If we don't have any stored merged declarations, just look in the
1940   // merged declarations set.
1941   StoredMergedDeclsMap::iterator StoredPos = StoredMergedDecls.find(CanonID);
1942   if (StoredPos == StoredMergedDecls.end())
1943     return MergedDecls.find(Canon);
1944 
1945   // Append the stored merged declarations to the merged declarations set.
1946   MergedDeclsMap::iterator Pos = MergedDecls.find(Canon);
1947   if (Pos == MergedDecls.end())
1948     Pos = MergedDecls.insert(std::make_pair(Canon,
1949                                             SmallVector<DeclID, 2>())).first;
1950   Pos->second.append(StoredPos->second.begin(), StoredPos->second.end());
1951   StoredMergedDecls.erase(StoredPos);
1952 
1953   // Sort and uniquify the set of merged declarations.
1954   llvm::array_pod_sort(Pos->second.begin(), Pos->second.end());
1955   Pos->second.erase(std::unique(Pos->second.begin(), Pos->second.end()),
1956                     Pos->second.end());
1957   return Pos;
1958 }
1959 
1960 void ASTReader::loadAndAttachPreviousDecl(Decl *D, serialization::DeclID ID) {
1961   Decl *previous = GetDecl(ID);
1962   ASTDeclReader::attachPreviousDecl(D, previous);
1963 }
1964 
1965 /// \brief Read the declaration at the given offset from the AST file.
1966 Decl *ASTReader::ReadDeclRecord(DeclID ID) {
1967   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
1968   unsigned RawLocation = 0;
1969   RecordLocation Loc = DeclCursorForID(ID, RawLocation);
1970   llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
1971   // Keep track of where we are in the stream, then jump back there
1972   // after reading this declaration.
1973   SavedStreamPosition SavedPosition(DeclsCursor);
1974 
1975   ReadingKindTracker ReadingKind(Read_Decl, *this);
1976 
1977   // Note that we are loading a declaration record.
1978   Deserializing ADecl(this);
1979 
1980   DeclsCursor.JumpToBit(Loc.Offset);
1981   RecordData Record;
1982   unsigned Code = DeclsCursor.ReadCode();
1983   unsigned Idx = 0;
1984   ASTDeclReader Reader(*this, *Loc.F, ID, RawLocation, Record,Idx);
1985 
1986   Decl *D = 0;
1987   switch ((DeclCode)DeclsCursor.readRecord(Code, Record)) {
1988   case DECL_CONTEXT_LEXICAL:
1989   case DECL_CONTEXT_VISIBLE:
1990     llvm_unreachable("Record cannot be de-serialized with ReadDeclRecord");
1991   case DECL_TYPEDEF:
1992     D = TypedefDecl::CreateDeserialized(Context, ID);
1993     break;
1994   case DECL_TYPEALIAS:
1995     D = TypeAliasDecl::CreateDeserialized(Context, ID);
1996     break;
1997   case DECL_ENUM:
1998     D = EnumDecl::CreateDeserialized(Context, ID);
1999     break;
2000   case DECL_RECORD:
2001     D = RecordDecl::CreateDeserialized(Context, ID);
2002     break;
2003   case DECL_ENUM_CONSTANT:
2004     D = EnumConstantDecl::CreateDeserialized(Context, ID);
2005     break;
2006   case DECL_FUNCTION:
2007     D = FunctionDecl::CreateDeserialized(Context, ID);
2008     break;
2009   case DECL_LINKAGE_SPEC:
2010     D = LinkageSpecDecl::CreateDeserialized(Context, ID);
2011     break;
2012   case DECL_LABEL:
2013     D = LabelDecl::CreateDeserialized(Context, ID);
2014     break;
2015   case DECL_NAMESPACE:
2016     D = NamespaceDecl::CreateDeserialized(Context, ID);
2017     break;
2018   case DECL_NAMESPACE_ALIAS:
2019     D = NamespaceAliasDecl::CreateDeserialized(Context, ID);
2020     break;
2021   case DECL_USING:
2022     D = UsingDecl::CreateDeserialized(Context, ID);
2023     break;
2024   case DECL_USING_SHADOW:
2025     D = UsingShadowDecl::CreateDeserialized(Context, ID);
2026     break;
2027   case DECL_USING_DIRECTIVE:
2028     D = UsingDirectiveDecl::CreateDeserialized(Context, ID);
2029     break;
2030   case DECL_UNRESOLVED_USING_VALUE:
2031     D = UnresolvedUsingValueDecl::CreateDeserialized(Context, ID);
2032     break;
2033   case DECL_UNRESOLVED_USING_TYPENAME:
2034     D = UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID);
2035     break;
2036   case DECL_CXX_RECORD:
2037     D = CXXRecordDecl::CreateDeserialized(Context, ID);
2038     break;
2039   case DECL_CXX_METHOD:
2040     D = CXXMethodDecl::CreateDeserialized(Context, ID);
2041     break;
2042   case DECL_CXX_CONSTRUCTOR:
2043     D = CXXConstructorDecl::CreateDeserialized(Context, ID);
2044     break;
2045   case DECL_CXX_DESTRUCTOR:
2046     D = CXXDestructorDecl::CreateDeserialized(Context, ID);
2047     break;
2048   case DECL_CXX_CONVERSION:
2049     D = CXXConversionDecl::CreateDeserialized(Context, ID);
2050     break;
2051   case DECL_ACCESS_SPEC:
2052     D = AccessSpecDecl::CreateDeserialized(Context, ID);
2053     break;
2054   case DECL_FRIEND:
2055     D = FriendDecl::CreateDeserialized(Context, ID, Record[Idx++]);
2056     break;
2057   case DECL_FRIEND_TEMPLATE:
2058     D = FriendTemplateDecl::CreateDeserialized(Context, ID);
2059     break;
2060   case DECL_CLASS_TEMPLATE:
2061     D = ClassTemplateDecl::CreateDeserialized(Context, ID);
2062     break;
2063   case DECL_CLASS_TEMPLATE_SPECIALIZATION:
2064     D = ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID);
2065     break;
2066   case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
2067     D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
2068     break;
2069   case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
2070     D = ClassScopeFunctionSpecializationDecl::CreateDeserialized(Context, ID);
2071     break;
2072   case DECL_FUNCTION_TEMPLATE:
2073     D = FunctionTemplateDecl::CreateDeserialized(Context, ID);
2074     break;
2075   case DECL_TEMPLATE_TYPE_PARM:
2076     D = TemplateTypeParmDecl::CreateDeserialized(Context, ID);
2077     break;
2078   case DECL_NON_TYPE_TEMPLATE_PARM:
2079     D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID);
2080     break;
2081   case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK:
2082     D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID, Record[Idx++]);
2083     break;
2084   case DECL_TEMPLATE_TEMPLATE_PARM:
2085     D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID);
2086     break;
2087   case DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK:
2088     D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID,
2089                                                      Record[Idx++]);
2090     break;
2091   case DECL_TYPE_ALIAS_TEMPLATE:
2092     D = TypeAliasTemplateDecl::CreateDeserialized(Context, ID);
2093     break;
2094   case DECL_STATIC_ASSERT:
2095     D = StaticAssertDecl::CreateDeserialized(Context, ID);
2096     break;
2097   case DECL_OBJC_METHOD:
2098     D = ObjCMethodDecl::CreateDeserialized(Context, ID);
2099     break;
2100   case DECL_OBJC_INTERFACE:
2101     D = ObjCInterfaceDecl::CreateDeserialized(Context, ID);
2102     break;
2103   case DECL_OBJC_IVAR:
2104     D = ObjCIvarDecl::CreateDeserialized(Context, ID);
2105     break;
2106   case DECL_OBJC_PROTOCOL:
2107     D = ObjCProtocolDecl::CreateDeserialized(Context, ID);
2108     break;
2109   case DECL_OBJC_AT_DEFS_FIELD:
2110     D = ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID);
2111     break;
2112   case DECL_OBJC_CATEGORY:
2113     D = ObjCCategoryDecl::CreateDeserialized(Context, ID);
2114     break;
2115   case DECL_OBJC_CATEGORY_IMPL:
2116     D = ObjCCategoryImplDecl::CreateDeserialized(Context, ID);
2117     break;
2118   case DECL_OBJC_IMPLEMENTATION:
2119     D = ObjCImplementationDecl::CreateDeserialized(Context, ID);
2120     break;
2121   case DECL_OBJC_COMPATIBLE_ALIAS:
2122     D = ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID);
2123     break;
2124   case DECL_OBJC_PROPERTY:
2125     D = ObjCPropertyDecl::CreateDeserialized(Context, ID);
2126     break;
2127   case DECL_OBJC_PROPERTY_IMPL:
2128     D = ObjCPropertyImplDecl::CreateDeserialized(Context, ID);
2129     break;
2130   case DECL_FIELD:
2131     D = FieldDecl::CreateDeserialized(Context, ID);
2132     break;
2133   case DECL_INDIRECTFIELD:
2134     D = IndirectFieldDecl::CreateDeserialized(Context, ID);
2135     break;
2136   case DECL_VAR:
2137     D = VarDecl::CreateDeserialized(Context, ID);
2138     break;
2139   case DECL_IMPLICIT_PARAM:
2140     D = ImplicitParamDecl::CreateDeserialized(Context, ID);
2141     break;
2142   case DECL_PARM_VAR:
2143     D = ParmVarDecl::CreateDeserialized(Context, ID);
2144     break;
2145   case DECL_FILE_SCOPE_ASM:
2146     D = FileScopeAsmDecl::CreateDeserialized(Context, ID);
2147     break;
2148   case DECL_BLOCK:
2149     D = BlockDecl::CreateDeserialized(Context, ID);
2150     break;
2151   case DECL_MS_PROPERTY:
2152     D = MSPropertyDecl::CreateDeserialized(Context, ID);
2153     break;
2154   case DECL_CAPTURED:
2155     llvm_unreachable("not implemented yet");
2156     break;
2157   case DECL_CXX_BASE_SPECIFIERS:
2158     Error("attempt to read a C++ base-specifier record as a declaration");
2159     return 0;
2160   case DECL_IMPORT:
2161     // Note: last entry of the ImportDecl record is the number of stored source
2162     // locations.
2163     D = ImportDecl::CreateDeserialized(Context, ID, Record.back());
2164     break;
2165   case DECL_OMP_THREADPRIVATE:
2166     D = OMPThreadPrivateDecl::CreateDeserialized(Context, ID, Record[Idx++]);
2167     break;
2168   case DECL_EMPTY:
2169     D = EmptyDecl::CreateDeserialized(Context, ID);
2170     break;
2171   }
2172 
2173   assert(D && "Unknown declaration reading AST file");
2174   LoadedDecl(Index, D);
2175   // Set the DeclContext before doing any deserialization, to make sure internal
2176   // calls to Decl::getASTContext() by Decl's methods will find the
2177   // TranslationUnitDecl without crashing.
2178   D->setDeclContext(Context.getTranslationUnitDecl());
2179   Reader.Visit(D);
2180 
2181   // If this declaration is also a declaration context, get the
2182   // offsets for its tables of lexical and visible declarations.
2183   if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
2184     // FIXME: This should really be
2185     //     DeclContext *LookupDC = DC->getPrimaryContext();
2186     // but that can walk the redeclaration chain, which might not work yet.
2187     DeclContext *LookupDC = DC;
2188     if (isa<NamespaceDecl>(DC))
2189       LookupDC = DC->getPrimaryContext();
2190     std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
2191     if (Offsets.first || Offsets.second) {
2192       if (Offsets.first != 0)
2193         DC->setHasExternalLexicalStorage(true);
2194       if (Offsets.second != 0)
2195         LookupDC->setHasExternalVisibleStorage(true);
2196       if (ReadDeclContextStorage(*Loc.F, DeclsCursor, Offsets,
2197                                  Loc.F->DeclContextInfos[DC]))
2198         return 0;
2199     }
2200 
2201     // Now add the pending visible updates for this decl context, if it has any.
2202     DeclContextVisibleUpdatesPending::iterator I =
2203         PendingVisibleUpdates.find(ID);
2204     if (I != PendingVisibleUpdates.end()) {
2205       // There are updates. This means the context has external visible
2206       // storage, even if the original stored version didn't.
2207       LookupDC->setHasExternalVisibleStorage(true);
2208       DeclContextVisibleUpdates &U = I->second;
2209       for (DeclContextVisibleUpdates::iterator UI = U.begin(), UE = U.end();
2210            UI != UE; ++UI) {
2211         DeclContextInfo &Info = UI->second->DeclContextInfos[DC];
2212         delete Info.NameLookupTableData;
2213         Info.NameLookupTableData = UI->first;
2214       }
2215       PendingVisibleUpdates.erase(I);
2216     }
2217   }
2218   assert(Idx == Record.size());
2219 
2220   // Load any relevant update records.
2221   loadDeclUpdateRecords(ID, D);
2222 
2223   // Load the categories after recursive loading is finished.
2224   if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2225     if (Class->isThisDeclarationADefinition())
2226       loadObjCCategories(ID, Class);
2227 
2228   // If we have deserialized a declaration that has a definition the
2229   // AST consumer might need to know about, queue it.
2230   // We don't pass it to the consumer immediately because we may be in recursive
2231   // loading, and some declarations may still be initializing.
2232   if (isConsumerInterestedIn(D, Reader.hasPendingBody()))
2233     InterestingDecls.push_back(D);
2234 
2235   return D;
2236 }
2237 
2238 void ASTReader::loadDeclUpdateRecords(serialization::DeclID ID, Decl *D) {
2239   // The declaration may have been modified by files later in the chain.
2240   // If this is the case, read the record containing the updates from each file
2241   // and pass it to ASTDeclReader to make the modifications.
2242   DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
2243   if (UpdI != DeclUpdateOffsets.end()) {
2244     FileOffsetsTy &UpdateOffsets = UpdI->second;
2245     for (FileOffsetsTy::iterator
2246          I = UpdateOffsets.begin(), E = UpdateOffsets.end(); I != E; ++I) {
2247       ModuleFile *F = I->first;
2248       uint64_t Offset = I->second;
2249       llvm::BitstreamCursor &Cursor = F->DeclsCursor;
2250       SavedStreamPosition SavedPosition(Cursor);
2251       Cursor.JumpToBit(Offset);
2252       RecordData Record;
2253       unsigned Code = Cursor.ReadCode();
2254       unsigned RecCode = Cursor.readRecord(Code, Record);
2255       (void)RecCode;
2256       assert(RecCode == DECL_UPDATES && "Expected DECL_UPDATES record!");
2257 
2258       unsigned Idx = 0;
2259       ASTDeclReader Reader(*this, *F, ID, 0, Record, Idx);
2260       Reader.UpdateDecl(D, *F, Record);
2261     }
2262   }
2263 }
2264 
2265 namespace {
2266   struct CompareLocalRedeclarationsInfoToID {
2267     bool operator()(const LocalRedeclarationsInfo &X, DeclID Y) {
2268       return X.FirstID < Y;
2269     }
2270 
2271     bool operator()(DeclID X, const LocalRedeclarationsInfo &Y) {
2272       return X < Y.FirstID;
2273     }
2274 
2275     bool operator()(const LocalRedeclarationsInfo &X,
2276                     const LocalRedeclarationsInfo &Y) {
2277       return X.FirstID < Y.FirstID;
2278     }
2279     bool operator()(DeclID X, DeclID Y) {
2280       return X < Y;
2281     }
2282   };
2283 
2284   /// \brief Module visitor class that finds all of the redeclarations of a
2285   ///
2286   class RedeclChainVisitor {
2287     ASTReader &Reader;
2288     SmallVectorImpl<DeclID> &SearchDecls;
2289     llvm::SmallPtrSet<Decl *, 16> &Deserialized;
2290     GlobalDeclID CanonID;
2291     SmallVector<Decl *, 4> Chain;
2292 
2293   public:
2294     RedeclChainVisitor(ASTReader &Reader, SmallVectorImpl<DeclID> &SearchDecls,
2295                        llvm::SmallPtrSet<Decl *, 16> &Deserialized,
2296                        GlobalDeclID CanonID)
2297       : Reader(Reader), SearchDecls(SearchDecls), Deserialized(Deserialized),
2298         CanonID(CanonID) {
2299       for (unsigned I = 0, N = SearchDecls.size(); I != N; ++I)
2300         addToChain(Reader.GetDecl(SearchDecls[I]));
2301     }
2302 
2303     static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
2304       if (Preorder)
2305         return false;
2306 
2307       return static_cast<RedeclChainVisitor *>(UserData)->visit(M);
2308     }
2309 
2310     void addToChain(Decl *D) {
2311       if (!D)
2312         return;
2313 
2314       if (Deserialized.erase(D))
2315         Chain.push_back(D);
2316     }
2317 
2318     void searchForID(ModuleFile &M, GlobalDeclID GlobalID) {
2319       // Map global ID of the first declaration down to the local ID
2320       // used in this module file.
2321       DeclID ID = Reader.mapGlobalIDToModuleFileGlobalID(M, GlobalID);
2322       if (!ID)
2323         return;
2324 
2325       // Perform a binary search to find the local redeclarations for this
2326       // declaration (if any).
2327       const LocalRedeclarationsInfo *Result
2328         = std::lower_bound(M.RedeclarationsMap,
2329                            M.RedeclarationsMap + M.LocalNumRedeclarationsInMap,
2330                            ID, CompareLocalRedeclarationsInfoToID());
2331       if (Result == M.RedeclarationsMap + M.LocalNumRedeclarationsInMap ||
2332           Result->FirstID != ID) {
2333         // If we have a previously-canonical singleton declaration that was
2334         // merged into another redeclaration chain, create a trivial chain
2335         // for this single declaration so that it will get wired into the
2336         // complete redeclaration chain.
2337         if (GlobalID != CanonID &&
2338             GlobalID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
2339             GlobalID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls) {
2340           addToChain(Reader.GetDecl(GlobalID));
2341         }
2342 
2343         return;
2344       }
2345 
2346       // Dig out all of the redeclarations.
2347       unsigned Offset = Result->Offset;
2348       unsigned N = M.RedeclarationChains[Offset];
2349       M.RedeclarationChains[Offset++] = 0; // Don't try to deserialize again
2350       for (unsigned I = 0; I != N; ++I)
2351         addToChain(Reader.GetLocalDecl(M, M.RedeclarationChains[Offset++]));
2352     }
2353 
2354     bool visit(ModuleFile &M) {
2355       // Visit each of the declarations.
2356       for (unsigned I = 0, N = SearchDecls.size(); I != N; ++I)
2357         searchForID(M, SearchDecls[I]);
2358       return false;
2359     }
2360 
2361     ArrayRef<Decl *> getChain() const {
2362       return Chain;
2363     }
2364   };
2365 }
2366 
2367 void ASTReader::loadPendingDeclChain(serialization::GlobalDeclID ID) {
2368   Decl *D = GetDecl(ID);
2369   Decl *CanonDecl = D->getCanonicalDecl();
2370 
2371   // Determine the set of declaration IDs we'll be searching for.
2372   SmallVector<DeclID, 1> SearchDecls;
2373   GlobalDeclID CanonID = 0;
2374   if (D == CanonDecl) {
2375     SearchDecls.push_back(ID); // Always first.
2376     CanonID = ID;
2377   }
2378   MergedDeclsMap::iterator MergedPos = combineStoredMergedDecls(CanonDecl, ID);
2379   if (MergedPos != MergedDecls.end())
2380     SearchDecls.append(MergedPos->second.begin(), MergedPos->second.end());
2381 
2382   // Build up the list of redeclarations.
2383   RedeclChainVisitor Visitor(*this, SearchDecls, RedeclsDeserialized, CanonID);
2384   ModuleMgr.visitDepthFirst(&RedeclChainVisitor::visit, &Visitor);
2385 
2386   // Retrieve the chains.
2387   ArrayRef<Decl *> Chain = Visitor.getChain();
2388   if (Chain.empty())
2389     return;
2390 
2391   // Hook up the chains.
2392   Decl *MostRecent = CanonDecl->getMostRecentDecl();
2393   for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2394     if (Chain[I] == CanonDecl)
2395       continue;
2396 
2397     ASTDeclReader::attachPreviousDecl(Chain[I], MostRecent);
2398     MostRecent = Chain[I];
2399   }
2400 
2401   ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent);
2402 }
2403 
2404 namespace {
2405   struct CompareObjCCategoriesInfo {
2406     bool operator()(const ObjCCategoriesInfo &X, DeclID Y) {
2407       return X.DefinitionID < Y;
2408     }
2409 
2410     bool operator()(DeclID X, const ObjCCategoriesInfo &Y) {
2411       return X < Y.DefinitionID;
2412     }
2413 
2414     bool operator()(const ObjCCategoriesInfo &X,
2415                     const ObjCCategoriesInfo &Y) {
2416       return X.DefinitionID < Y.DefinitionID;
2417     }
2418     bool operator()(DeclID X, DeclID Y) {
2419       return X < Y;
2420     }
2421   };
2422 
2423   /// \brief Given an ObjC interface, goes through the modules and links to the
2424   /// interface all the categories for it.
2425   class ObjCCategoriesVisitor {
2426     ASTReader &Reader;
2427     serialization::GlobalDeclID InterfaceID;
2428     ObjCInterfaceDecl *Interface;
2429     llvm::SmallPtrSet<ObjCCategoryDecl *, 16> &Deserialized;
2430     unsigned PreviousGeneration;
2431     ObjCCategoryDecl *Tail;
2432     llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
2433 
2434     void add(ObjCCategoryDecl *Cat) {
2435       // Only process each category once.
2436       if (!Deserialized.erase(Cat))
2437         return;
2438 
2439       // Check for duplicate categories.
2440       if (Cat->getDeclName()) {
2441         ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
2442         if (Existing &&
2443             Reader.getOwningModuleFile(Existing)
2444                                           != Reader.getOwningModuleFile(Cat)) {
2445           // FIXME: We should not warn for duplicates in diamond:
2446           //
2447           //   MT     //
2448           //  /  \    //
2449           // ML  MR   //
2450           //  \  /    //
2451           //   MB     //
2452           //
2453           // If there are duplicates in ML/MR, there will be warning when
2454           // creating MB *and* when importing MB. We should not warn when
2455           // importing.
2456           Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
2457             << Interface->getDeclName() << Cat->getDeclName();
2458           Reader.Diag(Existing->getLocation(), diag::note_previous_definition);
2459         } else if (!Existing) {
2460           // Record this category.
2461           Existing = Cat;
2462         }
2463       }
2464 
2465       // Add this category to the end of the chain.
2466       if (Tail)
2467         ASTDeclReader::setNextObjCCategory(Tail, Cat);
2468       else
2469         Interface->setCategoryListRaw(Cat);
2470       Tail = Cat;
2471     }
2472 
2473   public:
2474     ObjCCategoriesVisitor(ASTReader &Reader,
2475                           serialization::GlobalDeclID InterfaceID,
2476                           ObjCInterfaceDecl *Interface,
2477                         llvm::SmallPtrSet<ObjCCategoryDecl *, 16> &Deserialized,
2478                           unsigned PreviousGeneration)
2479       : Reader(Reader), InterfaceID(InterfaceID), Interface(Interface),
2480         Deserialized(Deserialized), PreviousGeneration(PreviousGeneration),
2481         Tail(0)
2482     {
2483       // Populate the name -> category map with the set of known categories.
2484       for (ObjCInterfaceDecl::known_categories_iterator
2485              Cat = Interface->known_categories_begin(),
2486              CatEnd = Interface->known_categories_end();
2487            Cat != CatEnd; ++Cat) {
2488         if (Cat->getDeclName())
2489           NameCategoryMap[Cat->getDeclName()] = *Cat;
2490 
2491         // Keep track of the tail of the category list.
2492         Tail = *Cat;
2493       }
2494     }
2495 
2496     static bool visit(ModuleFile &M, void *UserData) {
2497       return static_cast<ObjCCategoriesVisitor *>(UserData)->visit(M);
2498     }
2499 
2500     bool visit(ModuleFile &M) {
2501       // If we've loaded all of the category information we care about from
2502       // this module file, we're done.
2503       if (M.Generation <= PreviousGeneration)
2504         return true;
2505 
2506       // Map global ID of the definition down to the local ID used in this
2507       // module file. If there is no such mapping, we'll find nothing here
2508       // (or in any module it imports).
2509       DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID);
2510       if (!LocalID)
2511         return true;
2512 
2513       // Perform a binary search to find the local redeclarations for this
2514       // declaration (if any).
2515       const ObjCCategoriesInfo *Result
2516         = std::lower_bound(M.ObjCCategoriesMap,
2517                            M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap,
2518                            LocalID, CompareObjCCategoriesInfo());
2519       if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap ||
2520           Result->DefinitionID != LocalID) {
2521         // We didn't find anything. If the class definition is in this module
2522         // file, then the module files it depends on cannot have any categories,
2523         // so suppress further lookup.
2524         return Reader.isDeclIDFromModule(InterfaceID, M);
2525       }
2526 
2527       // We found something. Dig out all of the categories.
2528       unsigned Offset = Result->Offset;
2529       unsigned N = M.ObjCCategories[Offset];
2530       M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again
2531       for (unsigned I = 0; I != N; ++I)
2532         add(cast_or_null<ObjCCategoryDecl>(
2533               Reader.GetLocalDecl(M, M.ObjCCategories[Offset++])));
2534       return true;
2535     }
2536   };
2537 }
2538 
2539 void ASTReader::loadObjCCategories(serialization::GlobalDeclID ID,
2540                                    ObjCInterfaceDecl *D,
2541                                    unsigned PreviousGeneration) {
2542   ObjCCategoriesVisitor Visitor(*this, ID, D, CategoriesDeserialized,
2543                                 PreviousGeneration);
2544   ModuleMgr.visit(ObjCCategoriesVisitor::visit, &Visitor);
2545 }
2546 
2547 void ASTDeclReader::UpdateDecl(Decl *D, ModuleFile &ModuleFile,
2548                                const RecordData &Record) {
2549   unsigned Idx = 0;
2550   while (Idx < Record.size()) {
2551     switch ((DeclUpdateKind)Record[Idx++]) {
2552     case UPD_CXX_ADDED_IMPLICIT_MEMBER:
2553       cast<CXXRecordDecl>(D)->addedMember(Reader.ReadDecl(ModuleFile, Record, Idx));
2554       break;
2555 
2556     case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
2557       // It will be added to the template's specializations set when loaded.
2558       (void)Reader.ReadDecl(ModuleFile, Record, Idx);
2559       break;
2560 
2561     case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
2562       NamespaceDecl *Anon
2563         = Reader.ReadDeclAs<NamespaceDecl>(ModuleFile, Record, Idx);
2564 
2565       // Each module has its own anonymous namespace, which is disjoint from
2566       // any other module's anonymous namespaces, so don't attach the anonymous
2567       // namespace at all.
2568       if (ModuleFile.Kind != MK_Module) {
2569         if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(D))
2570           TU->setAnonymousNamespace(Anon);
2571         else
2572           cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon);
2573       }
2574       break;
2575     }
2576 
2577     case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
2578       cast<VarDecl>(D)->getMemberSpecializationInfo()->setPointOfInstantiation(
2579           Reader.ReadSourceLocation(ModuleFile, Record, Idx));
2580       break;
2581     }
2582   }
2583 }
2584