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