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