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