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