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