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