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