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