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->setIsUsed(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 = ReadDeclID(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   // Lazily load the key function to avoid deserializing every method so we can
1280   // compute it.
1281   if (D->IsCompleteDefinition) {
1282     if (DeclID KeyFn = ReadDeclID(Record, Idx))
1283       C.KeyFunctions[D] = KeyFn;
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 = ReadDeclID(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 /// TODO: Unify with ClassTemplateDecl version?
1444 ///       May require unifying ClassTemplateDecl and
1445 ///        VarTemplateDecl beyond TemplateDecl...
1446 void ASTDeclReader::VisitVarTemplateDecl(VarTemplateDecl *D) {
1447   RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
1448 
1449   if (ThisDeclID == Redecl.getFirstID()) {
1450     // This VarTemplateDecl owns a CommonPtr; read it to keep track of all of
1451     // the specializations.
1452     SmallVector<serialization::DeclID, 2> SpecIDs;
1453     SpecIDs.push_back(0);
1454 
1455     // Specializations.
1456     unsigned Size = Record[Idx++];
1457     SpecIDs[0] += Size;
1458     for (unsigned I = 0; I != Size; ++I)
1459       SpecIDs.push_back(ReadDeclID(Record, Idx));
1460 
1461     // Partial specializations.
1462     Size = Record[Idx++];
1463     SpecIDs[0] += Size;
1464     for (unsigned I = 0; I != Size; ++I)
1465       SpecIDs.push_back(ReadDeclID(Record, Idx));
1466 
1467     VarTemplateDecl::Common *CommonPtr = D->getCommonPtr();
1468     if (SpecIDs[0]) {
1469       typedef serialization::DeclID DeclID;
1470 
1471       // FIXME: Append specializations!
1472       CommonPtr->LazySpecializations =
1473           new (Reader.getContext()) DeclID[SpecIDs.size()];
1474       memcpy(CommonPtr->LazySpecializations, SpecIDs.data(),
1475              SpecIDs.size() * sizeof(DeclID));
1476     }
1477   }
1478 }
1479 
1480 ASTDeclReader::RedeclarableResult
1481 ASTDeclReader::VisitClassTemplateSpecializationDeclImpl(
1482     ClassTemplateSpecializationDecl *D) {
1483   RedeclarableResult Redecl = VisitCXXRecordDeclImpl(D);
1484 
1485   ASTContext &C = Reader.getContext();
1486   if (Decl *InstD = ReadDecl(Record, Idx)) {
1487     if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
1488       D->SpecializedTemplate = CTD;
1489     } else {
1490       SmallVector<TemplateArgument, 8> TemplArgs;
1491       Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1492       TemplateArgumentList *ArgList
1493         = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
1494                                            TemplArgs.size());
1495       ClassTemplateSpecializationDecl::SpecializedPartialSpecialization *PS
1496           = new (C) ClassTemplateSpecializationDecl::
1497                                              SpecializedPartialSpecialization();
1498       PS->PartialSpecialization
1499           = cast<ClassTemplatePartialSpecializationDecl>(InstD);
1500       PS->TemplateArgs = ArgList;
1501       D->SpecializedTemplate = PS;
1502     }
1503   }
1504 
1505   // Explicit info.
1506   if (TypeSourceInfo *TyInfo = GetTypeSourceInfo(Record, Idx)) {
1507     ClassTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo
1508         = new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
1509     ExplicitInfo->TypeAsWritten = TyInfo;
1510     ExplicitInfo->ExternLoc = ReadSourceLocation(Record, Idx);
1511     ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation(Record, Idx);
1512     D->ExplicitInfo = ExplicitInfo;
1513   }
1514 
1515   SmallVector<TemplateArgument, 8> TemplArgs;
1516   Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1517   D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs.data(),
1518                                                      TemplArgs.size());
1519   D->PointOfInstantiation = ReadSourceLocation(Record, Idx);
1520   D->SpecializationKind = (TemplateSpecializationKind)Record[Idx++];
1521 
1522   bool writtenAsCanonicalDecl = Record[Idx++];
1523   if (writtenAsCanonicalDecl) {
1524     ClassTemplateDecl *CanonPattern = ReadDeclAs<ClassTemplateDecl>(Record,Idx);
1525     if (D->isCanonicalDecl()) { // It's kept in the folding set.
1526       if (ClassTemplatePartialSpecializationDecl *Partial =
1527               dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
1528         CanonPattern->getCommonPtr()->PartialSpecializations
1529             .GetOrInsertNode(Partial);
1530       } else {
1531         CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
1532       }
1533     }
1534   }
1535 
1536   return Redecl;
1537 }
1538 
1539 void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
1540                                     ClassTemplatePartialSpecializationDecl *D) {
1541   RedeclarableResult Redecl = VisitClassTemplateSpecializationDeclImpl(D);
1542 
1543   D->TemplateParams = Reader.ReadTemplateParameterList(F, Record, Idx);
1544   D->ArgsAsWritten = Reader.ReadASTTemplateArgumentListInfo(F, Record, Idx);
1545 
1546   // These are read/set from/to the first declaration.
1547   if (ThisDeclID == Redecl.getFirstID()) {
1548     D->InstantiatedFromMember.setPointer(
1549       ReadDeclAs<ClassTemplatePartialSpecializationDecl>(Record, Idx));
1550     D->InstantiatedFromMember.setInt(Record[Idx++]);
1551   }
1552 }
1553 
1554 void ASTDeclReader::VisitClassScopeFunctionSpecializationDecl(
1555                                     ClassScopeFunctionSpecializationDecl *D) {
1556   VisitDecl(D);
1557   D->Specialization = ReadDeclAs<CXXMethodDecl>(Record, Idx);
1558 }
1559 
1560 void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
1561   RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
1562 
1563   if (ThisDeclID == Redecl.getFirstID()) {
1564     // This FunctionTemplateDecl owns a CommonPtr; read it.
1565 
1566     // Read the function specialization declaration IDs. The specializations
1567     // themselves will be loaded if they're needed.
1568     if (unsigned NumSpecs = Record[Idx++]) {
1569       // FIXME: Append specializations!
1570       FunctionTemplateDecl::Common *CommonPtr = D->getCommonPtr();
1571       CommonPtr->LazySpecializations = new (Reader.getContext())
1572           serialization::DeclID[NumSpecs + 1];
1573       CommonPtr->LazySpecializations[0] = NumSpecs;
1574       for (unsigned I = 0; I != NumSpecs; ++I)
1575         CommonPtr->LazySpecializations[I + 1] = ReadDeclID(Record, Idx);
1576     }
1577   }
1578 }
1579 
1580 /// TODO: Unify with ClassTemplateSpecializationDecl version?
1581 ///       May require unifying ClassTemplate(Partial)SpecializationDecl and
1582 ///        VarTemplate(Partial)SpecializationDecl with a new data
1583 ///        structure Template(Partial)SpecializationDecl, and
1584 ///        using Template(Partial)SpecializationDecl as input type.
1585 ASTDeclReader::RedeclarableResult
1586 ASTDeclReader::VisitVarTemplateSpecializationDeclImpl(
1587     VarTemplateSpecializationDecl *D) {
1588   RedeclarableResult Redecl = VisitVarDeclImpl(D);
1589 
1590   ASTContext &C = Reader.getContext();
1591   if (Decl *InstD = ReadDecl(Record, Idx)) {
1592     if (VarTemplateDecl *VTD = dyn_cast<VarTemplateDecl>(InstD)) {
1593       D->SpecializedTemplate = VTD;
1594     } else {
1595       SmallVector<TemplateArgument, 8> TemplArgs;
1596       Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1597       TemplateArgumentList *ArgList = TemplateArgumentList::CreateCopy(
1598           C, TemplArgs.data(), TemplArgs.size());
1599       VarTemplateSpecializationDecl::SpecializedPartialSpecialization *PS =
1600           new (C)
1601           VarTemplateSpecializationDecl::SpecializedPartialSpecialization();
1602       PS->PartialSpecialization =
1603           cast<VarTemplatePartialSpecializationDecl>(InstD);
1604       PS->TemplateArgs = ArgList;
1605       D->SpecializedTemplate = PS;
1606     }
1607   }
1608 
1609   // Explicit info.
1610   if (TypeSourceInfo *TyInfo = GetTypeSourceInfo(Record, Idx)) {
1611     VarTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo =
1612         new (C) VarTemplateSpecializationDecl::ExplicitSpecializationInfo;
1613     ExplicitInfo->TypeAsWritten = TyInfo;
1614     ExplicitInfo->ExternLoc = ReadSourceLocation(Record, Idx);
1615     ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation(Record, Idx);
1616     D->ExplicitInfo = ExplicitInfo;
1617   }
1618 
1619   SmallVector<TemplateArgument, 8> TemplArgs;
1620   Reader.ReadTemplateArgumentList(TemplArgs, F, Record, Idx);
1621   D->TemplateArgs =
1622       TemplateArgumentList::CreateCopy(C, TemplArgs.data(), TemplArgs.size());
1623   D->PointOfInstantiation = ReadSourceLocation(Record, Idx);
1624   D->SpecializationKind = (TemplateSpecializationKind)Record[Idx++];
1625 
1626   bool writtenAsCanonicalDecl = Record[Idx++];
1627   if (writtenAsCanonicalDecl) {
1628     VarTemplateDecl *CanonPattern = ReadDeclAs<VarTemplateDecl>(Record, Idx);
1629     if (D->isCanonicalDecl()) { // It's kept in the folding set.
1630       if (VarTemplatePartialSpecializationDecl *Partial =
1631               dyn_cast<VarTemplatePartialSpecializationDecl>(D)) {
1632         CanonPattern->getCommonPtr()->PartialSpecializations
1633             .GetOrInsertNode(Partial);
1634       } else {
1635         CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
1636       }
1637     }
1638   }
1639 
1640   return Redecl;
1641 }
1642 
1643 /// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
1644 ///       May require unifying ClassTemplate(Partial)SpecializationDecl and
1645 ///        VarTemplate(Partial)SpecializationDecl with a new data
1646 ///        structure Template(Partial)SpecializationDecl, and
1647 ///        using Template(Partial)SpecializationDecl as input type.
1648 void ASTDeclReader::VisitVarTemplatePartialSpecializationDecl(
1649     VarTemplatePartialSpecializationDecl *D) {
1650   RedeclarableResult Redecl = VisitVarTemplateSpecializationDeclImpl(D);
1651 
1652   D->TemplateParams = Reader.ReadTemplateParameterList(F, Record, Idx);
1653   D->ArgsAsWritten = Reader.ReadASTTemplateArgumentListInfo(F, Record, Idx);
1654 
1655   // These are read/set from/to the first declaration.
1656   if (ThisDeclID == Redecl.getFirstID()) {
1657     D->InstantiatedFromMember.setPointer(
1658         ReadDeclAs<VarTemplatePartialSpecializationDecl>(Record, Idx));
1659     D->InstantiatedFromMember.setInt(Record[Idx++]);
1660   }
1661 }
1662 
1663 void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
1664   VisitTypeDecl(D);
1665 
1666   D->setDeclaredWithTypename(Record[Idx++]);
1667 
1668   bool Inherited = Record[Idx++];
1669   TypeSourceInfo *DefArg = GetTypeSourceInfo(Record, Idx);
1670   D->setDefaultArgument(DefArg, Inherited);
1671 }
1672 
1673 void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
1674   VisitDeclaratorDecl(D);
1675   // TemplateParmPosition.
1676   D->setDepth(Record[Idx++]);
1677   D->setPosition(Record[Idx++]);
1678   if (D->isExpandedParameterPack()) {
1679     void **Data = reinterpret_cast<void **>(D + 1);
1680     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
1681       Data[2*I] = Reader.readType(F, Record, Idx).getAsOpaquePtr();
1682       Data[2*I + 1] = GetTypeSourceInfo(Record, Idx);
1683     }
1684   } else {
1685     // Rest of NonTypeTemplateParmDecl.
1686     D->ParameterPack = Record[Idx++];
1687     if (Record[Idx++]) {
1688       Expr *DefArg = Reader.ReadExpr(F);
1689       bool Inherited = Record[Idx++];
1690       D->setDefaultArgument(DefArg, Inherited);
1691    }
1692   }
1693 }
1694 
1695 void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
1696   VisitTemplateDecl(D);
1697   // TemplateParmPosition.
1698   D->setDepth(Record[Idx++]);
1699   D->setPosition(Record[Idx++]);
1700   if (D->isExpandedParameterPack()) {
1701     void **Data = reinterpret_cast<void **>(D + 1);
1702     for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
1703          I != N; ++I)
1704       Data[I] = Reader.ReadTemplateParameterList(F, Record, Idx);
1705   } else {
1706     // Rest of TemplateTemplateParmDecl.
1707     TemplateArgumentLoc Arg = Reader.ReadTemplateArgumentLoc(F, Record, Idx);
1708     bool IsInherited = Record[Idx++];
1709     D->setDefaultArgument(Arg, IsInherited);
1710     D->ParameterPack = Record[Idx++];
1711   }
1712 }
1713 
1714 void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
1715   VisitRedeclarableTemplateDecl(D);
1716 }
1717 
1718 void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
1719   VisitDecl(D);
1720   D->AssertExprAndFailed.setPointer(Reader.ReadExpr(F));
1721   D->AssertExprAndFailed.setInt(Record[Idx++]);
1722   D->Message = cast<StringLiteral>(Reader.ReadExpr(F));
1723   D->RParenLoc = ReadSourceLocation(Record, Idx);
1724 }
1725 
1726 void ASTDeclReader::VisitEmptyDecl(EmptyDecl *D) {
1727   VisitDecl(D);
1728 }
1729 
1730 std::pair<uint64_t, uint64_t>
1731 ASTDeclReader::VisitDeclContext(DeclContext *DC) {
1732   uint64_t LexicalOffset = Record[Idx++];
1733   uint64_t VisibleOffset = Record[Idx++];
1734   return std::make_pair(LexicalOffset, VisibleOffset);
1735 }
1736 
1737 template <typename T>
1738 ASTDeclReader::RedeclarableResult
1739 ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
1740   DeclID FirstDeclID = ReadDeclID(Record, Idx);
1741 
1742   // 0 indicates that this declaration was the only declaration of its entity,
1743   // and is used for space optimization.
1744   if (FirstDeclID == 0)
1745     FirstDeclID = ThisDeclID;
1746 
1747   T *FirstDecl = cast_or_null<T>(Reader.GetDecl(FirstDeclID));
1748   if (FirstDecl != D) {
1749     // We delay loading of the redeclaration chain to avoid deeply nested calls.
1750     // We temporarily set the first (canonical) declaration as the previous one
1751     // which is the one that matters and mark the real previous DeclID to be
1752     // loaded & attached later on.
1753     D->RedeclLink = Redeclarable<T>::PreviousDeclLink(FirstDecl);
1754   }
1755 
1756   // Note that this declaration has been deserialized.
1757   Reader.RedeclsDeserialized.insert(static_cast<T *>(D));
1758 
1759   // The result structure takes care to note that we need to load the
1760   // other declaration chains for this ID.
1761   return RedeclarableResult(Reader, FirstDeclID,
1762                             static_cast<T *>(D)->getKind());
1763 }
1764 
1765 /// \brief Attempts to merge the given declaration (D) with another declaration
1766 /// of the same entity.
1767 template<typename T>
1768 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *D,
1769                                       RedeclarableResult &Redecl) {
1770   // If modules are not available, there is no reason to perform this merge.
1771   if (!Reader.getContext().getLangOpts().Modules)
1772     return;
1773 
1774   if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D))) {
1775     if (T *Existing = ExistingRes) {
1776       T *ExistingCanon = Existing->getCanonicalDecl();
1777       T *DCanon = static_cast<T*>(D)->getCanonicalDecl();
1778       if (ExistingCanon != DCanon) {
1779         // Have our redeclaration link point back at the canonical declaration
1780         // of the existing declaration, so that this declaration has the
1781         // appropriate canonical declaration.
1782         D->RedeclLink = Redeclarable<T>::PreviousDeclLink(ExistingCanon);
1783 
1784         // When we merge a namespace, update its pointer to the first namespace.
1785         if (NamespaceDecl *Namespace
1786               = dyn_cast<NamespaceDecl>(static_cast<T*>(D))) {
1787           Namespace->AnonOrFirstNamespaceAndInline.setPointer(
1788             static_cast<NamespaceDecl *>(static_cast<void*>(ExistingCanon)));
1789         }
1790 
1791         // Don't introduce DCanon into the set of pending declaration chains.
1792         Redecl.suppress();
1793 
1794         // Introduce ExistingCanon into the set of pending declaration chains,
1795         // if in fact it came from a module file.
1796         if (ExistingCanon->isFromASTFile()) {
1797           GlobalDeclID ExistingCanonID = ExistingCanon->getGlobalID();
1798           assert(ExistingCanonID && "Unrecorded canonical declaration ID?");
1799           if (Reader.PendingDeclChainsKnown.insert(ExistingCanonID))
1800             Reader.PendingDeclChains.push_back(ExistingCanonID);
1801         }
1802 
1803         // If this declaration was the canonical declaration, make a note of
1804         // that. We accept the linear algorithm here because the number of
1805         // unique canonical declarations of an entity should always be tiny.
1806         if (DCanon == static_cast<T*>(D)) {
1807           SmallVectorImpl<DeclID> &Merged = Reader.MergedDecls[ExistingCanon];
1808           if (std::find(Merged.begin(), Merged.end(), Redecl.getFirstID())
1809                 == Merged.end())
1810             Merged.push_back(Redecl.getFirstID());
1811 
1812           // If ExistingCanon did not come from a module file, introduce the
1813           // first declaration that *does* come from a module file to the
1814           // set of pending declaration chains, so that we merge this
1815           // declaration.
1816           if (!ExistingCanon->isFromASTFile() &&
1817               Reader.PendingDeclChainsKnown.insert(Redecl.getFirstID()))
1818             Reader.PendingDeclChains.push_back(Merged[0]);
1819         }
1820       }
1821     }
1822   }
1823 }
1824 
1825 void ASTDeclReader::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
1826   VisitDecl(D);
1827   unsigned NumVars = D->varlist_size();
1828   SmallVector<Expr *, 16> Vars;
1829   Vars.reserve(NumVars);
1830   for (unsigned i = 0; i != NumVars; ++i) {
1831     Vars.push_back(Reader.ReadExpr(F));
1832   }
1833   D->setVars(Vars);
1834 }
1835 
1836 //===----------------------------------------------------------------------===//
1837 // Attribute Reading
1838 //===----------------------------------------------------------------------===//
1839 
1840 /// \brief Reads attributes from the current stream position.
1841 void ASTReader::ReadAttributes(ModuleFile &F, AttrVec &Attrs,
1842                                const RecordData &Record, unsigned &Idx) {
1843   for (unsigned i = 0, e = Record[Idx++]; i != e; ++i) {
1844     Attr *New = 0;
1845     attr::Kind Kind = (attr::Kind)Record[Idx++];
1846     SourceRange Range = ReadSourceRange(F, Record, Idx);
1847 
1848 #include "clang/Serialization/AttrPCHRead.inc"
1849 
1850     assert(New && "Unable to decode attribute?");
1851     Attrs.push_back(New);
1852   }
1853 }
1854 
1855 //===----------------------------------------------------------------------===//
1856 // ASTReader Implementation
1857 //===----------------------------------------------------------------------===//
1858 
1859 /// \brief Note that we have loaded the declaration with the given
1860 /// Index.
1861 ///
1862 /// This routine notes that this declaration has already been loaded,
1863 /// so that future GetDecl calls will return this declaration rather
1864 /// than trying to load a new declaration.
1865 inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
1866   assert(!DeclsLoaded[Index] && "Decl loaded twice?");
1867   DeclsLoaded[Index] = D;
1868 }
1869 
1870 
1871 /// \brief Determine whether the consumer will be interested in seeing
1872 /// this declaration (via HandleTopLevelDecl).
1873 ///
1874 /// This routine should return true for anything that might affect
1875 /// code generation, e.g., inline function definitions, Objective-C
1876 /// declarations with metadata, etc.
1877 static bool isConsumerInterestedIn(Decl *D, bool HasBody) {
1878   // An ObjCMethodDecl is never considered as "interesting" because its
1879   // implementation container always is.
1880 
1881   if (isa<FileScopeAsmDecl>(D) ||
1882       isa<ObjCProtocolDecl>(D) ||
1883       isa<ObjCImplDecl>(D))
1884     return true;
1885   if (VarDecl *Var = dyn_cast<VarDecl>(D))
1886     return Var->isFileVarDecl() &&
1887            Var->isThisDeclarationADefinition() == VarDecl::Definition;
1888   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
1889     return Func->doesThisDeclarationHaveABody() || HasBody;
1890 
1891   return false;
1892 }
1893 
1894 /// \brief Get the correct cursor and offset for loading a declaration.
1895 ASTReader::RecordLocation
1896 ASTReader::DeclCursorForID(DeclID ID, unsigned &RawLocation) {
1897   // See if there's an override.
1898   DeclReplacementMap::iterator It = ReplacedDecls.find(ID);
1899   if (It != ReplacedDecls.end()) {
1900     RawLocation = It->second.RawLoc;
1901     return RecordLocation(It->second.Mod, It->second.Offset);
1902   }
1903 
1904   GlobalDeclMapType::iterator I = GlobalDeclMap.find(ID);
1905   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
1906   ModuleFile *M = I->second;
1907   const DeclOffset &
1908     DOffs =  M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS];
1909   RawLocation = DOffs.Loc;
1910   return RecordLocation(M, DOffs.BitOffset);
1911 }
1912 
1913 ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
1914   ContinuousRangeMap<uint64_t, ModuleFile*, 4>::iterator I
1915     = GlobalBitOffsetsMap.find(GlobalOffset);
1916 
1917   assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map");
1918   return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
1919 }
1920 
1921 uint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset) {
1922   return LocalOffset + M.GlobalBitOffset;
1923 }
1924 
1925 static bool isSameTemplateParameterList(const TemplateParameterList *X,
1926                                         const TemplateParameterList *Y);
1927 
1928 /// \brief Determine whether two template parameters are similar enough
1929 /// that they may be used in declarations of the same template.
1930 static bool isSameTemplateParameter(const NamedDecl *X,
1931                                     const NamedDecl *Y) {
1932   if (X->getKind() != Y->getKind())
1933     return false;
1934 
1935   if (const TemplateTypeParmDecl *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
1936     const TemplateTypeParmDecl *TY = cast<TemplateTypeParmDecl>(Y);
1937     return TX->isParameterPack() == TY->isParameterPack();
1938   }
1939 
1940   if (const NonTypeTemplateParmDecl *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
1941     const NonTypeTemplateParmDecl *TY = cast<NonTypeTemplateParmDecl>(Y);
1942     return TX->isParameterPack() == TY->isParameterPack() &&
1943            TX->getASTContext().hasSameType(TX->getType(), TY->getType());
1944   }
1945 
1946   const TemplateTemplateParmDecl *TX = cast<TemplateTemplateParmDecl>(X);
1947   const TemplateTemplateParmDecl *TY = cast<TemplateTemplateParmDecl>(Y);
1948   return TX->isParameterPack() == TY->isParameterPack() &&
1949          isSameTemplateParameterList(TX->getTemplateParameters(),
1950                                      TY->getTemplateParameters());
1951 }
1952 
1953 /// \brief Determine whether two template parameter lists are similar enough
1954 /// that they may be used in declarations of the same template.
1955 static bool isSameTemplateParameterList(const TemplateParameterList *X,
1956                                         const TemplateParameterList *Y) {
1957   if (X->size() != Y->size())
1958     return false;
1959 
1960   for (unsigned I = 0, N = X->size(); I != N; ++I)
1961     if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
1962       return false;
1963 
1964   return true;
1965 }
1966 
1967 /// \brief Determine whether the two declarations refer to the same entity.
1968 static bool isSameEntity(NamedDecl *X, NamedDecl *Y) {
1969   assert(X->getDeclName() == Y->getDeclName() && "Declaration name mismatch!");
1970 
1971   if (X == Y)
1972     return true;
1973 
1974   // Must be in the same context.
1975   if (!X->getDeclContext()->getRedeclContext()->Equals(
1976          Y->getDeclContext()->getRedeclContext()))
1977     return false;
1978 
1979   // Two typedefs refer to the same entity if they have the same underlying
1980   // type.
1981   if (TypedefNameDecl *TypedefX = dyn_cast<TypedefNameDecl>(X))
1982     if (TypedefNameDecl *TypedefY = dyn_cast<TypedefNameDecl>(Y))
1983       return X->getASTContext().hasSameType(TypedefX->getUnderlyingType(),
1984                                             TypedefY->getUnderlyingType());
1985 
1986   // Must have the same kind.
1987   if (X->getKind() != Y->getKind())
1988     return false;
1989 
1990   // Objective-C classes and protocols with the same name always match.
1991   if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
1992     return true;
1993 
1994   if (isa<ClassTemplateSpecializationDecl>(X)) {
1995     // FIXME: Deal with merging of template specializations.
1996     // For now, don't merge these; we need to check more than just the name to
1997     // determine if they refer to the same entity.
1998     return false;
1999   }
2000 
2001   // Compatible tags match.
2002   if (TagDecl *TagX = dyn_cast<TagDecl>(X)) {
2003     TagDecl *TagY = cast<TagDecl>(Y);
2004     return (TagX->getTagKind() == TagY->getTagKind()) ||
2005       ((TagX->getTagKind() == TTK_Struct || TagX->getTagKind() == TTK_Class ||
2006         TagX->getTagKind() == TTK_Interface) &&
2007        (TagY->getTagKind() == TTK_Struct || TagY->getTagKind() == TTK_Class ||
2008         TagY->getTagKind() == TTK_Interface));
2009   }
2010 
2011   // Functions with the same type and linkage match.
2012   // FIXME: This needs to cope with function template specializations,
2013   // merging of prototyped/non-prototyped functions, etc.
2014   if (FunctionDecl *FuncX = dyn_cast<FunctionDecl>(X)) {
2015     FunctionDecl *FuncY = cast<FunctionDecl>(Y);
2016     return (FuncX->getLinkageInternal() == FuncY->getLinkageInternal()) &&
2017       FuncX->getASTContext().hasSameType(FuncX->getType(), FuncY->getType());
2018   }
2019 
2020   // Variables with the same type and linkage match.
2021   if (VarDecl *VarX = dyn_cast<VarDecl>(X)) {
2022     VarDecl *VarY = cast<VarDecl>(Y);
2023     return (VarX->getLinkageInternal() == VarY->getLinkageInternal()) &&
2024       VarX->getASTContext().hasSameType(VarX->getType(), VarY->getType());
2025   }
2026 
2027   // Namespaces with the same name and inlinedness match.
2028   if (NamespaceDecl *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
2029     NamespaceDecl *NamespaceY = cast<NamespaceDecl>(Y);
2030     return NamespaceX->isInline() == NamespaceY->isInline();
2031   }
2032 
2033   // Identical template names and kinds match if their template parameter lists
2034   // and patterns match.
2035   if (TemplateDecl *TemplateX = dyn_cast<TemplateDecl>(X)) {
2036     TemplateDecl *TemplateY = cast<TemplateDecl>(Y);
2037     return isSameEntity(TemplateX->getTemplatedDecl(),
2038                         TemplateY->getTemplatedDecl()) &&
2039            isSameTemplateParameterList(TemplateX->getTemplateParameters(),
2040                                        TemplateY->getTemplateParameters());
2041   }
2042 
2043   // FIXME: Many other cases to implement.
2044   return false;
2045 }
2046 
2047 ASTDeclReader::FindExistingResult::~FindExistingResult() {
2048   if (!AddResult || Existing)
2049     return;
2050 
2051   DeclContext *DC = New->getDeclContext()->getRedeclContext();
2052   if (DC->isTranslationUnit() && Reader.SemaObj) {
2053     Reader.SemaObj->IdResolver.tryAddTopLevelDecl(New, New->getDeclName());
2054   } else if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(DC)) {
2055     // Add the declaration to its redeclaration context so later merging
2056     // lookups will find it.
2057     NS->getFirstDeclaration()->makeDeclVisibleInContextImpl(New,
2058                                                             /*Internal*/true);
2059   }
2060 }
2061 
2062 ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) {
2063   DeclarationName Name = D->getDeclName();
2064   if (!Name) {
2065     // Don't bother trying to find unnamed declarations.
2066     FindExistingResult Result(Reader, D, /*Existing=*/0);
2067     Result.suppress();
2068     return Result;
2069   }
2070 
2071   DeclContext *DC = D->getDeclContext()->getRedeclContext();
2072   if (!DC->isFileContext())
2073     return FindExistingResult(Reader);
2074 
2075   if (DC->isTranslationUnit() && Reader.SemaObj) {
2076     IdentifierResolver &IdResolver = Reader.SemaObj->IdResolver;
2077 
2078     // Temporarily consider the identifier to be up-to-date. We don't want to
2079     // cause additional lookups here.
2080     class UpToDateIdentifierRAII {
2081       IdentifierInfo *II;
2082       bool WasOutToDate;
2083 
2084     public:
2085       explicit UpToDateIdentifierRAII(IdentifierInfo *II)
2086         : II(II), WasOutToDate(false)
2087       {
2088         if (II) {
2089           WasOutToDate = II->isOutOfDate();
2090           if (WasOutToDate)
2091             II->setOutOfDate(false);
2092         }
2093       }
2094 
2095       ~UpToDateIdentifierRAII() {
2096         if (WasOutToDate)
2097           II->setOutOfDate(true);
2098       }
2099     } UpToDate(Name.getAsIdentifierInfo());
2100 
2101     for (IdentifierResolver::iterator I = IdResolver.begin(Name),
2102                                    IEnd = IdResolver.end();
2103          I != IEnd; ++I) {
2104       if (isSameEntity(*I, D))
2105         return FindExistingResult(Reader, D, *I);
2106     }
2107   } else if (NamespaceDecl *NS = dyn_cast<NamespaceDecl>(DC)) {
2108     DeclContext::lookup_result R = NS->getFirstDeclaration()->noload_lookup(Name);
2109     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
2110       if (isSameEntity(*I, D))
2111         return FindExistingResult(Reader, D, *I);
2112     }
2113   }
2114 
2115   return FindExistingResult(Reader, D, /*Existing=*/0);
2116 }
2117 
2118 void ASTDeclReader::attachPreviousDecl(Decl *D, Decl *previous) {
2119   assert(D && previous);
2120   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2121     TD->RedeclLink.setNext(cast<TagDecl>(previous));
2122   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2123     FD->RedeclLink.setNext(cast<FunctionDecl>(previous));
2124   } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2125     VD->RedeclLink.setNext(cast<VarDecl>(previous));
2126   } else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2127     TD->RedeclLink.setNext(cast<TypedefNameDecl>(previous));
2128   } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
2129     ID->RedeclLink.setNext(cast<ObjCInterfaceDecl>(previous));
2130   } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
2131     PD->RedeclLink.setNext(cast<ObjCProtocolDecl>(previous));
2132   } else if (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(D)) {
2133     ND->RedeclLink.setNext(cast<NamespaceDecl>(previous));
2134   } else {
2135     RedeclarableTemplateDecl *TD = cast<RedeclarableTemplateDecl>(D);
2136     TD->RedeclLink.setNext(cast<RedeclarableTemplateDecl>(previous));
2137   }
2138 
2139   // If the declaration was visible in one module, a redeclaration of it in
2140   // another module remains visible even if it wouldn't be visible by itself.
2141   //
2142   // FIXME: In this case, the declaration should only be visible if a module
2143   //        that makes it visible has been imported.
2144   // FIXME: This is not correct in the case where previous is a local extern
2145   //        declaration and D is a friend declaraton.
2146   D->IdentifierNamespace |=
2147       previous->IdentifierNamespace &
2148       (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
2149 }
2150 
2151 void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {
2152   assert(D && Latest);
2153   if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
2154     TD->RedeclLink
2155       = Redeclarable<TagDecl>::LatestDeclLink(cast<TagDecl>(Latest));
2156   } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2157     FD->RedeclLink
2158       = Redeclarable<FunctionDecl>::LatestDeclLink(cast<FunctionDecl>(Latest));
2159   } else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
2160     VD->RedeclLink
2161       = Redeclarable<VarDecl>::LatestDeclLink(cast<VarDecl>(Latest));
2162   } else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
2163     TD->RedeclLink
2164       = Redeclarable<TypedefNameDecl>::LatestDeclLink(
2165                                                 cast<TypedefNameDecl>(Latest));
2166   } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
2167     ID->RedeclLink
2168       = Redeclarable<ObjCInterfaceDecl>::LatestDeclLink(
2169                                               cast<ObjCInterfaceDecl>(Latest));
2170   } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
2171     PD->RedeclLink
2172       = Redeclarable<ObjCProtocolDecl>::LatestDeclLink(
2173                                                 cast<ObjCProtocolDecl>(Latest));
2174   } else if (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(D)) {
2175     ND->RedeclLink
2176       = Redeclarable<NamespaceDecl>::LatestDeclLink(
2177                                                    cast<NamespaceDecl>(Latest));
2178   } else {
2179     RedeclarableTemplateDecl *TD = cast<RedeclarableTemplateDecl>(D);
2180     TD->RedeclLink
2181       = Redeclarable<RedeclarableTemplateDecl>::LatestDeclLink(
2182                                         cast<RedeclarableTemplateDecl>(Latest));
2183   }
2184 }
2185 
2186 ASTReader::MergedDeclsMap::iterator
2187 ASTReader::combineStoredMergedDecls(Decl *Canon, GlobalDeclID CanonID) {
2188   // If we don't have any stored merged declarations, just look in the
2189   // merged declarations set.
2190   StoredMergedDeclsMap::iterator StoredPos = StoredMergedDecls.find(CanonID);
2191   if (StoredPos == StoredMergedDecls.end())
2192     return MergedDecls.find(Canon);
2193 
2194   // Append the stored merged declarations to the merged declarations set.
2195   MergedDeclsMap::iterator Pos = MergedDecls.find(Canon);
2196   if (Pos == MergedDecls.end())
2197     Pos = MergedDecls.insert(std::make_pair(Canon,
2198                                             SmallVector<DeclID, 2>())).first;
2199   Pos->second.append(StoredPos->second.begin(), StoredPos->second.end());
2200   StoredMergedDecls.erase(StoredPos);
2201 
2202   // Sort and uniquify the set of merged declarations.
2203   llvm::array_pod_sort(Pos->second.begin(), Pos->second.end());
2204   Pos->second.erase(std::unique(Pos->second.begin(), Pos->second.end()),
2205                     Pos->second.end());
2206   return Pos;
2207 }
2208 
2209 /// \brief Read the declaration at the given offset from the AST file.
2210 Decl *ASTReader::ReadDeclRecord(DeclID ID) {
2211   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
2212   unsigned RawLocation = 0;
2213   RecordLocation Loc = DeclCursorForID(ID, RawLocation);
2214   llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
2215   // Keep track of where we are in the stream, then jump back there
2216   // after reading this declaration.
2217   SavedStreamPosition SavedPosition(DeclsCursor);
2218 
2219   ReadingKindTracker ReadingKind(Read_Decl, *this);
2220 
2221   // Note that we are loading a declaration record.
2222   Deserializing ADecl(this);
2223 
2224   DeclsCursor.JumpToBit(Loc.Offset);
2225   RecordData Record;
2226   unsigned Code = DeclsCursor.ReadCode();
2227   unsigned Idx = 0;
2228   ASTDeclReader Reader(*this, *Loc.F, ID, RawLocation, Record,Idx);
2229 
2230   Decl *D = 0;
2231   switch ((DeclCode)DeclsCursor.readRecord(Code, Record)) {
2232   case DECL_CONTEXT_LEXICAL:
2233   case DECL_CONTEXT_VISIBLE:
2234     llvm_unreachable("Record cannot be de-serialized with ReadDeclRecord");
2235   case DECL_TYPEDEF:
2236     D = TypedefDecl::CreateDeserialized(Context, ID);
2237     break;
2238   case DECL_TYPEALIAS:
2239     D = TypeAliasDecl::CreateDeserialized(Context, ID);
2240     break;
2241   case DECL_ENUM:
2242     D = EnumDecl::CreateDeserialized(Context, ID);
2243     break;
2244   case DECL_RECORD:
2245     D = RecordDecl::CreateDeserialized(Context, ID);
2246     break;
2247   case DECL_ENUM_CONSTANT:
2248     D = EnumConstantDecl::CreateDeserialized(Context, ID);
2249     break;
2250   case DECL_FUNCTION:
2251     D = FunctionDecl::CreateDeserialized(Context, ID);
2252     break;
2253   case DECL_LINKAGE_SPEC:
2254     D = LinkageSpecDecl::CreateDeserialized(Context, ID);
2255     break;
2256   case DECL_LABEL:
2257     D = LabelDecl::CreateDeserialized(Context, ID);
2258     break;
2259   case DECL_NAMESPACE:
2260     D = NamespaceDecl::CreateDeserialized(Context, ID);
2261     break;
2262   case DECL_NAMESPACE_ALIAS:
2263     D = NamespaceAliasDecl::CreateDeserialized(Context, ID);
2264     break;
2265   case DECL_USING:
2266     D = UsingDecl::CreateDeserialized(Context, ID);
2267     break;
2268   case DECL_USING_SHADOW:
2269     D = UsingShadowDecl::CreateDeserialized(Context, ID);
2270     break;
2271   case DECL_USING_DIRECTIVE:
2272     D = UsingDirectiveDecl::CreateDeserialized(Context, ID);
2273     break;
2274   case DECL_UNRESOLVED_USING_VALUE:
2275     D = UnresolvedUsingValueDecl::CreateDeserialized(Context, ID);
2276     break;
2277   case DECL_UNRESOLVED_USING_TYPENAME:
2278     D = UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID);
2279     break;
2280   case DECL_CXX_RECORD:
2281     D = CXXRecordDecl::CreateDeserialized(Context, ID);
2282     break;
2283   case DECL_CXX_METHOD:
2284     D = CXXMethodDecl::CreateDeserialized(Context, ID);
2285     break;
2286   case DECL_CXX_CONSTRUCTOR:
2287     D = CXXConstructorDecl::CreateDeserialized(Context, ID);
2288     break;
2289   case DECL_CXX_DESTRUCTOR:
2290     D = CXXDestructorDecl::CreateDeserialized(Context, ID);
2291     break;
2292   case DECL_CXX_CONVERSION:
2293     D = CXXConversionDecl::CreateDeserialized(Context, ID);
2294     break;
2295   case DECL_ACCESS_SPEC:
2296     D = AccessSpecDecl::CreateDeserialized(Context, ID);
2297     break;
2298   case DECL_FRIEND:
2299     D = FriendDecl::CreateDeserialized(Context, ID, Record[Idx++]);
2300     break;
2301   case DECL_FRIEND_TEMPLATE:
2302     D = FriendTemplateDecl::CreateDeserialized(Context, ID);
2303     break;
2304   case DECL_CLASS_TEMPLATE:
2305     D = ClassTemplateDecl::CreateDeserialized(Context, ID);
2306     break;
2307   case DECL_CLASS_TEMPLATE_SPECIALIZATION:
2308     D = ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID);
2309     break;
2310   case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
2311     D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
2312     break;
2313   case DECL_VAR_TEMPLATE:
2314     D = VarTemplateDecl::CreateDeserialized(Context, ID);
2315     break;
2316   case DECL_VAR_TEMPLATE_SPECIALIZATION:
2317     D = VarTemplateSpecializationDecl::CreateDeserialized(Context, ID);
2318     break;
2319   case DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION:
2320     D = VarTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
2321     break;
2322   case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
2323     D = ClassScopeFunctionSpecializationDecl::CreateDeserialized(Context, ID);
2324     break;
2325   case DECL_FUNCTION_TEMPLATE:
2326     D = FunctionTemplateDecl::CreateDeserialized(Context, ID);
2327     break;
2328   case DECL_TEMPLATE_TYPE_PARM:
2329     D = TemplateTypeParmDecl::CreateDeserialized(Context, ID);
2330     break;
2331   case DECL_NON_TYPE_TEMPLATE_PARM:
2332     D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID);
2333     break;
2334   case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK:
2335     D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID, Record[Idx++]);
2336     break;
2337   case DECL_TEMPLATE_TEMPLATE_PARM:
2338     D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID);
2339     break;
2340   case DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK:
2341     D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID,
2342                                                      Record[Idx++]);
2343     break;
2344   case DECL_TYPE_ALIAS_TEMPLATE:
2345     D = TypeAliasTemplateDecl::CreateDeserialized(Context, ID);
2346     break;
2347   case DECL_STATIC_ASSERT:
2348     D = StaticAssertDecl::CreateDeserialized(Context, ID);
2349     break;
2350   case DECL_OBJC_METHOD:
2351     D = ObjCMethodDecl::CreateDeserialized(Context, ID);
2352     break;
2353   case DECL_OBJC_INTERFACE:
2354     D = ObjCInterfaceDecl::CreateDeserialized(Context, ID);
2355     break;
2356   case DECL_OBJC_IVAR:
2357     D = ObjCIvarDecl::CreateDeserialized(Context, ID);
2358     break;
2359   case DECL_OBJC_PROTOCOL:
2360     D = ObjCProtocolDecl::CreateDeserialized(Context, ID);
2361     break;
2362   case DECL_OBJC_AT_DEFS_FIELD:
2363     D = ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID);
2364     break;
2365   case DECL_OBJC_CATEGORY:
2366     D = ObjCCategoryDecl::CreateDeserialized(Context, ID);
2367     break;
2368   case DECL_OBJC_CATEGORY_IMPL:
2369     D = ObjCCategoryImplDecl::CreateDeserialized(Context, ID);
2370     break;
2371   case DECL_OBJC_IMPLEMENTATION:
2372     D = ObjCImplementationDecl::CreateDeserialized(Context, ID);
2373     break;
2374   case DECL_OBJC_COMPATIBLE_ALIAS:
2375     D = ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID);
2376     break;
2377   case DECL_OBJC_PROPERTY:
2378     D = ObjCPropertyDecl::CreateDeserialized(Context, ID);
2379     break;
2380   case DECL_OBJC_PROPERTY_IMPL:
2381     D = ObjCPropertyImplDecl::CreateDeserialized(Context, ID);
2382     break;
2383   case DECL_FIELD:
2384     D = FieldDecl::CreateDeserialized(Context, ID);
2385     break;
2386   case DECL_INDIRECTFIELD:
2387     D = IndirectFieldDecl::CreateDeserialized(Context, ID);
2388     break;
2389   case DECL_VAR:
2390     D = VarDecl::CreateDeserialized(Context, ID);
2391     break;
2392   case DECL_IMPLICIT_PARAM:
2393     D = ImplicitParamDecl::CreateDeserialized(Context, ID);
2394     break;
2395   case DECL_PARM_VAR:
2396     D = ParmVarDecl::CreateDeserialized(Context, ID);
2397     break;
2398   case DECL_FILE_SCOPE_ASM:
2399     D = FileScopeAsmDecl::CreateDeserialized(Context, ID);
2400     break;
2401   case DECL_BLOCK:
2402     D = BlockDecl::CreateDeserialized(Context, ID);
2403     break;
2404   case DECL_MS_PROPERTY:
2405     D = MSPropertyDecl::CreateDeserialized(Context, ID);
2406     break;
2407   case DECL_CAPTURED:
2408     D = CapturedDecl::CreateDeserialized(Context, ID, Record[Idx++]);
2409     break;
2410   case DECL_CXX_BASE_SPECIFIERS:
2411     Error("attempt to read a C++ base-specifier record as a declaration");
2412     return 0;
2413   case DECL_IMPORT:
2414     // Note: last entry of the ImportDecl record is the number of stored source
2415     // locations.
2416     D = ImportDecl::CreateDeserialized(Context, ID, Record.back());
2417     break;
2418   case DECL_OMP_THREADPRIVATE:
2419     D = OMPThreadPrivateDecl::CreateDeserialized(Context, ID, Record[Idx++]);
2420     break;
2421   case DECL_EMPTY:
2422     D = EmptyDecl::CreateDeserialized(Context, ID);
2423     break;
2424   }
2425 
2426   assert(D && "Unknown declaration reading AST file");
2427   LoadedDecl(Index, D);
2428   // Set the DeclContext before doing any deserialization, to make sure internal
2429   // calls to Decl::getASTContext() by Decl's methods will find the
2430   // TranslationUnitDecl without crashing.
2431   D->setDeclContext(Context.getTranslationUnitDecl());
2432   Reader.Visit(D);
2433 
2434   // If this declaration is also a declaration context, get the
2435   // offsets for its tables of lexical and visible declarations.
2436   if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
2437     // FIXME: This should really be
2438     //     DeclContext *LookupDC = DC->getPrimaryContext();
2439     // but that can walk the redeclaration chain, which might not work yet.
2440     DeclContext *LookupDC = DC;
2441     if (isa<NamespaceDecl>(DC))
2442       LookupDC = DC->getPrimaryContext();
2443     std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
2444     if (Offsets.first || Offsets.second) {
2445       if (Offsets.first != 0)
2446         DC->setHasExternalLexicalStorage(true);
2447       if (Offsets.second != 0)
2448         LookupDC->setHasExternalVisibleStorage(true);
2449       if (ReadDeclContextStorage(*Loc.F, DeclsCursor, Offsets,
2450                                  Loc.F->DeclContextInfos[DC]))
2451         return 0;
2452     }
2453 
2454     // Now add the pending visible updates for this decl context, if it has any.
2455     DeclContextVisibleUpdatesPending::iterator I =
2456         PendingVisibleUpdates.find(ID);
2457     if (I != PendingVisibleUpdates.end()) {
2458       // There are updates. This means the context has external visible
2459       // storage, even if the original stored version didn't.
2460       LookupDC->setHasExternalVisibleStorage(true);
2461       DeclContextVisibleUpdates &U = I->second;
2462       for (DeclContextVisibleUpdates::iterator UI = U.begin(), UE = U.end();
2463            UI != UE; ++UI) {
2464         DeclContextInfo &Info = UI->second->DeclContextInfos[DC];
2465         delete Info.NameLookupTableData;
2466         Info.NameLookupTableData = UI->first;
2467       }
2468       PendingVisibleUpdates.erase(I);
2469     }
2470   }
2471   assert(Idx == Record.size());
2472 
2473   // Load any relevant update records.
2474   loadDeclUpdateRecords(ID, D);
2475 
2476   // Load the categories after recursive loading is finished.
2477   if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
2478     if (Class->isThisDeclarationADefinition())
2479       loadObjCCategories(ID, Class);
2480 
2481   // If we have deserialized a declaration that has a definition the
2482   // AST consumer might need to know about, queue it.
2483   // We don't pass it to the consumer immediately because we may be in recursive
2484   // loading, and some declarations may still be initializing.
2485   if (isConsumerInterestedIn(D, Reader.hasPendingBody()))
2486     InterestingDecls.push_back(D);
2487 
2488   return D;
2489 }
2490 
2491 void ASTReader::loadDeclUpdateRecords(serialization::DeclID ID, Decl *D) {
2492   // The declaration may have been modified by files later in the chain.
2493   // If this is the case, read the record containing the updates from each file
2494   // and pass it to ASTDeclReader to make the modifications.
2495   DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
2496   if (UpdI != DeclUpdateOffsets.end()) {
2497     FileOffsetsTy &UpdateOffsets = UpdI->second;
2498     for (FileOffsetsTy::iterator
2499          I = UpdateOffsets.begin(), E = UpdateOffsets.end(); I != E; ++I) {
2500       ModuleFile *F = I->first;
2501       uint64_t Offset = I->second;
2502       llvm::BitstreamCursor &Cursor = F->DeclsCursor;
2503       SavedStreamPosition SavedPosition(Cursor);
2504       Cursor.JumpToBit(Offset);
2505       RecordData Record;
2506       unsigned Code = Cursor.ReadCode();
2507       unsigned RecCode = Cursor.readRecord(Code, Record);
2508       (void)RecCode;
2509       assert(RecCode == DECL_UPDATES && "Expected DECL_UPDATES record!");
2510 
2511       unsigned Idx = 0;
2512       ASTDeclReader Reader(*this, *F, ID, 0, Record, Idx);
2513       Reader.UpdateDecl(D, *F, Record);
2514     }
2515   }
2516 }
2517 
2518 namespace {
2519   struct CompareLocalRedeclarationsInfoToID {
2520     bool operator()(const LocalRedeclarationsInfo &X, DeclID Y) {
2521       return X.FirstID < Y;
2522     }
2523 
2524     bool operator()(DeclID X, const LocalRedeclarationsInfo &Y) {
2525       return X < Y.FirstID;
2526     }
2527 
2528     bool operator()(const LocalRedeclarationsInfo &X,
2529                     const LocalRedeclarationsInfo &Y) {
2530       return X.FirstID < Y.FirstID;
2531     }
2532     bool operator()(DeclID X, DeclID Y) {
2533       return X < Y;
2534     }
2535   };
2536 
2537   /// \brief Module visitor class that finds all of the redeclarations of a
2538   ///
2539   class RedeclChainVisitor {
2540     ASTReader &Reader;
2541     SmallVectorImpl<DeclID> &SearchDecls;
2542     llvm::SmallPtrSet<Decl *, 16> &Deserialized;
2543     GlobalDeclID CanonID;
2544     SmallVector<Decl *, 4> Chain;
2545 
2546   public:
2547     RedeclChainVisitor(ASTReader &Reader, SmallVectorImpl<DeclID> &SearchDecls,
2548                        llvm::SmallPtrSet<Decl *, 16> &Deserialized,
2549                        GlobalDeclID CanonID)
2550       : Reader(Reader), SearchDecls(SearchDecls), Deserialized(Deserialized),
2551         CanonID(CanonID) {
2552       for (unsigned I = 0, N = SearchDecls.size(); I != N; ++I)
2553         addToChain(Reader.GetDecl(SearchDecls[I]));
2554     }
2555 
2556     static bool visit(ModuleFile &M, bool Preorder, void *UserData) {
2557       if (Preorder)
2558         return false;
2559 
2560       return static_cast<RedeclChainVisitor *>(UserData)->visit(M);
2561     }
2562 
2563     void addToChain(Decl *D) {
2564       if (!D)
2565         return;
2566 
2567       if (Deserialized.erase(D))
2568         Chain.push_back(D);
2569     }
2570 
2571     void searchForID(ModuleFile &M, GlobalDeclID GlobalID) {
2572       // Map global ID of the first declaration down to the local ID
2573       // used in this module file.
2574       DeclID ID = Reader.mapGlobalIDToModuleFileGlobalID(M, GlobalID);
2575       if (!ID)
2576         return;
2577 
2578       // Perform a binary search to find the local redeclarations for this
2579       // declaration (if any).
2580       const LocalRedeclarationsInfo *Result
2581         = std::lower_bound(M.RedeclarationsMap,
2582                            M.RedeclarationsMap + M.LocalNumRedeclarationsInMap,
2583                            ID, CompareLocalRedeclarationsInfoToID());
2584       if (Result == M.RedeclarationsMap + M.LocalNumRedeclarationsInMap ||
2585           Result->FirstID != ID) {
2586         // If we have a previously-canonical singleton declaration that was
2587         // merged into another redeclaration chain, create a trivial chain
2588         // for this single declaration so that it will get wired into the
2589         // complete redeclaration chain.
2590         if (GlobalID != CanonID &&
2591             GlobalID - NUM_PREDEF_DECL_IDS >= M.BaseDeclID &&
2592             GlobalID - NUM_PREDEF_DECL_IDS < M.BaseDeclID + M.LocalNumDecls) {
2593           addToChain(Reader.GetDecl(GlobalID));
2594         }
2595 
2596         return;
2597       }
2598 
2599       // Dig out all of the redeclarations.
2600       unsigned Offset = Result->Offset;
2601       unsigned N = M.RedeclarationChains[Offset];
2602       M.RedeclarationChains[Offset++] = 0; // Don't try to deserialize again
2603       for (unsigned I = 0; I != N; ++I)
2604         addToChain(Reader.GetLocalDecl(M, M.RedeclarationChains[Offset++]));
2605     }
2606 
2607     bool visit(ModuleFile &M) {
2608       // Visit each of the declarations.
2609       for (unsigned I = 0, N = SearchDecls.size(); I != N; ++I)
2610         searchForID(M, SearchDecls[I]);
2611       return false;
2612     }
2613 
2614     ArrayRef<Decl *> getChain() const {
2615       return Chain;
2616     }
2617   };
2618 }
2619 
2620 void ASTReader::loadPendingDeclChain(serialization::GlobalDeclID ID) {
2621   Decl *D = GetDecl(ID);
2622   Decl *CanonDecl = D->getCanonicalDecl();
2623 
2624   // Determine the set of declaration IDs we'll be searching for.
2625   SmallVector<DeclID, 1> SearchDecls;
2626   GlobalDeclID CanonID = 0;
2627   if (D == CanonDecl) {
2628     SearchDecls.push_back(ID); // Always first.
2629     CanonID = ID;
2630   }
2631   MergedDeclsMap::iterator MergedPos = combineStoredMergedDecls(CanonDecl, ID);
2632   if (MergedPos != MergedDecls.end())
2633     SearchDecls.append(MergedPos->second.begin(), MergedPos->second.end());
2634 
2635   // Build up the list of redeclarations.
2636   RedeclChainVisitor Visitor(*this, SearchDecls, RedeclsDeserialized, CanonID);
2637   ModuleMgr.visitDepthFirst(&RedeclChainVisitor::visit, &Visitor);
2638 
2639   // Retrieve the chains.
2640   ArrayRef<Decl *> Chain = Visitor.getChain();
2641   if (Chain.empty())
2642     return;
2643 
2644   // Hook up the chains.
2645   Decl *MostRecent = CanonDecl->getMostRecentDecl();
2646   for (unsigned I = 0, N = Chain.size(); I != N; ++I) {
2647     if (Chain[I] == CanonDecl)
2648       continue;
2649 
2650     ASTDeclReader::attachPreviousDecl(Chain[I], MostRecent);
2651     MostRecent = Chain[I];
2652   }
2653 
2654   ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent);
2655 }
2656 
2657 namespace {
2658   struct CompareObjCCategoriesInfo {
2659     bool operator()(const ObjCCategoriesInfo &X, DeclID Y) {
2660       return X.DefinitionID < Y;
2661     }
2662 
2663     bool operator()(DeclID X, const ObjCCategoriesInfo &Y) {
2664       return X < Y.DefinitionID;
2665     }
2666 
2667     bool operator()(const ObjCCategoriesInfo &X,
2668                     const ObjCCategoriesInfo &Y) {
2669       return X.DefinitionID < Y.DefinitionID;
2670     }
2671     bool operator()(DeclID X, DeclID Y) {
2672       return X < Y;
2673     }
2674   };
2675 
2676   /// \brief Given an ObjC interface, goes through the modules and links to the
2677   /// interface all the categories for it.
2678   class ObjCCategoriesVisitor {
2679     ASTReader &Reader;
2680     serialization::GlobalDeclID InterfaceID;
2681     ObjCInterfaceDecl *Interface;
2682     llvm::SmallPtrSet<ObjCCategoryDecl *, 16> &Deserialized;
2683     unsigned PreviousGeneration;
2684     ObjCCategoryDecl *Tail;
2685     llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
2686 
2687     void add(ObjCCategoryDecl *Cat) {
2688       // Only process each category once.
2689       if (!Deserialized.erase(Cat))
2690         return;
2691 
2692       // Check for duplicate categories.
2693       if (Cat->getDeclName()) {
2694         ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
2695         if (Existing &&
2696             Reader.getOwningModuleFile(Existing)
2697                                           != Reader.getOwningModuleFile(Cat)) {
2698           // FIXME: We should not warn for duplicates in diamond:
2699           //
2700           //   MT     //
2701           //  /  \    //
2702           // ML  MR   //
2703           //  \  /    //
2704           //   MB     //
2705           //
2706           // If there are duplicates in ML/MR, there will be warning when
2707           // creating MB *and* when importing MB. We should not warn when
2708           // importing.
2709           Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
2710             << Interface->getDeclName() << Cat->getDeclName();
2711           Reader.Diag(Existing->getLocation(), diag::note_previous_definition);
2712         } else if (!Existing) {
2713           // Record this category.
2714           Existing = Cat;
2715         }
2716       }
2717 
2718       // Add this category to the end of the chain.
2719       if (Tail)
2720         ASTDeclReader::setNextObjCCategory(Tail, Cat);
2721       else
2722         Interface->setCategoryListRaw(Cat);
2723       Tail = Cat;
2724     }
2725 
2726   public:
2727     ObjCCategoriesVisitor(ASTReader &Reader,
2728                           serialization::GlobalDeclID InterfaceID,
2729                           ObjCInterfaceDecl *Interface,
2730                         llvm::SmallPtrSet<ObjCCategoryDecl *, 16> &Deserialized,
2731                           unsigned PreviousGeneration)
2732       : Reader(Reader), InterfaceID(InterfaceID), Interface(Interface),
2733         Deserialized(Deserialized), PreviousGeneration(PreviousGeneration),
2734         Tail(0)
2735     {
2736       // Populate the name -> category map with the set of known categories.
2737       for (ObjCInterfaceDecl::known_categories_iterator
2738              Cat = Interface->known_categories_begin(),
2739              CatEnd = Interface->known_categories_end();
2740            Cat != CatEnd; ++Cat) {
2741         if (Cat->getDeclName())
2742           NameCategoryMap[Cat->getDeclName()] = *Cat;
2743 
2744         // Keep track of the tail of the category list.
2745         Tail = *Cat;
2746       }
2747     }
2748 
2749     static bool visit(ModuleFile &M, void *UserData) {
2750       return static_cast<ObjCCategoriesVisitor *>(UserData)->visit(M);
2751     }
2752 
2753     bool visit(ModuleFile &M) {
2754       // If we've loaded all of the category information we care about from
2755       // this module file, we're done.
2756       if (M.Generation <= PreviousGeneration)
2757         return true;
2758 
2759       // Map global ID of the definition down to the local ID used in this
2760       // module file. If there is no such mapping, we'll find nothing here
2761       // (or in any module it imports).
2762       DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID);
2763       if (!LocalID)
2764         return true;
2765 
2766       // Perform a binary search to find the local redeclarations for this
2767       // declaration (if any).
2768       const ObjCCategoriesInfo *Result
2769         = std::lower_bound(M.ObjCCategoriesMap,
2770                            M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap,
2771                            LocalID, CompareObjCCategoriesInfo());
2772       if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap ||
2773           Result->DefinitionID != LocalID) {
2774         // We didn't find anything. If the class definition is in this module
2775         // file, then the module files it depends on cannot have any categories,
2776         // so suppress further lookup.
2777         return Reader.isDeclIDFromModule(InterfaceID, M);
2778       }
2779 
2780       // We found something. Dig out all of the categories.
2781       unsigned Offset = Result->Offset;
2782       unsigned N = M.ObjCCategories[Offset];
2783       M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again
2784       for (unsigned I = 0; I != N; ++I)
2785         add(cast_or_null<ObjCCategoryDecl>(
2786               Reader.GetLocalDecl(M, M.ObjCCategories[Offset++])));
2787       return true;
2788     }
2789   };
2790 }
2791 
2792 void ASTReader::loadObjCCategories(serialization::GlobalDeclID ID,
2793                                    ObjCInterfaceDecl *D,
2794                                    unsigned PreviousGeneration) {
2795   ObjCCategoriesVisitor Visitor(*this, ID, D, CategoriesDeserialized,
2796                                 PreviousGeneration);
2797   ModuleMgr.visit(ObjCCategoriesVisitor::visit, &Visitor);
2798 }
2799 
2800 void ASTDeclReader::UpdateDecl(Decl *D, ModuleFile &ModuleFile,
2801                                const RecordData &Record) {
2802   unsigned Idx = 0;
2803   while (Idx < Record.size()) {
2804     switch ((DeclUpdateKind)Record[Idx++]) {
2805     case UPD_CXX_ADDED_IMPLICIT_MEMBER:
2806       cast<CXXRecordDecl>(D)->addedMember(Reader.ReadDecl(ModuleFile, Record, Idx));
2807       break;
2808 
2809     case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
2810       // It will be added to the template's specializations set when loaded.
2811       (void)Reader.ReadDecl(ModuleFile, Record, Idx);
2812       break;
2813 
2814     case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
2815       NamespaceDecl *Anon
2816         = Reader.ReadDeclAs<NamespaceDecl>(ModuleFile, Record, Idx);
2817 
2818       // Each module has its own anonymous namespace, which is disjoint from
2819       // any other module's anonymous namespaces, so don't attach the anonymous
2820       // namespace at all.
2821       if (ModuleFile.Kind != MK_Module) {
2822         if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(D))
2823           TU->setAnonymousNamespace(Anon);
2824         else
2825           cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon);
2826       }
2827       break;
2828     }
2829 
2830     case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
2831       cast<VarDecl>(D)->getMemberSpecializationInfo()->setPointOfInstantiation(
2832           Reader.ReadSourceLocation(ModuleFile, Record, Idx));
2833       break;
2834 
2835     case UPD_CXX_DEDUCED_RETURN_TYPE: {
2836       FunctionDecl *FD = cast<FunctionDecl>(D);
2837       Reader.Context.adjustDeducedFunctionResultType(
2838           FD, Reader.readType(ModuleFile, Record, Idx));
2839       break;
2840     }
2841 
2842     case UPD_DECL_MARKED_USED: {
2843       D->markUsed(Reader.getContext());
2844       break;
2845     }
2846     }
2847   }
2848 }
2849