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->setIdentifier(Record.getIdentifierInfo());
1142   D->CategoryNameLoc = ReadSourceLocation();
1143 }
1144 
1145 void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1146   VisitObjCImplDecl(D);
1147   D->setSuperClass(ReadDeclAs<ObjCInterfaceDecl>());
1148   D->SuperLoc = ReadSourceLocation();
1149   D->setIvarLBraceLoc(ReadSourceLocation());
1150   D->setIvarRBraceLoc(ReadSourceLocation());
1151   D->setHasNonZeroConstructors(Record.readInt());
1152   D->setHasDestructors(Record.readInt());
1153   D->NumIvarInitializers = Record.readInt();
1154   if (D->NumIvarInitializers)
1155     D->IvarInitializers = ReadGlobalOffset();
1156 }
1157 
1158 void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
1159   VisitDecl(D);
1160   D->setAtLoc(ReadSourceLocation());
1161   D->setPropertyDecl(ReadDeclAs<ObjCPropertyDecl>());
1162   D->PropertyIvarDecl = ReadDeclAs<ObjCIvarDecl>();
1163   D->IvarLoc = ReadSourceLocation();
1164   D->setGetterCXXConstructor(Record.readExpr());
1165   D->setSetterCXXAssignment(Record.readExpr());
1166 }
1167 
1168 void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {
1169   VisitDeclaratorDecl(FD);
1170   FD->Mutable = Record.readInt();
1171   if (int BitWidthOrInitializer = Record.readInt()) {
1172     FD->InitStorage.setInt(
1173           static_cast<FieldDecl::InitStorageKind>(BitWidthOrInitializer - 1));
1174     if (FD->InitStorage.getInt() == FieldDecl::ISK_CapturedVLAType) {
1175       // Read captured variable length array.
1176       FD->InitStorage.setPointer(Record.readType().getAsOpaquePtr());
1177     } else {
1178       FD->InitStorage.setPointer(Record.readExpr());
1179     }
1180   }
1181   if (!FD->getDeclName()) {
1182     if (FieldDecl *Tmpl = ReadDeclAs<FieldDecl>())
1183       Reader.getContext().setInstantiatedFromUnnamedFieldDecl(FD, Tmpl);
1184   }
1185   mergeMergeable(FD);
1186 }
1187 
1188 void ASTDeclReader::VisitMSPropertyDecl(MSPropertyDecl *PD) {
1189   VisitDeclaratorDecl(PD);
1190   PD->GetterId = Record.getIdentifierInfo();
1191   PD->SetterId = Record.getIdentifierInfo();
1192 }
1193 
1194 void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
1195   VisitValueDecl(FD);
1196 
1197   FD->ChainingSize = Record.readInt();
1198   assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2");
1199   FD->Chaining = new (Reader.getContext())NamedDecl*[FD->ChainingSize];
1200 
1201   for (unsigned I = 0; I != FD->ChainingSize; ++I)
1202     FD->Chaining[I] = ReadDeclAs<NamedDecl>();
1203 
1204   mergeMergeable(FD);
1205 }
1206 
1207 ASTDeclReader::RedeclarableResult ASTDeclReader::VisitVarDeclImpl(VarDecl *VD) {
1208   RedeclarableResult Redecl = VisitRedeclarable(VD);
1209   VisitDeclaratorDecl(VD);
1210 
1211   VD->VarDeclBits.SClass = (StorageClass)Record.readInt();
1212   VD->VarDeclBits.TSCSpec = Record.readInt();
1213   VD->VarDeclBits.InitStyle = Record.readInt();
1214   if (!isa<ParmVarDecl>(VD)) {
1215     VD->NonParmVarDeclBits.IsThisDeclarationADemotedDefinition =
1216         Record.readInt();
1217     VD->NonParmVarDeclBits.ExceptionVar = Record.readInt();
1218     VD->NonParmVarDeclBits.NRVOVariable = Record.readInt();
1219     VD->NonParmVarDeclBits.CXXForRangeDecl = Record.readInt();
1220     VD->NonParmVarDeclBits.ARCPseudoStrong = Record.readInt();
1221     VD->NonParmVarDeclBits.IsInline = Record.readInt();
1222     VD->NonParmVarDeclBits.IsInlineSpecified = Record.readInt();
1223     VD->NonParmVarDeclBits.IsConstexpr = Record.readInt();
1224     VD->NonParmVarDeclBits.IsInitCapture = Record.readInt();
1225     VD->NonParmVarDeclBits.PreviousDeclInSameBlockScope = Record.readInt();
1226   }
1227   Linkage VarLinkage = Linkage(Record.readInt());
1228   VD->setCachedLinkage(VarLinkage);
1229 
1230   // Reconstruct the one piece of the IdentifierNamespace that we need.
1231   if (VD->getStorageClass() == SC_Extern && VarLinkage != NoLinkage &&
1232       VD->getLexicalDeclContext()->isFunctionOrMethod())
1233     VD->setLocalExternDecl();
1234 
1235   if (uint64_t Val = Record.readInt()) {
1236     VD->setInit(Record.readExpr());
1237     if (Val > 1) { // IsInitKnownICE = 1, IsInitNotICE = 2, IsInitICE = 3
1238       EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
1239       Eval->CheckedICE = true;
1240       Eval->IsICE = Val == 3;
1241     }
1242   }
1243 
1244   enum VarKind {
1245     VarNotTemplate = 0, VarTemplate, StaticDataMemberSpecialization
1246   };
1247   switch ((VarKind)Record.readInt()) {
1248   case VarNotTemplate:
1249     // Only true variables (not parameters or implicit parameters) can be
1250     // merged; the other kinds are not really redeclarable at all.
1251     if (!isa<ParmVarDecl>(VD) && !isa<ImplicitParamDecl>(VD) &&
1252         !isa<VarTemplateSpecializationDecl>(VD))
1253       mergeRedeclarable(VD, Redecl);
1254     break;
1255   case VarTemplate:
1256     // Merged when we merge the template.
1257     VD->setDescribedVarTemplate(ReadDeclAs<VarTemplateDecl>());
1258     break;
1259   case StaticDataMemberSpecialization: { // HasMemberSpecializationInfo.
1260     VarDecl *Tmpl = ReadDeclAs<VarDecl>();
1261     TemplateSpecializationKind TSK =
1262         (TemplateSpecializationKind)Record.readInt();
1263     SourceLocation POI = ReadSourceLocation();
1264     Reader.getContext().setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);
1265     mergeRedeclarable(VD, Redecl);
1266     break;
1267   }
1268   }
1269 
1270   return Redecl;
1271 }
1272 
1273 void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
1274   VisitVarDecl(PD);
1275 }
1276 
1277 void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
1278   VisitVarDecl(PD);
1279   unsigned isObjCMethodParam = Record.readInt();
1280   unsigned scopeDepth = Record.readInt();
1281   unsigned scopeIndex = Record.readInt();
1282   unsigned declQualifier = Record.readInt();
1283   if (isObjCMethodParam) {
1284     assert(scopeDepth == 0);
1285     PD->setObjCMethodScopeInfo(scopeIndex);
1286     PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier;
1287   } else {
1288     PD->setScopeInfo(scopeDepth, scopeIndex);
1289   }
1290   PD->ParmVarDeclBits.IsKNRPromoted = Record.readInt();
1291   PD->ParmVarDeclBits.HasInheritedDefaultArg = Record.readInt();
1292   if (Record.readInt()) // hasUninstantiatedDefaultArg.
1293     PD->setUninstantiatedDefaultArg(Record.readExpr());
1294 
1295   // FIXME: If this is a redeclaration of a function from another module, handle
1296   // inheritance of default arguments.
1297 }
1298 
1299 void ASTDeclReader::VisitDecompositionDecl(DecompositionDecl *DD) {
1300   VisitVarDecl(DD);
1301   BindingDecl **BDs = DD->getTrailingObjects<BindingDecl*>();
1302   for (unsigned I = 0; I != DD->NumBindings; ++I)
1303     BDs[I] = ReadDeclAs<BindingDecl>();
1304 }
1305 
1306 void ASTDeclReader::VisitBindingDecl(BindingDecl *BD) {
1307   VisitValueDecl(BD);
1308   BD->Binding = Record.readExpr();
1309 }
1310 
1311 void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
1312   VisitDecl(AD);
1313   AD->setAsmString(cast<StringLiteral>(Record.readExpr()));
1314   AD->setRParenLoc(ReadSourceLocation());
1315 }
1316 
1317 void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
1318   VisitDecl(BD);
1319   BD->setBody(cast_or_null<CompoundStmt>(Record.readStmt()));
1320   BD->setSignatureAsWritten(GetTypeSourceInfo());
1321   unsigned NumParams = Record.readInt();
1322   SmallVector<ParmVarDecl *, 16> Params;
1323   Params.reserve(NumParams);
1324   for (unsigned I = 0; I != NumParams; ++I)
1325     Params.push_back(ReadDeclAs<ParmVarDecl>());
1326   BD->setParams(Params);
1327 
1328   BD->setIsVariadic(Record.readInt());
1329   BD->setBlockMissingReturnType(Record.readInt());
1330   BD->setIsConversionFromLambda(Record.readInt());
1331 
1332   bool capturesCXXThis = Record.readInt();
1333   unsigned numCaptures = Record.readInt();
1334   SmallVector<BlockDecl::Capture, 16> captures;
1335   captures.reserve(numCaptures);
1336   for (unsigned i = 0; i != numCaptures; ++i) {
1337     VarDecl *decl = ReadDeclAs<VarDecl>();
1338     unsigned flags = Record.readInt();
1339     bool byRef = (flags & 1);
1340     bool nested = (flags & 2);
1341     Expr *copyExpr = ((flags & 4) ? Record.readExpr() : nullptr);
1342 
1343     captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr));
1344   }
1345   BD->setCaptures(Reader.getContext(), captures, capturesCXXThis);
1346 }
1347 
1348 void ASTDeclReader::VisitCapturedDecl(CapturedDecl *CD) {
1349   VisitDecl(CD);
1350   unsigned ContextParamPos = Record.readInt();
1351   CD->setNothrow(Record.readInt() != 0);
1352   // Body is set by VisitCapturedStmt.
1353   for (unsigned I = 0; I < CD->NumParams; ++I) {
1354     if (I != ContextParamPos)
1355       CD->setParam(I, ReadDeclAs<ImplicitParamDecl>());
1356     else
1357       CD->setContextParam(I, ReadDeclAs<ImplicitParamDecl>());
1358   }
1359 }
1360 
1361 void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1362   VisitDecl(D);
1363   D->setLanguage((LinkageSpecDecl::LanguageIDs)Record.readInt());
1364   D->setExternLoc(ReadSourceLocation());
1365   D->setRBraceLoc(ReadSourceLocation());
1366 }
1367 
1368 void ASTDeclReader::VisitExportDecl(ExportDecl *D) {
1369   VisitDecl(D);
1370   D->RBraceLoc = ReadSourceLocation();
1371 }
1372 
1373 void ASTDeclReader::VisitLabelDecl(LabelDecl *D) {
1374   VisitNamedDecl(D);
1375   D->setLocStart(ReadSourceLocation());
1376 }
1377 
1378 void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
1379   RedeclarableResult Redecl = VisitRedeclarable(D);
1380   VisitNamedDecl(D);
1381   D->setInline(Record.readInt());
1382   D->LocStart = ReadSourceLocation();
1383   D->RBraceLoc = ReadSourceLocation();
1384 
1385   // Defer loading the anonymous namespace until we've finished merging
1386   // this namespace; loading it might load a later declaration of the
1387   // same namespace, and we have an invariant that older declarations
1388   // get merged before newer ones try to merge.
1389   GlobalDeclID AnonNamespace = 0;
1390   if (Redecl.getFirstID() == ThisDeclID) {
1391     AnonNamespace = ReadDeclID();
1392   } else {
1393     // Link this namespace back to the first declaration, which has already
1394     // been deserialized.
1395     D->AnonOrFirstNamespaceAndInline.setPointer(D->getFirstDecl());
1396   }
1397 
1398   mergeRedeclarable(D, Redecl);
1399 
1400   if (AnonNamespace) {
1401     // Each module has its own anonymous namespace, which is disjoint from
1402     // any other module's anonymous namespaces, so don't attach the anonymous
1403     // namespace at all.
1404     NamespaceDecl *Anon = cast<NamespaceDecl>(Reader.GetDecl(AnonNamespace));
1405     if (!Record.isModule())
1406       D->setAnonymousNamespace(Anon);
1407   }
1408 }
1409 
1410 void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1411   RedeclarableResult Redecl = VisitRedeclarable(D);
1412   VisitNamedDecl(D);
1413   D->NamespaceLoc = ReadSourceLocation();
1414   D->IdentLoc = ReadSourceLocation();
1415   D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1416   D->Namespace = ReadDeclAs<NamedDecl>();
1417   mergeRedeclarable(D, Redecl);
1418 }
1419 
1420 void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
1421   VisitNamedDecl(D);
1422   D->setUsingLoc(ReadSourceLocation());
1423   D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1424   ReadDeclarationNameLoc(D->DNLoc, D->getDeclName());
1425   D->FirstUsingShadow.setPointer(ReadDeclAs<UsingShadowDecl>());
1426   D->setTypename(Record.readInt());
1427   if (NamedDecl *Pattern = ReadDeclAs<NamedDecl>())
1428     Reader.getContext().setInstantiatedFromUsingDecl(D, Pattern);
1429   mergeMergeable(D);
1430 }
1431 
1432 void ASTDeclReader::VisitUsingPackDecl(UsingPackDecl *D) {
1433   VisitNamedDecl(D);
1434   D->InstantiatedFrom = ReadDeclAs<NamedDecl>();
1435   NamedDecl **Expansions = D->getTrailingObjects<NamedDecl*>();
1436   for (unsigned I = 0; I != D->NumExpansions; ++I)
1437     Expansions[I] = ReadDeclAs<NamedDecl>();
1438   mergeMergeable(D);
1439 }
1440 
1441 void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
1442   RedeclarableResult Redecl = VisitRedeclarable(D);
1443   VisitNamedDecl(D);
1444   D->setTargetDecl(ReadDeclAs<NamedDecl>());
1445   D->UsingOrNextShadow = ReadDeclAs<NamedDecl>();
1446   UsingShadowDecl *Pattern = ReadDeclAs<UsingShadowDecl>();
1447   if (Pattern)
1448     Reader.getContext().setInstantiatedFromUsingShadowDecl(D, Pattern);
1449   mergeRedeclarable(D, Redecl);
1450 }
1451 
1452 void ASTDeclReader::VisitConstructorUsingShadowDecl(
1453     ConstructorUsingShadowDecl *D) {
1454   VisitUsingShadowDecl(D);
1455   D->NominatedBaseClassShadowDecl = ReadDeclAs<ConstructorUsingShadowDecl>();
1456   D->ConstructedBaseClassShadowDecl = ReadDeclAs<ConstructorUsingShadowDecl>();
1457   D->IsVirtual = Record.readInt();
1458 }
1459 
1460 void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1461   VisitNamedDecl(D);
1462   D->UsingLoc = ReadSourceLocation();
1463   D->NamespaceLoc = ReadSourceLocation();
1464   D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1465   D->NominatedNamespace = ReadDeclAs<NamedDecl>();
1466   D->CommonAncestor = ReadDeclAs<DeclContext>();
1467 }
1468 
1469 void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1470   VisitValueDecl(D);
1471   D->setUsingLoc(ReadSourceLocation());
1472   D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1473   ReadDeclarationNameLoc(D->DNLoc, D->getDeclName());
1474   D->EllipsisLoc = ReadSourceLocation();
1475   mergeMergeable(D);
1476 }
1477 
1478 void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
1479                                                UnresolvedUsingTypenameDecl *D) {
1480   VisitTypeDecl(D);
1481   D->TypenameLocation = ReadSourceLocation();
1482   D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1483   D->EllipsisLoc = ReadSourceLocation();
1484   mergeMergeable(D);
1485 }
1486 
1487 void ASTDeclReader::ReadCXXDefinitionData(
1488                                    struct CXXRecordDecl::DefinitionData &Data) {
1489   // Note: the caller has deserialized the IsLambda bit already.
1490   Data.UserDeclaredConstructor = Record.readInt();
1491   Data.UserDeclaredSpecialMembers = Record.readInt();
1492   Data.Aggregate = Record.readInt();
1493   Data.PlainOldData = Record.readInt();
1494   Data.Empty = Record.readInt();
1495   Data.Polymorphic = Record.readInt();
1496   Data.Abstract = Record.readInt();
1497   Data.IsStandardLayout = Record.readInt();
1498   Data.HasNoNonEmptyBases = Record.readInt();
1499   Data.HasPrivateFields = Record.readInt();
1500   Data.HasProtectedFields = Record.readInt();
1501   Data.HasPublicFields = Record.readInt();
1502   Data.HasMutableFields = Record.readInt();
1503   Data.HasVariantMembers = Record.readInt();
1504   Data.HasOnlyCMembers = Record.readInt();
1505   Data.HasInClassInitializer = Record.readInt();
1506   Data.HasUninitializedReferenceMember = Record.readInt();
1507   Data.HasUninitializedFields = Record.readInt();
1508   Data.HasInheritedConstructor = Record.readInt();
1509   Data.HasInheritedAssignment = Record.readInt();
1510   Data.NeedOverloadResolutionForMoveConstructor = Record.readInt();
1511   Data.NeedOverloadResolutionForMoveAssignment = Record.readInt();
1512   Data.NeedOverloadResolutionForDestructor = Record.readInt();
1513   Data.DefaultedMoveConstructorIsDeleted = Record.readInt();
1514   Data.DefaultedMoveAssignmentIsDeleted = Record.readInt();
1515   Data.DefaultedDestructorIsDeleted = Record.readInt();
1516   Data.HasTrivialSpecialMembers = Record.readInt();
1517   Data.DeclaredNonTrivialSpecialMembers = Record.readInt();
1518   Data.HasIrrelevantDestructor = Record.readInt();
1519   Data.HasConstexprNonCopyMoveConstructor = Record.readInt();
1520   Data.HasDefaultedDefaultConstructor = Record.readInt();
1521   Data.DefaultedDefaultConstructorIsConstexpr = Record.readInt();
1522   Data.HasConstexprDefaultConstructor = Record.readInt();
1523   Data.HasNonLiteralTypeFieldsOrBases = Record.readInt();
1524   Data.ComputedVisibleConversions = Record.readInt();
1525   Data.UserProvidedDefaultConstructor = Record.readInt();
1526   Data.DeclaredSpecialMembers = Record.readInt();
1527   Data.ImplicitCopyConstructorHasConstParam = 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(ImplicitCopyConstructorHasConstParam)
1658   MATCH_FIELD(ImplicitCopyAssignmentHasConstParam)
1659   OR_FIELD(HasDeclaredCopyConstructorWithConstParam)
1660   OR_FIELD(HasDeclaredCopyAssignmentWithConstParam)
1661   MATCH_FIELD(IsLambda)
1662   MATCH_FIELD(ODRHash)
1663 #undef OR_FIELD
1664 #undef MATCH_FIELD
1665 
1666   if (DD.NumBases != MergeDD.NumBases || DD.NumVBases != MergeDD.NumVBases)
1667     DetectedOdrViolation = true;
1668   // FIXME: Issue a diagnostic if the base classes don't match when we come
1669   // to lazily load them.
1670 
1671   // FIXME: Issue a diagnostic if the list of conversion functions doesn't
1672   // match when we come to lazily load them.
1673   if (MergeDD.ComputedVisibleConversions && !DD.ComputedVisibleConversions) {
1674     DD.VisibleConversions = std::move(MergeDD.VisibleConversions);
1675     DD.ComputedVisibleConversions = true;
1676   }
1677 
1678   // FIXME: Issue a diagnostic if FirstFriend doesn't match when we come to
1679   // lazily load it.
1680 
1681   if (DD.IsLambda) {
1682     // FIXME: ODR-checking for merging lambdas (this happens, for instance,
1683     // when they occur within the body of a function template specialization).
1684   }
1685 
1686   if (DetectedOdrViolation)
1687     Reader.PendingOdrMergeFailures[DD.Definition].push_back(MergeDD.Definition);
1688 }
1689 
1690 void ASTDeclReader::ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update) {
1691   struct CXXRecordDecl::DefinitionData *DD;
1692   ASTContext &C = Reader.getContext();
1693 
1694   // Determine whether this is a lambda closure type, so that we can
1695   // allocate the appropriate DefinitionData structure.
1696   bool IsLambda = Record.readInt();
1697   if (IsLambda)
1698     DD = new (C) CXXRecordDecl::LambdaDefinitionData(D, nullptr, false, false,
1699                                                      LCD_None);
1700   else
1701     DD = new (C) struct CXXRecordDecl::DefinitionData(D);
1702 
1703   ReadCXXDefinitionData(*DD);
1704 
1705   // We might already have a definition for this record. This can happen either
1706   // because we're reading an update record, or because we've already done some
1707   // merging. Either way, just merge into it.
1708   CXXRecordDecl *Canon = D->getCanonicalDecl();
1709   if (Canon->DefinitionData) {
1710     MergeDefinitionData(Canon, std::move(*DD));
1711     D->DefinitionData = Canon->DefinitionData;
1712     return;
1713   }
1714 
1715   // Mark this declaration as being a definition.
1716   D->IsCompleteDefinition = true;
1717   D->DefinitionData = DD;
1718 
1719   // If this is not the first declaration or is an update record, we can have
1720   // other redeclarations already. Make a note that we need to propagate the
1721   // DefinitionData pointer onto them.
1722   if (Update || Canon != D) {
1723     Canon->DefinitionData = D->DefinitionData;
1724     Reader.PendingDefinitions.insert(D);
1725   }
1726 }
1727 
1728 ASTDeclReader::RedeclarableResult
1729 ASTDeclReader::VisitCXXRecordDeclImpl(CXXRecordDecl *D) {
1730   RedeclarableResult Redecl = VisitRecordDeclImpl(D);
1731 
1732   ASTContext &C = Reader.getContext();
1733 
1734   enum CXXRecKind {
1735     CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
1736   };
1737   switch ((CXXRecKind)Record.readInt()) {
1738   case CXXRecNotTemplate:
1739     // Merged when we merge the folding set entry in the primary template.
1740     if (!isa<ClassTemplateSpecializationDecl>(D))
1741       mergeRedeclarable(D, Redecl);
1742     break;
1743   case CXXRecTemplate: {
1744     // Merged when we merge the template.
1745     ClassTemplateDecl *Template = ReadDeclAs<ClassTemplateDecl>();
1746     D->TemplateOrInstantiation = Template;
1747     if (!Template->getTemplatedDecl()) {
1748       // We've not actually loaded the ClassTemplateDecl yet, because we're
1749       // currently being loaded as its pattern. Rely on it to set up our
1750       // TypeForDecl (see VisitClassTemplateDecl).
1751       //
1752       // Beware: we do not yet know our canonical declaration, and may still
1753       // get merged once the surrounding class template has got off the ground.
1754       TypeIDForTypeDecl = 0;
1755     }
1756     break;
1757   }
1758   case CXXRecMemberSpecialization: {
1759     CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>();
1760     TemplateSpecializationKind TSK =
1761         (TemplateSpecializationKind)Record.readInt();
1762     SourceLocation POI = ReadSourceLocation();
1763     MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
1764     MSI->setPointOfInstantiation(POI);
1765     D->TemplateOrInstantiation = MSI;
1766     mergeRedeclarable(D, Redecl);
1767     break;
1768   }
1769   }
1770 
1771   bool WasDefinition = Record.readInt();
1772   if (WasDefinition)
1773     ReadCXXRecordDefinition(D, /*Update*/false);
1774   else
1775     // Propagate DefinitionData pointer from the canonical declaration.
1776     D->DefinitionData = D->getCanonicalDecl()->DefinitionData;
1777 
1778   // Lazily load the key function to avoid deserializing every method so we can
1779   // compute it.
1780   if (WasDefinition) {
1781     DeclID KeyFn = ReadDeclID();
1782     if (KeyFn && D->IsCompleteDefinition)
1783       // FIXME: This is wrong for the ARM ABI, where some other module may have
1784       // made this function no longer be a key function. We need an update
1785       // record or similar for that case.
1786       C.KeyFunctions[D] = KeyFn;
1787   }
1788 
1789   return Redecl;
1790 }
1791 
1792 void ASTDeclReader::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
1793   VisitFunctionDecl(D);
1794 }
1795 
1796 void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
1797   VisitFunctionDecl(D);
1798 
1799   unsigned NumOverridenMethods = Record.readInt();
1800   if (D->isCanonicalDecl()) {
1801     while (NumOverridenMethods--) {
1802       // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
1803       // MD may be initializing.
1804       if (CXXMethodDecl *MD = ReadDeclAs<CXXMethodDecl>())
1805         Reader.getContext().addOverriddenMethod(D, MD->getCanonicalDecl());
1806     }
1807   } else {
1808     // We don't care about which declarations this used to override; we get
1809     // the relevant information from the canonical declaration.
1810     Record.skipInts(NumOverridenMethods);
1811   }
1812 }
1813 
1814 void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1815   // We need the inherited constructor information to merge the declaration,
1816   // so we have to read it before we call VisitCXXMethodDecl.
1817   if (D->isInheritingConstructor()) {
1818     auto *Shadow = ReadDeclAs<ConstructorUsingShadowDecl>();
1819     auto *Ctor = ReadDeclAs<CXXConstructorDecl>();
1820     *D->getTrailingObjects<InheritedConstructor>() =
1821         InheritedConstructor(Shadow, Ctor);
1822   }
1823 
1824   VisitCXXMethodDecl(D);
1825 }
1826 
1827 void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1828   VisitCXXMethodDecl(D);
1829 
1830   if (auto *OperatorDelete = ReadDeclAs<FunctionDecl>()) {
1831     auto *Canon = cast<CXXDestructorDecl>(D->getCanonicalDecl());
1832     // FIXME: Check consistency if we have an old and new operator delete.
1833     if (!Canon->OperatorDelete)
1834       Canon->OperatorDelete = OperatorDelete;
1835   }
1836 }
1837 
1838 void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
1839   VisitCXXMethodDecl(D);
1840 }
1841 
1842 void ASTDeclReader::VisitImportDecl(ImportDecl *D) {
1843   VisitDecl(D);
1844   D->ImportedAndComplete.setPointer(readModule());
1845   D->ImportedAndComplete.setInt(Record.readInt());
1846   SourceLocation *StoredLocs = D->getTrailingObjects<SourceLocation>();
1847   for (unsigned I = 0, N = Record.back(); I != N; ++I)
1848     StoredLocs[I] = ReadSourceLocation();
1849   Record.skipInts(1); // The number of stored source locations.
1850 }
1851 
1852 void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
1853   VisitDecl(D);
1854   D->setColonLoc(ReadSourceLocation());
1855 }
1856 
1857 void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
1858   VisitDecl(D);
1859   if (Record.readInt()) // hasFriendDecl
1860     D->Friend = ReadDeclAs<NamedDecl>();
1861   else
1862     D->Friend = GetTypeSourceInfo();
1863   for (unsigned i = 0; i != D->NumTPLists; ++i)
1864     D->getTrailingObjects<TemplateParameterList *>()[i] =
1865         Record.readTemplateParameterList();
1866   D->NextFriend = ReadDeclID();
1867   D->UnsupportedFriend = (Record.readInt() != 0);
1868   D->FriendLoc = ReadSourceLocation();
1869 }
1870 
1871 void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
1872   VisitDecl(D);
1873   unsigned NumParams = Record.readInt();
1874   D->NumParams = NumParams;
1875   D->Params = new TemplateParameterList*[NumParams];
1876   for (unsigned i = 0; i != NumParams; ++i)
1877     D->Params[i] = Record.readTemplateParameterList();
1878   if (Record.readInt()) // HasFriendDecl
1879     D->Friend = ReadDeclAs<NamedDecl>();
1880   else
1881     D->Friend = GetTypeSourceInfo();
1882   D->FriendLoc = ReadSourceLocation();
1883 }
1884 
1885 DeclID ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
1886   VisitNamedDecl(D);
1887 
1888   DeclID PatternID = ReadDeclID();
1889   NamedDecl *TemplatedDecl = cast_or_null<NamedDecl>(Reader.GetDecl(PatternID));
1890   TemplateParameterList *TemplateParams = Record.readTemplateParameterList();
1891   // FIXME handle associated constraints
1892   D->init(TemplatedDecl, TemplateParams);
1893 
1894   return PatternID;
1895 }
1896 
1897 ASTDeclReader::RedeclarableResult
1898 ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
1899   RedeclarableResult Redecl = VisitRedeclarable(D);
1900 
1901   // Make sure we've allocated the Common pointer first. We do this before
1902   // VisitTemplateDecl so that getCommonPtr() can be used during initialization.
1903   RedeclarableTemplateDecl *CanonD = D->getCanonicalDecl();
1904   if (!CanonD->Common) {
1905     CanonD->Common = CanonD->newCommon(Reader.getContext());
1906     Reader.PendingDefinitions.insert(CanonD);
1907   }
1908   D->Common = CanonD->Common;
1909 
1910   // If this is the first declaration of the template, fill in the information
1911   // for the 'common' pointer.
1912   if (ThisDeclID == Redecl.getFirstID()) {
1913     if (RedeclarableTemplateDecl *RTD
1914           = ReadDeclAs<RedeclarableTemplateDecl>()) {
1915       assert(RTD->getKind() == D->getKind() &&
1916              "InstantiatedFromMemberTemplate kind mismatch");
1917       D->setInstantiatedFromMemberTemplate(RTD);
1918       if (Record.readInt())
1919         D->setMemberSpecialization();
1920     }
1921   }
1922 
1923   DeclID PatternID = VisitTemplateDecl(D);
1924   D->IdentifierNamespace = Record.readInt();
1925 
1926   mergeRedeclarable(D, Redecl, PatternID);
1927 
1928   // If we merged the template with a prior declaration chain, merge the common
1929   // pointer.
1930   // FIXME: Actually merge here, don't just overwrite.
1931   D->Common = D->getCanonicalDecl()->Common;
1932 
1933   return Redecl;
1934 }
1935 
1936 static DeclID *newDeclIDList(ASTContext &Context, DeclID *Old,
1937                              SmallVectorImpl<DeclID> &IDs) {
1938   assert(!IDs.empty() && "no IDs to add to list");
1939   if (Old) {
1940     IDs.insert(IDs.end(), Old + 1, Old + 1 + Old[0]);
1941     std::sort(IDs.begin(), IDs.end());
1942     IDs.erase(std::unique(IDs.begin(), IDs.end()), IDs.end());
1943   }
1944 
1945   auto *Result = new (Context) DeclID[1 + IDs.size()];
1946   *Result = IDs.size();
1947   std::copy(IDs.begin(), IDs.end(), Result + 1);
1948   return Result;
1949 }
1950 
1951 void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1952   RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
1953 
1954   if (ThisDeclID == Redecl.getFirstID()) {
1955     // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
1956     // the specializations.
1957     SmallVector<serialization::DeclID, 32> SpecIDs;
1958     ReadDeclIDList(SpecIDs);
1959 
1960     if (!SpecIDs.empty()) {
1961       auto *CommonPtr = D->getCommonPtr();
1962       CommonPtr->LazySpecializations = newDeclIDList(
1963           Reader.getContext(), CommonPtr->LazySpecializations, SpecIDs);
1964     }
1965   }
1966 
1967   if (D->getTemplatedDecl()->TemplateOrInstantiation) {
1968     // We were loaded before our templated declaration was. We've not set up
1969     // its corresponding type yet (see VisitCXXRecordDeclImpl), so reconstruct
1970     // it now.
1971     Reader.Context.getInjectedClassNameType(
1972         D->getTemplatedDecl(), D->getInjectedClassNameSpecialization());
1973   }
1974 }
1975 
1976 void ASTDeclReader::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
1977   llvm_unreachable("BuiltinTemplates are not serialized");
1978 }
1979 
1980 /// TODO: Unify with ClassTemplateDecl version?
1981 ///       May require unifying ClassTemplateDecl and
1982 ///        VarTemplateDecl beyond TemplateDecl...
1983 void ASTDeclReader::VisitVarTemplateDecl(VarTemplateDecl *D) {
1984   RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
1985 
1986   if (ThisDeclID == Redecl.getFirstID()) {
1987     // This VarTemplateDecl owns a CommonPtr; read it to keep track of all of
1988     // the specializations.
1989     SmallVector<serialization::DeclID, 32> SpecIDs;
1990     ReadDeclIDList(SpecIDs);
1991 
1992     if (!SpecIDs.empty()) {
1993       auto *CommonPtr = D->getCommonPtr();
1994       CommonPtr->LazySpecializations = newDeclIDList(
1995           Reader.getContext(), CommonPtr->LazySpecializations, SpecIDs);
1996     }
1997   }
1998 }
1999 
2000 ASTDeclReader::RedeclarableResult
2001 ASTDeclReader::VisitClassTemplateSpecializationDeclImpl(
2002     ClassTemplateSpecializationDecl *D) {
2003   RedeclarableResult Redecl = VisitCXXRecordDeclImpl(D);
2004 
2005   ASTContext &C = Reader.getContext();
2006   if (Decl *InstD = ReadDecl()) {
2007     if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
2008       D->SpecializedTemplate = CTD;
2009     } else {
2010       SmallVector<TemplateArgument, 8> TemplArgs;
2011       Record.readTemplateArgumentList(TemplArgs);
2012       TemplateArgumentList *ArgList
2013         = TemplateArgumentList::CreateCopy(C, TemplArgs);
2014       ClassTemplateSpecializationDecl::SpecializedPartialSpecialization *PS
2015           = new (C) ClassTemplateSpecializationDecl::
2016                                              SpecializedPartialSpecialization();
2017       PS->PartialSpecialization
2018           = cast<ClassTemplatePartialSpecializationDecl>(InstD);
2019       PS->TemplateArgs = ArgList;
2020       D->SpecializedTemplate = PS;
2021     }
2022   }
2023 
2024   SmallVector<TemplateArgument, 8> TemplArgs;
2025   Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
2026   D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs);
2027   D->PointOfInstantiation = ReadSourceLocation();
2028   D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
2029 
2030   bool writtenAsCanonicalDecl = Record.readInt();
2031   if (writtenAsCanonicalDecl) {
2032     ClassTemplateDecl *CanonPattern = ReadDeclAs<ClassTemplateDecl>();
2033     if (D->isCanonicalDecl()) { // It's kept in the folding set.
2034       // Set this as, or find, the canonical declaration for this specialization
2035       ClassTemplateSpecializationDecl *CanonSpec;
2036       if (ClassTemplatePartialSpecializationDecl *Partial =
2037               dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
2038         CanonSpec = CanonPattern->getCommonPtr()->PartialSpecializations
2039             .GetOrInsertNode(Partial);
2040       } else {
2041         CanonSpec =
2042             CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
2043       }
2044       // If there was already a canonical specialization, merge into it.
2045       if (CanonSpec != D) {
2046         mergeRedeclarable<TagDecl>(D, CanonSpec, Redecl);
2047 
2048         // This declaration might be a definition. Merge with any existing
2049         // definition.
2050         if (auto *DDD = D->DefinitionData) {
2051           if (CanonSpec->DefinitionData)
2052             MergeDefinitionData(CanonSpec, std::move(*DDD));
2053           else
2054             CanonSpec->DefinitionData = D->DefinitionData;
2055         }
2056         D->DefinitionData = CanonSpec->DefinitionData;
2057       }
2058     }
2059   }
2060 
2061   // Explicit info.
2062   if (TypeSourceInfo *TyInfo = GetTypeSourceInfo()) {
2063     ClassTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo
2064         = new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
2065     ExplicitInfo->TypeAsWritten = TyInfo;
2066     ExplicitInfo->ExternLoc = ReadSourceLocation();
2067     ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation();
2068     D->ExplicitInfo = ExplicitInfo;
2069   }
2070 
2071   return Redecl;
2072 }
2073 
2074 void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
2075                                     ClassTemplatePartialSpecializationDecl *D) {
2076   RedeclarableResult Redecl = VisitClassTemplateSpecializationDeclImpl(D);
2077 
2078   D->TemplateParams = Record.readTemplateParameterList();
2079   D->ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2080 
2081   // These are read/set from/to the first declaration.
2082   if (ThisDeclID == Redecl.getFirstID()) {
2083     D->InstantiatedFromMember.setPointer(
2084       ReadDeclAs<ClassTemplatePartialSpecializationDecl>());
2085     D->InstantiatedFromMember.setInt(Record.readInt());
2086   }
2087 }
2088 
2089 void ASTDeclReader::VisitClassScopeFunctionSpecializationDecl(
2090                                     ClassScopeFunctionSpecializationDecl *D) {
2091   VisitDecl(D);
2092   D->Specialization = ReadDeclAs<CXXMethodDecl>();
2093 }
2094 
2095 void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
2096   RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2097 
2098   if (ThisDeclID == Redecl.getFirstID()) {
2099     // This FunctionTemplateDecl owns a CommonPtr; read it.
2100     SmallVector<serialization::DeclID, 32> SpecIDs;
2101     ReadDeclIDList(SpecIDs);
2102 
2103     if (!SpecIDs.empty()) {
2104       auto *CommonPtr = D->getCommonPtr();
2105       CommonPtr->LazySpecializations = newDeclIDList(
2106           Reader.getContext(), CommonPtr->LazySpecializations, SpecIDs);
2107     }
2108   }
2109 }
2110 
2111 /// TODO: Unify with ClassTemplateSpecializationDecl version?
2112 ///       May require unifying ClassTemplate(Partial)SpecializationDecl and
2113 ///        VarTemplate(Partial)SpecializationDecl with a new data
2114 ///        structure Template(Partial)SpecializationDecl, and
2115 ///        using Template(Partial)SpecializationDecl as input type.
2116 ASTDeclReader::RedeclarableResult
2117 ASTDeclReader::VisitVarTemplateSpecializationDeclImpl(
2118     VarTemplateSpecializationDecl *D) {
2119   RedeclarableResult Redecl = VisitVarDeclImpl(D);
2120 
2121   ASTContext &C = Reader.getContext();
2122   if (Decl *InstD = ReadDecl()) {
2123     if (VarTemplateDecl *VTD = dyn_cast<VarTemplateDecl>(InstD)) {
2124       D->SpecializedTemplate = VTD;
2125     } else {
2126       SmallVector<TemplateArgument, 8> TemplArgs;
2127       Record.readTemplateArgumentList(TemplArgs);
2128       TemplateArgumentList *ArgList = TemplateArgumentList::CreateCopy(
2129           C, TemplArgs);
2130       VarTemplateSpecializationDecl::SpecializedPartialSpecialization *PS =
2131           new (C)
2132           VarTemplateSpecializationDecl::SpecializedPartialSpecialization();
2133       PS->PartialSpecialization =
2134           cast<VarTemplatePartialSpecializationDecl>(InstD);
2135       PS->TemplateArgs = ArgList;
2136       D->SpecializedTemplate = PS;
2137     }
2138   }
2139 
2140   // Explicit info.
2141   if (TypeSourceInfo *TyInfo = GetTypeSourceInfo()) {
2142     VarTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo =
2143         new (C) VarTemplateSpecializationDecl::ExplicitSpecializationInfo;
2144     ExplicitInfo->TypeAsWritten = TyInfo;
2145     ExplicitInfo->ExternLoc = ReadSourceLocation();
2146     ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation();
2147     D->ExplicitInfo = ExplicitInfo;
2148   }
2149 
2150   SmallVector<TemplateArgument, 8> TemplArgs;
2151   Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
2152   D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs);
2153   D->PointOfInstantiation = ReadSourceLocation();
2154   D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
2155 
2156   bool writtenAsCanonicalDecl = Record.readInt();
2157   if (writtenAsCanonicalDecl) {
2158     VarTemplateDecl *CanonPattern = ReadDeclAs<VarTemplateDecl>();
2159     if (D->isCanonicalDecl()) { // It's kept in the folding set.
2160       // FIXME: If it's already present, merge it.
2161       if (VarTemplatePartialSpecializationDecl *Partial =
2162               dyn_cast<VarTemplatePartialSpecializationDecl>(D)) {
2163         CanonPattern->getCommonPtr()->PartialSpecializations
2164             .GetOrInsertNode(Partial);
2165       } else {
2166         CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
2167       }
2168     }
2169   }
2170 
2171   return Redecl;
2172 }
2173 
2174 /// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2175 ///       May require unifying ClassTemplate(Partial)SpecializationDecl and
2176 ///        VarTemplate(Partial)SpecializationDecl with a new data
2177 ///        structure Template(Partial)SpecializationDecl, and
2178 ///        using Template(Partial)SpecializationDecl as input type.
2179 void ASTDeclReader::VisitVarTemplatePartialSpecializationDecl(
2180     VarTemplatePartialSpecializationDecl *D) {
2181   RedeclarableResult Redecl = VisitVarTemplateSpecializationDeclImpl(D);
2182 
2183   D->TemplateParams = Record.readTemplateParameterList();
2184   D->ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2185 
2186   // These are read/set from/to the first declaration.
2187   if (ThisDeclID == Redecl.getFirstID()) {
2188     D->InstantiatedFromMember.setPointer(
2189         ReadDeclAs<VarTemplatePartialSpecializationDecl>());
2190     D->InstantiatedFromMember.setInt(Record.readInt());
2191   }
2192 }
2193 
2194 void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
2195   VisitTypeDecl(D);
2196 
2197   D->setDeclaredWithTypename(Record.readInt());
2198 
2199   if (Record.readInt())
2200     D->setDefaultArgument(GetTypeSourceInfo());
2201 }
2202 
2203 void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
2204   VisitDeclaratorDecl(D);
2205   // TemplateParmPosition.
2206   D->setDepth(Record.readInt());
2207   D->setPosition(Record.readInt());
2208   if (D->isExpandedParameterPack()) {
2209     auto TypesAndInfos =
2210         D->getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
2211     for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2212       new (&TypesAndInfos[I].first) QualType(Record.readType());
2213       TypesAndInfos[I].second = GetTypeSourceInfo();
2214     }
2215   } else {
2216     // Rest of NonTypeTemplateParmDecl.
2217     D->ParameterPack = Record.readInt();
2218     if (Record.readInt())
2219       D->setDefaultArgument(Record.readExpr());
2220   }
2221 }
2222 
2223 void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
2224   VisitTemplateDecl(D);
2225   // TemplateParmPosition.
2226   D->setDepth(Record.readInt());
2227   D->setPosition(Record.readInt());
2228   if (D->isExpandedParameterPack()) {
2229     TemplateParameterList **Data =
2230         D->getTrailingObjects<TemplateParameterList *>();
2231     for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2232          I != N; ++I)
2233       Data[I] = Record.readTemplateParameterList();
2234   } else {
2235     // Rest of TemplateTemplateParmDecl.
2236     D->ParameterPack = Record.readInt();
2237     if (Record.readInt())
2238       D->setDefaultArgument(Reader.getContext(),
2239                             Record.readTemplateArgumentLoc());
2240   }
2241 }
2242 
2243 void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
2244   VisitRedeclarableTemplateDecl(D);
2245 }
2246 
2247 void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
2248   VisitDecl(D);
2249   D->AssertExprAndFailed.setPointer(Record.readExpr());
2250   D->AssertExprAndFailed.setInt(Record.readInt());
2251   D->Message = cast_or_null<StringLiteral>(Record.readExpr());
2252   D->RParenLoc = ReadSourceLocation();
2253 }
2254 
2255 void ASTDeclReader::VisitEmptyDecl(EmptyDecl *D) {
2256   VisitDecl(D);
2257 }
2258 
2259 std::pair<uint64_t, uint64_t>
2260 ASTDeclReader::VisitDeclContext(DeclContext *DC) {
2261   uint64_t LexicalOffset = ReadLocalOffset();
2262   uint64_t VisibleOffset = ReadLocalOffset();
2263   return std::make_pair(LexicalOffset, VisibleOffset);
2264 }
2265 
2266 template <typename T>
2267 ASTDeclReader::RedeclarableResult
2268 ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
2269   DeclID FirstDeclID = ReadDeclID();
2270   Decl *MergeWith = nullptr;
2271 
2272   bool IsKeyDecl = ThisDeclID == FirstDeclID;
2273   bool IsFirstLocalDecl = false;
2274 
2275   uint64_t RedeclOffset = 0;
2276 
2277   // 0 indicates that this declaration was the only declaration of its entity,
2278   // and is used for space optimization.
2279   if (FirstDeclID == 0) {
2280     FirstDeclID = ThisDeclID;
2281     IsKeyDecl = true;
2282     IsFirstLocalDecl = true;
2283   } else if (unsigned N = Record.readInt()) {
2284     // This declaration was the first local declaration, but may have imported
2285     // other declarations.
2286     IsKeyDecl = N == 1;
2287     IsFirstLocalDecl = true;
2288 
2289     // We have some declarations that must be before us in our redeclaration
2290     // chain. Read them now, and remember that we ought to merge with one of
2291     // them.
2292     // FIXME: Provide a known merge target to the second and subsequent such
2293     // declaration.
2294     for (unsigned I = 0; I != N - 1; ++I)
2295       MergeWith = ReadDecl();
2296 
2297     RedeclOffset = ReadLocalOffset();
2298   } else {
2299     // This declaration was not the first local declaration. Read the first
2300     // local declaration now, to trigger the import of other redeclarations.
2301     (void)ReadDecl();
2302   }
2303 
2304   T *FirstDecl = cast_or_null<T>(Reader.GetDecl(FirstDeclID));
2305   if (FirstDecl != D) {
2306     // We delay loading of the redeclaration chain to avoid deeply nested calls.
2307     // We temporarily set the first (canonical) declaration as the previous one
2308     // which is the one that matters and mark the real previous DeclID to be
2309     // loaded & attached later on.
2310     D->RedeclLink = Redeclarable<T>::PreviousDeclLink(FirstDecl);
2311     D->First = FirstDecl->getCanonicalDecl();
2312   }
2313 
2314   T *DAsT = static_cast<T*>(D);
2315 
2316   // Note that we need to load local redeclarations of this decl and build a
2317   // decl chain for them. This must happen *after* we perform the preloading
2318   // above; this ensures that the redeclaration chain is built in the correct
2319   // order.
2320   if (IsFirstLocalDecl)
2321     Reader.PendingDeclChains.push_back(std::make_pair(DAsT, RedeclOffset));
2322 
2323   return RedeclarableResult(MergeWith, FirstDeclID, IsKeyDecl);
2324 }
2325 
2326 /// \brief Attempts to merge the given declaration (D) with another declaration
2327 /// of the same entity.
2328 template<typename T>
2329 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase,
2330                                       RedeclarableResult &Redecl,
2331                                       DeclID TemplatePatternID) {
2332   // If modules are not available, there is no reason to perform this merge.
2333   if (!Reader.getContext().getLangOpts().Modules)
2334     return;
2335 
2336   // If we're not the canonical declaration, we don't need to merge.
2337   if (!DBase->isFirstDecl())
2338     return;
2339 
2340   T *D = static_cast<T*>(DBase);
2341 
2342   if (auto *Existing = Redecl.getKnownMergeTarget())
2343     // We already know of an existing declaration we should merge with.
2344     mergeRedeclarable(D, cast<T>(Existing), Redecl, TemplatePatternID);
2345   else if (FindExistingResult ExistingRes = findExisting(D))
2346     if (T *Existing = ExistingRes)
2347       mergeRedeclarable(D, Existing, Redecl, TemplatePatternID);
2348 }
2349 
2350 /// \brief "Cast" to type T, asserting if we don't have an implicit conversion.
2351 /// We use this to put code in a template that will only be valid for certain
2352 /// instantiations.
2353 template<typename T> static T assert_cast(T t) { return t; }
2354 template<typename T> static T assert_cast(...) {
2355   llvm_unreachable("bad assert_cast");
2356 }
2357 
2358 /// \brief Merge together the pattern declarations from two template
2359 /// declarations.
2360 void ASTDeclReader::mergeTemplatePattern(RedeclarableTemplateDecl *D,
2361                                          RedeclarableTemplateDecl *Existing,
2362                                          DeclID DsID, bool IsKeyDecl) {
2363   auto *DPattern = D->getTemplatedDecl();
2364   auto *ExistingPattern = Existing->getTemplatedDecl();
2365   RedeclarableResult Result(/*MergeWith*/ ExistingPattern,
2366                             DPattern->getCanonicalDecl()->getGlobalID(),
2367                             IsKeyDecl);
2368 
2369   if (auto *DClass = dyn_cast<CXXRecordDecl>(DPattern)) {
2370     // Merge with any existing definition.
2371     // FIXME: This is duplicated in several places. Refactor.
2372     auto *ExistingClass =
2373         cast<CXXRecordDecl>(ExistingPattern)->getCanonicalDecl();
2374     if (auto *DDD = DClass->DefinitionData) {
2375       if (ExistingClass->DefinitionData) {
2376         MergeDefinitionData(ExistingClass, std::move(*DDD));
2377       } else {
2378         ExistingClass->DefinitionData = DClass->DefinitionData;
2379         // We may have skipped this before because we thought that DClass
2380         // was the canonical declaration.
2381         Reader.PendingDefinitions.insert(DClass);
2382       }
2383     }
2384     DClass->DefinitionData = ExistingClass->DefinitionData;
2385 
2386     return mergeRedeclarable(DClass, cast<TagDecl>(ExistingPattern),
2387                              Result);
2388   }
2389   if (auto *DFunction = dyn_cast<FunctionDecl>(DPattern))
2390     return mergeRedeclarable(DFunction, cast<FunctionDecl>(ExistingPattern),
2391                              Result);
2392   if (auto *DVar = dyn_cast<VarDecl>(DPattern))
2393     return mergeRedeclarable(DVar, cast<VarDecl>(ExistingPattern), Result);
2394   if (auto *DAlias = dyn_cast<TypeAliasDecl>(DPattern))
2395     return mergeRedeclarable(DAlias, cast<TypedefNameDecl>(ExistingPattern),
2396                              Result);
2397   llvm_unreachable("merged an unknown kind of redeclarable template");
2398 }
2399 
2400 /// \brief Attempts to merge the given declaration (D) with another declaration
2401 /// of the same entity.
2402 template<typename T>
2403 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase, T *Existing,
2404                                       RedeclarableResult &Redecl,
2405                                       DeclID TemplatePatternID) {
2406   T *D = static_cast<T*>(DBase);
2407   T *ExistingCanon = Existing->getCanonicalDecl();
2408   T *DCanon = D->getCanonicalDecl();
2409   if (ExistingCanon != DCanon) {
2410     assert(DCanon->getGlobalID() == Redecl.getFirstID() &&
2411            "already merged this declaration");
2412 
2413     // Have our redeclaration link point back at the canonical declaration
2414     // of the existing declaration, so that this declaration has the
2415     // appropriate canonical declaration.
2416     D->RedeclLink = Redeclarable<T>::PreviousDeclLink(ExistingCanon);
2417     D->First = ExistingCanon;
2418     ExistingCanon->Used |= D->Used;
2419     D->Used = false;
2420 
2421     // When we merge a namespace, update its pointer to the first namespace.
2422     // We cannot have loaded any redeclarations of this declaration yet, so
2423     // there's nothing else that needs to be updated.
2424     if (auto *Namespace = dyn_cast<NamespaceDecl>(D))
2425       Namespace->AnonOrFirstNamespaceAndInline.setPointer(
2426           assert_cast<NamespaceDecl*>(ExistingCanon));
2427 
2428     // When we merge a template, merge its pattern.
2429     if (auto *DTemplate = dyn_cast<RedeclarableTemplateDecl>(D))
2430       mergeTemplatePattern(
2431           DTemplate, assert_cast<RedeclarableTemplateDecl*>(ExistingCanon),
2432           TemplatePatternID, Redecl.isKeyDecl());
2433 
2434     // If this declaration is a key declaration, make a note of that.
2435     if (Redecl.isKeyDecl())
2436       Reader.KeyDecls[ExistingCanon].push_back(Redecl.getFirstID());
2437   }
2438 }
2439 
2440 /// \brief Attempts to merge the given declaration (D) with another declaration
2441 /// of the same entity, for the case where the entity is not actually
2442 /// redeclarable. This happens, for instance, when merging the fields of
2443 /// identical class definitions from two different modules.
2444 template<typename T>
2445 void ASTDeclReader::mergeMergeable(Mergeable<T> *D) {
2446   // If modules are not available, there is no reason to perform this merge.
2447   if (!Reader.getContext().getLangOpts().Modules)
2448     return;
2449 
2450   // ODR-based merging is only performed in C++. In C, identically-named things
2451   // in different translation units are not redeclarations (but may still have
2452   // compatible types).
2453   if (!Reader.getContext().getLangOpts().CPlusPlus)
2454     return;
2455 
2456   if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D)))
2457     if (T *Existing = ExistingRes)
2458       Reader.Context.setPrimaryMergedDecl(static_cast<T*>(D),
2459                                           Existing->getCanonicalDecl());
2460 }
2461 
2462 void ASTDeclReader::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
2463   VisitDecl(D);
2464   unsigned NumVars = D->varlist_size();
2465   SmallVector<Expr *, 16> Vars;
2466   Vars.reserve(NumVars);
2467   for (unsigned i = 0; i != NumVars; ++i) {
2468     Vars.push_back(Record.readExpr());
2469   }
2470   D->setVars(Vars);
2471 }
2472 
2473 void ASTDeclReader::VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D) {
2474   VisitValueDecl(D);
2475   D->setLocation(ReadSourceLocation());
2476   D->setCombiner(Record.readExpr());
2477   D->setInitializer(Record.readExpr());
2478   D->PrevDeclInScope = ReadDeclID();
2479 }
2480 
2481 void ASTDeclReader::VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D) {
2482   VisitVarDecl(D);
2483 }
2484 
2485 //===----------------------------------------------------------------------===//
2486 // Attribute Reading
2487 //===----------------------------------------------------------------------===//
2488 
2489 /// \brief Reads attributes from the current stream position.
2490 void ASTReader::ReadAttributes(ASTRecordReader &Record, AttrVec &Attrs) {
2491   for (unsigned i = 0, e = Record.readInt(); i != e; ++i) {
2492     Attr *New = nullptr;
2493     attr::Kind Kind = (attr::Kind)Record.readInt();
2494     SourceRange Range = Record.readSourceRange();
2495 
2496 #include "clang/Serialization/AttrPCHRead.inc"
2497 
2498     assert(New && "Unable to decode attribute?");
2499     Attrs.push_back(New);
2500   }
2501 }
2502 
2503 //===----------------------------------------------------------------------===//
2504 // ASTReader Implementation
2505 //===----------------------------------------------------------------------===//
2506 
2507 /// \brief Note that we have loaded the declaration with the given
2508 /// Index.
2509 ///
2510 /// This routine notes that this declaration has already been loaded,
2511 /// so that future GetDecl calls will return this declaration rather
2512 /// than trying to load a new declaration.
2513 inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
2514   assert(!DeclsLoaded[Index] && "Decl loaded twice?");
2515   DeclsLoaded[Index] = D;
2516 }
2517 
2518 
2519 /// \brief Determine whether the consumer will be interested in seeing
2520 /// this declaration (via HandleTopLevelDecl).
2521 ///
2522 /// This routine should return true for anything that might affect
2523 /// code generation, e.g., inline function definitions, Objective-C
2524 /// declarations with metadata, etc.
2525 static bool isConsumerInterestedIn(ASTContext &Ctx, Decl *D, bool HasBody) {
2526   // An ObjCMethodDecl is never considered as "interesting" because its
2527   // implementation container always is.
2528 
2529   // An ImportDecl or VarDecl imported from a module will get emitted when
2530   // we import the relevant module.
2531   if ((isa<ImportDecl>(D) || isa<VarDecl>(D)) && Ctx.DeclMustBeEmitted(D) &&
2532       D->getImportedOwningModule())
2533     return false;
2534 
2535   if (isa<FileScopeAsmDecl>(D) ||
2536       isa<ObjCProtocolDecl>(D) ||
2537       isa<ObjCImplDecl>(D) ||
2538       isa<ImportDecl>(D) ||
2539       isa<PragmaCommentDecl>(D) ||
2540       isa<PragmaDetectMismatchDecl>(D))
2541     return true;
2542   if (isa<OMPThreadPrivateDecl>(D) || isa<OMPDeclareReductionDecl>(D))
2543     return !D->getDeclContext()->isFunctionOrMethod();
2544   if (VarDecl *Var = dyn_cast<VarDecl>(D))
2545     return Var->isFileVarDecl() &&
2546            Var->isThisDeclarationADefinition() == VarDecl::Definition;
2547   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
2548     return Func->doesThisDeclarationHaveABody() || HasBody;
2549 
2550   return false;
2551 }
2552 
2553 /// \brief Get the correct cursor and offset for loading a declaration.
2554 ASTReader::RecordLocation
2555 ASTReader::DeclCursorForID(DeclID ID, SourceLocation &Loc) {
2556   GlobalDeclMapType::iterator I = GlobalDeclMap.find(ID);
2557   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
2558   ModuleFile *M = I->second;
2559   const DeclOffset &DOffs =
2560       M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS];
2561   Loc = TranslateSourceLocation(*M, DOffs.getLocation());
2562   return RecordLocation(M, DOffs.BitOffset);
2563 }
2564 
2565 ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
2566   ContinuousRangeMap<uint64_t, ModuleFile*, 4>::iterator I
2567     = GlobalBitOffsetsMap.find(GlobalOffset);
2568 
2569   assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map");
2570   return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
2571 }
2572 
2573 uint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset) {
2574   return LocalOffset + M.GlobalBitOffset;
2575 }
2576 
2577 static bool isSameTemplateParameterList(const TemplateParameterList *X,
2578                                         const TemplateParameterList *Y);
2579 
2580 /// \brief Determine whether two template parameters are similar enough
2581 /// that they may be used in declarations of the same template.
2582 static bool isSameTemplateParameter(const NamedDecl *X,
2583                                     const NamedDecl *Y) {
2584   if (X->getKind() != Y->getKind())
2585     return false;
2586 
2587   if (const TemplateTypeParmDecl *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
2588     const TemplateTypeParmDecl *TY = cast<TemplateTypeParmDecl>(Y);
2589     return TX->isParameterPack() == TY->isParameterPack();
2590   }
2591 
2592   if (const NonTypeTemplateParmDecl *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
2593     const NonTypeTemplateParmDecl *TY = cast<NonTypeTemplateParmDecl>(Y);
2594     return TX->isParameterPack() == TY->isParameterPack() &&
2595            TX->getASTContext().hasSameType(TX->getType(), TY->getType());
2596   }
2597 
2598   const TemplateTemplateParmDecl *TX = cast<TemplateTemplateParmDecl>(X);
2599   const TemplateTemplateParmDecl *TY = cast<TemplateTemplateParmDecl>(Y);
2600   return TX->isParameterPack() == TY->isParameterPack() &&
2601          isSameTemplateParameterList(TX->getTemplateParameters(),
2602                                      TY->getTemplateParameters());
2603 }
2604 
2605 static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) {
2606   if (auto *NS = X->getAsNamespace())
2607     return NS;
2608   if (auto *NAS = X->getAsNamespaceAlias())
2609     return NAS->getNamespace();
2610   return nullptr;
2611 }
2612 
2613 static bool isSameQualifier(const NestedNameSpecifier *X,
2614                             const NestedNameSpecifier *Y) {
2615   if (auto *NSX = getNamespace(X)) {
2616     auto *NSY = getNamespace(Y);
2617     if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
2618       return false;
2619   } else if (X->getKind() != Y->getKind())
2620     return false;
2621 
2622   // FIXME: For namespaces and types, we're permitted to check that the entity
2623   // is named via the same tokens. We should probably do so.
2624   switch (X->getKind()) {
2625   case NestedNameSpecifier::Identifier:
2626     if (X->getAsIdentifier() != Y->getAsIdentifier())
2627       return false;
2628     break;
2629   case NestedNameSpecifier::Namespace:
2630   case NestedNameSpecifier::NamespaceAlias:
2631     // We've already checked that we named the same namespace.
2632     break;
2633   case NestedNameSpecifier::TypeSpec:
2634   case NestedNameSpecifier::TypeSpecWithTemplate:
2635     if (X->getAsType()->getCanonicalTypeInternal() !=
2636         Y->getAsType()->getCanonicalTypeInternal())
2637       return false;
2638     break;
2639   case NestedNameSpecifier::Global:
2640   case NestedNameSpecifier::Super:
2641     return true;
2642   }
2643 
2644   // Recurse into earlier portion of NNS, if any.
2645   auto *PX = X->getPrefix();
2646   auto *PY = Y->getPrefix();
2647   if (PX && PY)
2648     return isSameQualifier(PX, PY);
2649   return !PX && !PY;
2650 }
2651 
2652 /// \brief Determine whether two template parameter lists are similar enough
2653 /// that they may be used in declarations of the same template.
2654 static bool isSameTemplateParameterList(const TemplateParameterList *X,
2655                                         const TemplateParameterList *Y) {
2656   if (X->size() != Y->size())
2657     return false;
2658 
2659   for (unsigned I = 0, N = X->size(); I != N; ++I)
2660     if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
2661       return false;
2662 
2663   return true;
2664 }
2665 
2666 /// Determine whether the attributes we can overload on are identical for A and
2667 /// B. Will ignore any overloadable attrs represented in the type of A and B.
2668 static bool hasSameOverloadableAttrs(const FunctionDecl *A,
2669                                      const FunctionDecl *B) {
2670   // Note that pass_object_size attributes are represented in the function's
2671   // ExtParameterInfo, so we don't need to check them here.
2672 
2673   SmallVector<const EnableIfAttr *, 4> AEnableIfs;
2674   // Since this is an equality check, we can ignore that enable_if attrs show up
2675   // in reverse order.
2676   for (const auto *EIA : A->specific_attrs<EnableIfAttr>())
2677     AEnableIfs.push_back(EIA);
2678 
2679   SmallVector<const EnableIfAttr *, 4> BEnableIfs;
2680   for (const auto *EIA : B->specific_attrs<EnableIfAttr>())
2681     BEnableIfs.push_back(EIA);
2682 
2683   // Two very common cases: either we have 0 enable_if attrs, or we have an
2684   // unequal number of enable_if attrs.
2685   if (AEnableIfs.empty() && BEnableIfs.empty())
2686     return true;
2687 
2688   if (AEnableIfs.size() != BEnableIfs.size())
2689     return false;
2690 
2691   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
2692   for (unsigned I = 0, E = AEnableIfs.size(); I != E; ++I) {
2693     Cand1ID.clear();
2694     Cand2ID.clear();
2695 
2696     AEnableIfs[I]->getCond()->Profile(Cand1ID, A->getASTContext(), true);
2697     BEnableIfs[I]->getCond()->Profile(Cand2ID, B->getASTContext(), true);
2698     if (Cand1ID != Cand2ID)
2699       return false;
2700   }
2701 
2702   return true;
2703 }
2704 
2705 /// \brief Determine whether the two declarations refer to the same entity.
2706 static bool isSameEntity(NamedDecl *X, NamedDecl *Y) {
2707   assert(X->getDeclName() == Y->getDeclName() && "Declaration name mismatch!");
2708 
2709   if (X == Y)
2710     return true;
2711 
2712   // Must be in the same context.
2713   if (!X->getDeclContext()->getRedeclContext()->Equals(
2714          Y->getDeclContext()->getRedeclContext()))
2715     return false;
2716 
2717   // Two typedefs refer to the same entity if they have the same underlying
2718   // type.
2719   if (TypedefNameDecl *TypedefX = dyn_cast<TypedefNameDecl>(X))
2720     if (TypedefNameDecl *TypedefY = dyn_cast<TypedefNameDecl>(Y))
2721       return X->getASTContext().hasSameType(TypedefX->getUnderlyingType(),
2722                                             TypedefY->getUnderlyingType());
2723 
2724   // Must have the same kind.
2725   if (X->getKind() != Y->getKind())
2726     return false;
2727 
2728   // Objective-C classes and protocols with the same name always match.
2729   if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
2730     return true;
2731 
2732   if (isa<ClassTemplateSpecializationDecl>(X)) {
2733     // No need to handle these here: we merge them when adding them to the
2734     // template.
2735     return false;
2736   }
2737 
2738   // Compatible tags match.
2739   if (TagDecl *TagX = dyn_cast<TagDecl>(X)) {
2740     TagDecl *TagY = cast<TagDecl>(Y);
2741     return (TagX->getTagKind() == TagY->getTagKind()) ||
2742       ((TagX->getTagKind() == TTK_Struct || TagX->getTagKind() == TTK_Class ||
2743         TagX->getTagKind() == TTK_Interface) &&
2744        (TagY->getTagKind() == TTK_Struct || TagY->getTagKind() == TTK_Class ||
2745         TagY->getTagKind() == TTK_Interface));
2746   }
2747 
2748   // Functions with the same type and linkage match.
2749   // FIXME: This needs to cope with merging of prototyped/non-prototyped
2750   // functions, etc.
2751   if (FunctionDecl *FuncX = dyn_cast<FunctionDecl>(X)) {
2752     FunctionDecl *FuncY = cast<FunctionDecl>(Y);
2753     if (CXXConstructorDecl *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
2754       CXXConstructorDecl *CtorY = cast<CXXConstructorDecl>(Y);
2755       if (CtorX->getInheritedConstructor() &&
2756           !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
2757                         CtorY->getInheritedConstructor().getConstructor()))
2758         return false;
2759     }
2760     return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
2761            FuncX->getASTContext().hasSameType(FuncX->getType(),
2762                                               FuncY->getType()) &&
2763            hasSameOverloadableAttrs(FuncX, FuncY);
2764   }
2765 
2766   // Variables with the same type and linkage match.
2767   if (VarDecl *VarX = dyn_cast<VarDecl>(X)) {
2768     VarDecl *VarY = cast<VarDecl>(Y);
2769     if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
2770       ASTContext &C = VarX->getASTContext();
2771       if (C.hasSameType(VarX->getType(), VarY->getType()))
2772         return true;
2773 
2774       // We can get decls with different types on the redecl chain. Eg.
2775       // template <typename T> struct S { static T Var[]; }; // #1
2776       // template <typename T> T S<T>::Var[sizeof(T)]; // #2
2777       // Only? happens when completing an incomplete array type. In this case
2778       // when comparing #1 and #2 we should go through their element type.
2779       const ArrayType *VarXTy = C.getAsArrayType(VarX->getType());
2780       const ArrayType *VarYTy = C.getAsArrayType(VarY->getType());
2781       if (!VarXTy || !VarYTy)
2782         return false;
2783       if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
2784         return C.hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
2785     }
2786     return false;
2787   }
2788 
2789   // Namespaces with the same name and inlinedness match.
2790   if (NamespaceDecl *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
2791     NamespaceDecl *NamespaceY = cast<NamespaceDecl>(Y);
2792     return NamespaceX->isInline() == NamespaceY->isInline();
2793   }
2794 
2795   // Identical template names and kinds match if their template parameter lists
2796   // and patterns match.
2797   if (TemplateDecl *TemplateX = dyn_cast<TemplateDecl>(X)) {
2798     TemplateDecl *TemplateY = cast<TemplateDecl>(Y);
2799     return isSameEntity(TemplateX->getTemplatedDecl(),
2800                         TemplateY->getTemplatedDecl()) &&
2801            isSameTemplateParameterList(TemplateX->getTemplateParameters(),
2802                                        TemplateY->getTemplateParameters());
2803   }
2804 
2805   // Fields with the same name and the same type match.
2806   if (FieldDecl *FDX = dyn_cast<FieldDecl>(X)) {
2807     FieldDecl *FDY = cast<FieldDecl>(Y);
2808     // FIXME: Also check the bitwidth is odr-equivalent, if any.
2809     return X->getASTContext().hasSameType(FDX->getType(), FDY->getType());
2810   }
2811 
2812   // Indirect fields with the same target field match.
2813   if (auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
2814     auto *IFDY = cast<IndirectFieldDecl>(Y);
2815     return IFDX->getAnonField()->getCanonicalDecl() ==
2816            IFDY->getAnonField()->getCanonicalDecl();
2817   }
2818 
2819   // Enumerators with the same name match.
2820   if (isa<EnumConstantDecl>(X))
2821     // FIXME: Also check the value is odr-equivalent.
2822     return true;
2823 
2824   // Using shadow declarations with the same target match.
2825   if (UsingShadowDecl *USX = dyn_cast<UsingShadowDecl>(X)) {
2826     UsingShadowDecl *USY = cast<UsingShadowDecl>(Y);
2827     return USX->getTargetDecl() == USY->getTargetDecl();
2828   }
2829 
2830   // Using declarations with the same qualifier match. (We already know that
2831   // the name matches.)
2832   if (auto *UX = dyn_cast<UsingDecl>(X)) {
2833     auto *UY = cast<UsingDecl>(Y);
2834     return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
2835            UX->hasTypename() == UY->hasTypename() &&
2836            UX->isAccessDeclaration() == UY->isAccessDeclaration();
2837   }
2838   if (auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
2839     auto *UY = cast<UnresolvedUsingValueDecl>(Y);
2840     return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
2841            UX->isAccessDeclaration() == UY->isAccessDeclaration();
2842   }
2843   if (auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X))
2844     return isSameQualifier(
2845         UX->getQualifier(),
2846         cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
2847 
2848   // Namespace alias definitions with the same target match.
2849   if (auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
2850     auto *NAY = cast<NamespaceAliasDecl>(Y);
2851     return NAX->getNamespace()->Equals(NAY->getNamespace());
2852   }
2853 
2854   return false;
2855 }
2856 
2857 /// Find the context in which we should search for previous declarations when
2858 /// looking for declarations to merge.
2859 DeclContext *ASTDeclReader::getPrimaryContextForMerging(ASTReader &Reader,
2860                                                         DeclContext *DC) {
2861   if (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
2862     return ND->getOriginalNamespace();
2863 
2864   if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
2865     // Try to dig out the definition.
2866     auto *DD = RD->DefinitionData;
2867     if (!DD)
2868       DD = RD->getCanonicalDecl()->DefinitionData;
2869 
2870     // If there's no definition yet, then DC's definition is added by an update
2871     // record, but we've not yet loaded that update record. In this case, we
2872     // commit to DC being the canonical definition now, and will fix this when
2873     // we load the update record.
2874     if (!DD) {
2875       DD = new (Reader.Context) struct CXXRecordDecl::DefinitionData(RD);
2876       RD->IsCompleteDefinition = true;
2877       RD->DefinitionData = DD;
2878       RD->getCanonicalDecl()->DefinitionData = DD;
2879 
2880       // Track that we did this horrible thing so that we can fix it later.
2881       Reader.PendingFakeDefinitionData.insert(
2882           std::make_pair(DD, ASTReader::PendingFakeDefinitionKind::Fake));
2883     }
2884 
2885     return DD->Definition;
2886   }
2887 
2888   if (EnumDecl *ED = dyn_cast<EnumDecl>(DC))
2889     return ED->getASTContext().getLangOpts().CPlusPlus? ED->getDefinition()
2890                                                       : nullptr;
2891 
2892   // We can see the TU here only if we have no Sema object. In that case,
2893   // there's no TU scope to look in, so using the DC alone is sufficient.
2894   if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
2895     return TU;
2896 
2897   return nullptr;
2898 }
2899 
2900 ASTDeclReader::FindExistingResult::~FindExistingResult() {
2901   // Record that we had a typedef name for linkage whether or not we merge
2902   // with that declaration.
2903   if (TypedefNameForLinkage) {
2904     DeclContext *DC = New->getDeclContext()->getRedeclContext();
2905     Reader.ImportedTypedefNamesForLinkage.insert(
2906         std::make_pair(std::make_pair(DC, TypedefNameForLinkage), New));
2907     return;
2908   }
2909 
2910   if (!AddResult || Existing)
2911     return;
2912 
2913   DeclarationName Name = New->getDeclName();
2914   DeclContext *DC = New->getDeclContext()->getRedeclContext();
2915   if (needsAnonymousDeclarationNumber(New)) {
2916     setAnonymousDeclForMerging(Reader, New->getLexicalDeclContext(),
2917                                AnonymousDeclNumber, New);
2918   } else if (DC->isTranslationUnit() &&
2919              !Reader.getContext().getLangOpts().CPlusPlus) {
2920     if (Reader.getIdResolver().tryAddTopLevelDecl(New, Name))
2921       Reader.PendingFakeLookupResults[Name.getAsIdentifierInfo()]
2922             .push_back(New);
2923   } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
2924     // Add the declaration to its redeclaration context so later merging
2925     // lookups will find it.
2926     MergeDC->makeDeclVisibleInContextImpl(New, /*Internal*/true);
2927   }
2928 }
2929 
2930 /// Find the declaration that should be merged into, given the declaration found
2931 /// by name lookup. If we're merging an anonymous declaration within a typedef,
2932 /// we need a matching typedef, and we merge with the type inside it.
2933 static NamedDecl *getDeclForMerging(NamedDecl *Found,
2934                                     bool IsTypedefNameForLinkage) {
2935   if (!IsTypedefNameForLinkage)
2936     return Found;
2937 
2938   // If we found a typedef declaration that gives a name to some other
2939   // declaration, then we want that inner declaration. Declarations from
2940   // AST files are handled via ImportedTypedefNamesForLinkage.
2941   if (Found->isFromASTFile())
2942     return nullptr;
2943 
2944   if (auto *TND = dyn_cast<TypedefNameDecl>(Found))
2945     return TND->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2946 
2947   return nullptr;
2948 }
2949 
2950 NamedDecl *ASTDeclReader::getAnonymousDeclForMerging(ASTReader &Reader,
2951                                                      DeclContext *DC,
2952                                                      unsigned Index) {
2953   // If the lexical context has been merged, look into the now-canonical
2954   // definition.
2955   if (auto *Merged = Reader.MergedDeclContexts.lookup(DC))
2956     DC = Merged;
2957 
2958   // If we've seen this before, return the canonical declaration.
2959   auto &Previous = Reader.AnonymousDeclarationsForMerging[DC];
2960   if (Index < Previous.size() && Previous[Index])
2961     return Previous[Index];
2962 
2963   // If this is the first time, but we have parsed a declaration of the context,
2964   // build the anonymous declaration list from the parsed declaration.
2965   if (!cast<Decl>(DC)->isFromASTFile()) {
2966     numberAnonymousDeclsWithin(DC, [&](NamedDecl *ND, unsigned Number) {
2967       if (Previous.size() == Number)
2968         Previous.push_back(cast<NamedDecl>(ND->getCanonicalDecl()));
2969       else
2970         Previous[Number] = cast<NamedDecl>(ND->getCanonicalDecl());
2971     });
2972   }
2973 
2974   return Index < Previous.size() ? Previous[Index] : nullptr;
2975 }
2976 
2977 void ASTDeclReader::setAnonymousDeclForMerging(ASTReader &Reader,
2978                                                DeclContext *DC, unsigned Index,
2979                                                NamedDecl *D) {
2980   if (auto *Merged = Reader.MergedDeclContexts.lookup(DC))
2981     DC = Merged;
2982 
2983   auto &Previous = Reader.AnonymousDeclarationsForMerging[DC];
2984   if (Index >= Previous.size())
2985     Previous.resize(Index + 1);
2986   if (!Previous[Index])
2987     Previous[Index] = D;
2988 }
2989 
2990 ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) {
2991   DeclarationName Name = TypedefNameForLinkage ? TypedefNameForLinkage
2992                                                : D->getDeclName();
2993 
2994   if (!Name && !needsAnonymousDeclarationNumber(D)) {
2995     // Don't bother trying to find unnamed declarations that are in
2996     // unmergeable contexts.
2997     FindExistingResult Result(Reader, D, /*Existing=*/nullptr,
2998                               AnonymousDeclNumber, TypedefNameForLinkage);
2999     Result.suppress();
3000     return Result;
3001   }
3002 
3003   DeclContext *DC = D->getDeclContext()->getRedeclContext();
3004   if (TypedefNameForLinkage) {
3005     auto It = Reader.ImportedTypedefNamesForLinkage.find(
3006         std::make_pair(DC, TypedefNameForLinkage));
3007     if (It != Reader.ImportedTypedefNamesForLinkage.end())
3008       if (isSameEntity(It->second, D))
3009         return FindExistingResult(Reader, D, It->second, AnonymousDeclNumber,
3010                                   TypedefNameForLinkage);
3011     // Go on to check in other places in case an existing typedef name
3012     // was not imported.
3013   }
3014 
3015   if (needsAnonymousDeclarationNumber(D)) {
3016     // This is an anonymous declaration that we may need to merge. Look it up
3017     // in its context by number.
3018     if (auto *Existing = getAnonymousDeclForMerging(
3019             Reader, D->getLexicalDeclContext(), AnonymousDeclNumber))
3020       if (isSameEntity(Existing, D))
3021         return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3022                                   TypedefNameForLinkage);
3023   } else if (DC->isTranslationUnit() &&
3024              !Reader.getContext().getLangOpts().CPlusPlus) {
3025     IdentifierResolver &IdResolver = Reader.getIdResolver();
3026 
3027     // Temporarily consider the identifier to be up-to-date. We don't want to
3028     // cause additional lookups here.
3029     class UpToDateIdentifierRAII {
3030       IdentifierInfo *II;
3031       bool WasOutToDate;
3032 
3033     public:
3034       explicit UpToDateIdentifierRAII(IdentifierInfo *II)
3035         : II(II), WasOutToDate(false)
3036       {
3037         if (II) {
3038           WasOutToDate = II->isOutOfDate();
3039           if (WasOutToDate)
3040             II->setOutOfDate(false);
3041         }
3042       }
3043 
3044       ~UpToDateIdentifierRAII() {
3045         if (WasOutToDate)
3046           II->setOutOfDate(true);
3047       }
3048     } UpToDate(Name.getAsIdentifierInfo());
3049 
3050     for (IdentifierResolver::iterator I = IdResolver.begin(Name),
3051                                    IEnd = IdResolver.end();
3052          I != IEnd; ++I) {
3053       if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
3054         if (isSameEntity(Existing, D))
3055           return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3056                                     TypedefNameForLinkage);
3057     }
3058   } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
3059     DeclContext::lookup_result R = MergeDC->noload_lookup(Name);
3060     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
3061       if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
3062         if (isSameEntity(Existing, D))
3063           return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3064                                     TypedefNameForLinkage);
3065     }
3066   } else {
3067     // Not in a mergeable context.
3068     return FindExistingResult(Reader);
3069   }
3070 
3071   // If this declaration is from a merged context, make a note that we need to
3072   // check that the canonical definition of that context contains the decl.
3073   //
3074   // FIXME: We should do something similar if we merge two definitions of the
3075   // same template specialization into the same CXXRecordDecl.
3076   auto MergedDCIt = Reader.MergedDeclContexts.find(D->getLexicalDeclContext());
3077   if (MergedDCIt != Reader.MergedDeclContexts.end() &&
3078       MergedDCIt->second == D->getDeclContext())
3079     Reader.PendingOdrMergeChecks.push_back(D);
3080 
3081   return FindExistingResult(Reader, D, /*Existing=*/nullptr,
3082                             AnonymousDeclNumber, TypedefNameForLinkage);
3083 }
3084 
3085 template<typename DeclT>
3086 Decl *ASTDeclReader::getMostRecentDeclImpl(Redeclarable<DeclT> *D) {
3087   return D->RedeclLink.getLatestNotUpdated();
3088 }
3089 Decl *ASTDeclReader::getMostRecentDeclImpl(...) {
3090   llvm_unreachable("getMostRecentDecl on non-redeclarable declaration");
3091 }
3092 
3093 Decl *ASTDeclReader::getMostRecentDecl(Decl *D) {
3094   assert(D);
3095 
3096   switch (D->getKind()) {
3097 #define ABSTRACT_DECL(TYPE)
3098 #define DECL(TYPE, BASE)                               \
3099   case Decl::TYPE:                                     \
3100     return getMostRecentDeclImpl(cast<TYPE##Decl>(D));
3101 #include "clang/AST/DeclNodes.inc"
3102   }
3103   llvm_unreachable("unknown decl kind");
3104 }
3105 
3106 Decl *ASTReader::getMostRecentExistingDecl(Decl *D) {
3107   return ASTDeclReader::getMostRecentDecl(D->getCanonicalDecl());
3108 }
3109 
3110 template<typename DeclT>
3111 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3112                                            Redeclarable<DeclT> *D,
3113                                            Decl *Previous, Decl *Canon) {
3114   D->RedeclLink.setPrevious(cast<DeclT>(Previous));
3115   D->First = cast<DeclT>(Previous)->First;
3116 }
3117 
3118 namespace clang {
3119 template<>
3120 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3121                                            Redeclarable<VarDecl> *D,
3122                                            Decl *Previous, Decl *Canon) {
3123   VarDecl *VD = static_cast<VarDecl*>(D);
3124   VarDecl *PrevVD = cast<VarDecl>(Previous);
3125   D->RedeclLink.setPrevious(PrevVD);
3126   D->First = PrevVD->First;
3127 
3128   // We should keep at most one definition on the chain.
3129   // FIXME: Cache the definition once we've found it. Building a chain with
3130   // N definitions currently takes O(N^2) time here.
3131   if (VD->isThisDeclarationADefinition() == VarDecl::Definition) {
3132     for (VarDecl *CurD = PrevVD; CurD; CurD = CurD->getPreviousDecl()) {
3133       if (CurD->isThisDeclarationADefinition() == VarDecl::Definition) {
3134         Reader.mergeDefinitionVisibility(CurD, VD);
3135         VD->demoteThisDefinitionToDeclaration();
3136         break;
3137       }
3138     }
3139   }
3140 }
3141 
3142 template<>
3143 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3144                                            Redeclarable<FunctionDecl> *D,
3145                                            Decl *Previous, Decl *Canon) {
3146   FunctionDecl *FD = static_cast<FunctionDecl*>(D);
3147   FunctionDecl *PrevFD = cast<FunctionDecl>(Previous);
3148 
3149   FD->RedeclLink.setPrevious(PrevFD);
3150   FD->First = PrevFD->First;
3151 
3152   // If the previous declaration is an inline function declaration, then this
3153   // declaration is too.
3154   if (PrevFD->IsInline != FD->IsInline) {
3155     // FIXME: [dcl.fct.spec]p4:
3156     //   If a function with external linkage is declared inline in one
3157     //   translation unit, it shall be declared inline in all translation
3158     //   units in which it appears.
3159     //
3160     // Be careful of this case:
3161     //
3162     // module A:
3163     //   template<typename T> struct X { void f(); };
3164     //   template<typename T> inline void X<T>::f() {}
3165     //
3166     // module B instantiates the declaration of X<int>::f
3167     // module C instantiates the definition of X<int>::f
3168     //
3169     // If module B and C are merged, we do not have a violation of this rule.
3170     FD->IsInline = true;
3171   }
3172 
3173   // If we need to propagate an exception specification along the redecl
3174   // chain, make a note of that so that we can do so later.
3175   auto *FPT = FD->getType()->getAs<FunctionProtoType>();
3176   auto *PrevFPT = PrevFD->getType()->getAs<FunctionProtoType>();
3177   if (FPT && PrevFPT) {
3178     bool IsUnresolved = isUnresolvedExceptionSpec(FPT->getExceptionSpecType());
3179     bool WasUnresolved =
3180         isUnresolvedExceptionSpec(PrevFPT->getExceptionSpecType());
3181     if (IsUnresolved != WasUnresolved)
3182       Reader.PendingExceptionSpecUpdates.insert(
3183           std::make_pair(Canon, IsUnresolved ? PrevFD : FD));
3184   }
3185 }
3186 } // end namespace clang
3187 
3188 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader, ...) {
3189   llvm_unreachable("attachPreviousDecl on non-redeclarable declaration");
3190 }
3191 
3192 /// Inherit the default template argument from \p From to \p To. Returns
3193 /// \c false if there is no default template for \p From.
3194 template <typename ParmDecl>
3195 static bool inheritDefaultTemplateArgument(ASTContext &Context, ParmDecl *From,
3196                                            Decl *ToD) {
3197   auto *To = cast<ParmDecl>(ToD);
3198   if (!From->hasDefaultArgument())
3199     return false;
3200   To->setInheritedDefaultArgument(Context, From);
3201   return true;
3202 }
3203 
3204 static void inheritDefaultTemplateArguments(ASTContext &Context,
3205                                             TemplateDecl *From,
3206                                             TemplateDecl *To) {
3207   auto *FromTP = From->getTemplateParameters();
3208   auto *ToTP = To->getTemplateParameters();
3209   assert(FromTP->size() == ToTP->size() && "merged mismatched templates?");
3210 
3211   for (unsigned I = 0, N = FromTP->size(); I != N; ++I) {
3212     NamedDecl *FromParam = FromTP->getParam(N - I - 1);
3213     if (FromParam->isParameterPack())
3214       continue;
3215     NamedDecl *ToParam = ToTP->getParam(N - I - 1);
3216 
3217     if (auto *FTTP = dyn_cast<TemplateTypeParmDecl>(FromParam)) {
3218       if (!inheritDefaultTemplateArgument(Context, FTTP, ToParam))
3219         break;
3220     } else if (auto *FNTTP = dyn_cast<NonTypeTemplateParmDecl>(FromParam)) {
3221       if (!inheritDefaultTemplateArgument(Context, FNTTP, ToParam))
3222         break;
3223     } else {
3224       if (!inheritDefaultTemplateArgument(
3225               Context, cast<TemplateTemplateParmDecl>(FromParam), ToParam))
3226         break;
3227     }
3228   }
3229 }
3230 
3231 void ASTDeclReader::attachPreviousDecl(ASTReader &Reader, Decl *D,
3232                                        Decl *Previous, Decl *Canon) {
3233   assert(D && Previous);
3234 
3235   switch (D->getKind()) {
3236 #define ABSTRACT_DECL(TYPE)
3237 #define DECL(TYPE, BASE)                                                  \
3238   case Decl::TYPE:                                                        \
3239     attachPreviousDeclImpl(Reader, cast<TYPE##Decl>(D), Previous, Canon); \
3240     break;
3241 #include "clang/AST/DeclNodes.inc"
3242   }
3243 
3244   // If the declaration was visible in one module, a redeclaration of it in
3245   // another module remains visible even if it wouldn't be visible by itself.
3246   //
3247   // FIXME: In this case, the declaration should only be visible if a module
3248   //        that makes it visible has been imported.
3249   D->IdentifierNamespace |=
3250       Previous->IdentifierNamespace &
3251       (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
3252 
3253   // If the declaration declares a template, it may inherit default arguments
3254   // from the previous declaration.
3255   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
3256     inheritDefaultTemplateArguments(Reader.getContext(),
3257                                     cast<TemplateDecl>(Previous), TD);
3258 }
3259 
3260 template<typename DeclT>
3261 void ASTDeclReader::attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest) {
3262   D->RedeclLink.setLatest(cast<DeclT>(Latest));
3263 }
3264 void ASTDeclReader::attachLatestDeclImpl(...) {
3265   llvm_unreachable("attachLatestDecl on non-redeclarable declaration");
3266 }
3267 
3268 void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {
3269   assert(D && Latest);
3270 
3271   switch (D->getKind()) {
3272 #define ABSTRACT_DECL(TYPE)
3273 #define DECL(TYPE, BASE)                                  \
3274   case Decl::TYPE:                                        \
3275     attachLatestDeclImpl(cast<TYPE##Decl>(D), Latest); \
3276     break;
3277 #include "clang/AST/DeclNodes.inc"
3278   }
3279 }
3280 
3281 template<typename DeclT>
3282 void ASTDeclReader::markIncompleteDeclChainImpl(Redeclarable<DeclT> *D) {
3283   D->RedeclLink.markIncomplete();
3284 }
3285 void ASTDeclReader::markIncompleteDeclChainImpl(...) {
3286   llvm_unreachable("markIncompleteDeclChain on non-redeclarable declaration");
3287 }
3288 
3289 void ASTReader::markIncompleteDeclChain(Decl *D) {
3290   switch (D->getKind()) {
3291 #define ABSTRACT_DECL(TYPE)
3292 #define DECL(TYPE, BASE)                                             \
3293   case Decl::TYPE:                                                   \
3294     ASTDeclReader::markIncompleteDeclChainImpl(cast<TYPE##Decl>(D)); \
3295     break;
3296 #include "clang/AST/DeclNodes.inc"
3297   }
3298 }
3299 
3300 /// \brief Read the declaration at the given offset from the AST file.
3301 Decl *ASTReader::ReadDeclRecord(DeclID ID) {
3302   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
3303   SourceLocation DeclLoc;
3304   RecordLocation Loc = DeclCursorForID(ID, DeclLoc);
3305   llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
3306   // Keep track of where we are in the stream, then jump back there
3307   // after reading this declaration.
3308   SavedStreamPosition SavedPosition(DeclsCursor);
3309 
3310   ReadingKindTracker ReadingKind(Read_Decl, *this);
3311 
3312   // Note that we are loading a declaration record.
3313   Deserializing ADecl(this);
3314 
3315   DeclsCursor.JumpToBit(Loc.Offset);
3316   ASTRecordReader Record(*this, *Loc.F);
3317   ASTDeclReader Reader(*this, Record, Loc, ID, DeclLoc);
3318   unsigned Code = DeclsCursor.ReadCode();
3319 
3320   Decl *D = nullptr;
3321   switch ((DeclCode)Record.readRecord(DeclsCursor, Code)) {
3322   case DECL_CONTEXT_LEXICAL:
3323   case DECL_CONTEXT_VISIBLE:
3324     llvm_unreachable("Record cannot be de-serialized with ReadDeclRecord");
3325   case DECL_TYPEDEF:
3326     D = TypedefDecl::CreateDeserialized(Context, ID);
3327     break;
3328   case DECL_TYPEALIAS:
3329     D = TypeAliasDecl::CreateDeserialized(Context, ID);
3330     break;
3331   case DECL_ENUM:
3332     D = EnumDecl::CreateDeserialized(Context, ID);
3333     break;
3334   case DECL_RECORD:
3335     D = RecordDecl::CreateDeserialized(Context, ID);
3336     break;
3337   case DECL_ENUM_CONSTANT:
3338     D = EnumConstantDecl::CreateDeserialized(Context, ID);
3339     break;
3340   case DECL_FUNCTION:
3341     D = FunctionDecl::CreateDeserialized(Context, ID);
3342     break;
3343   case DECL_LINKAGE_SPEC:
3344     D = LinkageSpecDecl::CreateDeserialized(Context, ID);
3345     break;
3346   case DECL_EXPORT:
3347     D = ExportDecl::CreateDeserialized(Context, ID);
3348     break;
3349   case DECL_LABEL:
3350     D = LabelDecl::CreateDeserialized(Context, ID);
3351     break;
3352   case DECL_NAMESPACE:
3353     D = NamespaceDecl::CreateDeserialized(Context, ID);
3354     break;
3355   case DECL_NAMESPACE_ALIAS:
3356     D = NamespaceAliasDecl::CreateDeserialized(Context, ID);
3357     break;
3358   case DECL_USING:
3359     D = UsingDecl::CreateDeserialized(Context, ID);
3360     break;
3361   case DECL_USING_PACK:
3362     D = UsingPackDecl::CreateDeserialized(Context, ID, Record.readInt());
3363     break;
3364   case DECL_USING_SHADOW:
3365     D = UsingShadowDecl::CreateDeserialized(Context, ID);
3366     break;
3367   case DECL_CONSTRUCTOR_USING_SHADOW:
3368     D = ConstructorUsingShadowDecl::CreateDeserialized(Context, ID);
3369     break;
3370   case DECL_USING_DIRECTIVE:
3371     D = UsingDirectiveDecl::CreateDeserialized(Context, ID);
3372     break;
3373   case DECL_UNRESOLVED_USING_VALUE:
3374     D = UnresolvedUsingValueDecl::CreateDeserialized(Context, ID);
3375     break;
3376   case DECL_UNRESOLVED_USING_TYPENAME:
3377     D = UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID);
3378     break;
3379   case DECL_CXX_RECORD:
3380     D = CXXRecordDecl::CreateDeserialized(Context, ID);
3381     break;
3382   case DECL_CXX_DEDUCTION_GUIDE:
3383     D = CXXDeductionGuideDecl::CreateDeserialized(Context, ID);
3384     break;
3385   case DECL_CXX_METHOD:
3386     D = CXXMethodDecl::CreateDeserialized(Context, ID);
3387     break;
3388   case DECL_CXX_CONSTRUCTOR:
3389     D = CXXConstructorDecl::CreateDeserialized(Context, ID, false);
3390     break;
3391   case DECL_CXX_INHERITED_CONSTRUCTOR:
3392     D = CXXConstructorDecl::CreateDeserialized(Context, ID, true);
3393     break;
3394   case DECL_CXX_DESTRUCTOR:
3395     D = CXXDestructorDecl::CreateDeserialized(Context, ID);
3396     break;
3397   case DECL_CXX_CONVERSION:
3398     D = CXXConversionDecl::CreateDeserialized(Context, ID);
3399     break;
3400   case DECL_ACCESS_SPEC:
3401     D = AccessSpecDecl::CreateDeserialized(Context, ID);
3402     break;
3403   case DECL_FRIEND:
3404     D = FriendDecl::CreateDeserialized(Context, ID, Record.readInt());
3405     break;
3406   case DECL_FRIEND_TEMPLATE:
3407     D = FriendTemplateDecl::CreateDeserialized(Context, ID);
3408     break;
3409   case DECL_CLASS_TEMPLATE:
3410     D = ClassTemplateDecl::CreateDeserialized(Context, ID);
3411     break;
3412   case DECL_CLASS_TEMPLATE_SPECIALIZATION:
3413     D = ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3414     break;
3415   case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
3416     D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3417     break;
3418   case DECL_VAR_TEMPLATE:
3419     D = VarTemplateDecl::CreateDeserialized(Context, ID);
3420     break;
3421   case DECL_VAR_TEMPLATE_SPECIALIZATION:
3422     D = VarTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3423     break;
3424   case DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION:
3425     D = VarTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3426     break;
3427   case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
3428     D = ClassScopeFunctionSpecializationDecl::CreateDeserialized(Context, ID);
3429     break;
3430   case DECL_FUNCTION_TEMPLATE:
3431     D = FunctionTemplateDecl::CreateDeserialized(Context, ID);
3432     break;
3433   case DECL_TEMPLATE_TYPE_PARM:
3434     D = TemplateTypeParmDecl::CreateDeserialized(Context, ID);
3435     break;
3436   case DECL_NON_TYPE_TEMPLATE_PARM:
3437     D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID);
3438     break;
3439   case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK:
3440     D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID,
3441                                                     Record.readInt());
3442     break;
3443   case DECL_TEMPLATE_TEMPLATE_PARM:
3444     D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID);
3445     break;
3446   case DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK:
3447     D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID,
3448                                                      Record.readInt());
3449     break;
3450   case DECL_TYPE_ALIAS_TEMPLATE:
3451     D = TypeAliasTemplateDecl::CreateDeserialized(Context, ID);
3452     break;
3453   case DECL_STATIC_ASSERT:
3454     D = StaticAssertDecl::CreateDeserialized(Context, ID);
3455     break;
3456   case DECL_OBJC_METHOD:
3457     D = ObjCMethodDecl::CreateDeserialized(Context, ID);
3458     break;
3459   case DECL_OBJC_INTERFACE:
3460     D = ObjCInterfaceDecl::CreateDeserialized(Context, ID);
3461     break;
3462   case DECL_OBJC_IVAR:
3463     D = ObjCIvarDecl::CreateDeserialized(Context, ID);
3464     break;
3465   case DECL_OBJC_PROTOCOL:
3466     D = ObjCProtocolDecl::CreateDeserialized(Context, ID);
3467     break;
3468   case DECL_OBJC_AT_DEFS_FIELD:
3469     D = ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID);
3470     break;
3471   case DECL_OBJC_CATEGORY:
3472     D = ObjCCategoryDecl::CreateDeserialized(Context, ID);
3473     break;
3474   case DECL_OBJC_CATEGORY_IMPL:
3475     D = ObjCCategoryImplDecl::CreateDeserialized(Context, ID);
3476     break;
3477   case DECL_OBJC_IMPLEMENTATION:
3478     D = ObjCImplementationDecl::CreateDeserialized(Context, ID);
3479     break;
3480   case DECL_OBJC_COMPATIBLE_ALIAS:
3481     D = ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID);
3482     break;
3483   case DECL_OBJC_PROPERTY:
3484     D = ObjCPropertyDecl::CreateDeserialized(Context, ID);
3485     break;
3486   case DECL_OBJC_PROPERTY_IMPL:
3487     D = ObjCPropertyImplDecl::CreateDeserialized(Context, ID);
3488     break;
3489   case DECL_FIELD:
3490     D = FieldDecl::CreateDeserialized(Context, ID);
3491     break;
3492   case DECL_INDIRECTFIELD:
3493     D = IndirectFieldDecl::CreateDeserialized(Context, ID);
3494     break;
3495   case DECL_VAR:
3496     D = VarDecl::CreateDeserialized(Context, ID);
3497     break;
3498   case DECL_IMPLICIT_PARAM:
3499     D = ImplicitParamDecl::CreateDeserialized(Context, ID);
3500     break;
3501   case DECL_PARM_VAR:
3502     D = ParmVarDecl::CreateDeserialized(Context, ID);
3503     break;
3504   case DECL_DECOMPOSITION:
3505     D = DecompositionDecl::CreateDeserialized(Context, ID, Record.readInt());
3506     break;
3507   case DECL_BINDING:
3508     D = BindingDecl::CreateDeserialized(Context, ID);
3509     break;
3510   case DECL_FILE_SCOPE_ASM:
3511     D = FileScopeAsmDecl::CreateDeserialized(Context, ID);
3512     break;
3513   case DECL_BLOCK:
3514     D = BlockDecl::CreateDeserialized(Context, ID);
3515     break;
3516   case DECL_MS_PROPERTY:
3517     D = MSPropertyDecl::CreateDeserialized(Context, ID);
3518     break;
3519   case DECL_CAPTURED:
3520     D = CapturedDecl::CreateDeserialized(Context, ID, Record.readInt());
3521     break;
3522   case DECL_CXX_BASE_SPECIFIERS:
3523     Error("attempt to read a C++ base-specifier record as a declaration");
3524     return nullptr;
3525   case DECL_CXX_CTOR_INITIALIZERS:
3526     Error("attempt to read a C++ ctor initializer record as a declaration");
3527     return nullptr;
3528   case DECL_IMPORT:
3529     // Note: last entry of the ImportDecl record is the number of stored source
3530     // locations.
3531     D = ImportDecl::CreateDeserialized(Context, ID, Record.back());
3532     break;
3533   case DECL_OMP_THREADPRIVATE:
3534     D = OMPThreadPrivateDecl::CreateDeserialized(Context, ID, Record.readInt());
3535     break;
3536   case DECL_OMP_DECLARE_REDUCTION:
3537     D = OMPDeclareReductionDecl::CreateDeserialized(Context, ID);
3538     break;
3539   case DECL_OMP_CAPTUREDEXPR:
3540     D = OMPCapturedExprDecl::CreateDeserialized(Context, ID);
3541     break;
3542   case DECL_PRAGMA_COMMENT:
3543     D = PragmaCommentDecl::CreateDeserialized(Context, ID, Record.readInt());
3544     break;
3545   case DECL_PRAGMA_DETECT_MISMATCH:
3546     D = PragmaDetectMismatchDecl::CreateDeserialized(Context, ID,
3547                                                      Record.readInt());
3548     break;
3549   case DECL_EMPTY:
3550     D = EmptyDecl::CreateDeserialized(Context, ID);
3551     break;
3552   case DECL_OBJC_TYPE_PARAM:
3553     D = ObjCTypeParamDecl::CreateDeserialized(Context, ID);
3554     break;
3555   }
3556 
3557   assert(D && "Unknown declaration reading AST file");
3558   LoadedDecl(Index, D);
3559   // Set the DeclContext before doing any deserialization, to make sure internal
3560   // calls to Decl::getASTContext() by Decl's methods will find the
3561   // TranslationUnitDecl without crashing.
3562   D->setDeclContext(Context.getTranslationUnitDecl());
3563   Reader.Visit(D);
3564 
3565   // If this declaration is also a declaration context, get the
3566   // offsets for its tables of lexical and visible declarations.
3567   if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
3568     std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
3569     if (Offsets.first &&
3570         ReadLexicalDeclContextStorage(*Loc.F, DeclsCursor, Offsets.first, DC))
3571       return nullptr;
3572     if (Offsets.second &&
3573         ReadVisibleDeclContextStorage(*Loc.F, DeclsCursor, Offsets.second, ID))
3574       return nullptr;
3575   }
3576   assert(Record.getIdx() == Record.size());
3577 
3578   // Load any relevant update records.
3579   PendingUpdateRecords.push_back(std::make_pair(ID, D));
3580 
3581   // Load the categories after recursive loading is finished.
3582   if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3583     // If we already have a definition when deserializing the ObjCInterfaceDecl,
3584     // we put the Decl in PendingDefinitions so we can pull the categories here.
3585     if (Class->isThisDeclarationADefinition() ||
3586         PendingDefinitions.count(Class))
3587       loadObjCCategories(ID, Class);
3588 
3589   // If we have deserialized a declaration that has a definition the
3590   // AST consumer might need to know about, queue it.
3591   // We don't pass it to the consumer immediately because we may be in recursive
3592   // loading, and some declarations may still be initializing.
3593   if (isConsumerInterestedIn(Context, D, Reader.hasPendingBody()))
3594     InterestingDecls.push_back(D);
3595 
3596   return D;
3597 }
3598 
3599 void ASTReader::loadDeclUpdateRecords(serialization::DeclID ID, Decl *D) {
3600   // The declaration may have been modified by files later in the chain.
3601   // If this is the case, read the record containing the updates from each file
3602   // and pass it to ASTDeclReader to make the modifications.
3603   ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
3604   DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
3605   if (UpdI != DeclUpdateOffsets.end()) {
3606     auto UpdateOffsets = std::move(UpdI->second);
3607     DeclUpdateOffsets.erase(UpdI);
3608 
3609     bool WasInteresting = isConsumerInterestedIn(Context, D, false);
3610     for (auto &FileAndOffset : UpdateOffsets) {
3611       ModuleFile *F = FileAndOffset.first;
3612       uint64_t Offset = FileAndOffset.second;
3613       llvm::BitstreamCursor &Cursor = F->DeclsCursor;
3614       SavedStreamPosition SavedPosition(Cursor);
3615       Cursor.JumpToBit(Offset);
3616       unsigned Code = Cursor.ReadCode();
3617       ASTRecordReader Record(*this, *F);
3618       unsigned RecCode = Record.readRecord(Cursor, Code);
3619       (void)RecCode;
3620       assert(RecCode == DECL_UPDATES && "Expected DECL_UPDATES record!");
3621 
3622       ASTDeclReader Reader(*this, Record, RecordLocation(F, Offset), ID,
3623                            SourceLocation());
3624       Reader.UpdateDecl(D);
3625 
3626       // We might have made this declaration interesting. If so, remember that
3627       // we need to hand it off to the consumer.
3628       if (!WasInteresting &&
3629           isConsumerInterestedIn(Context, D, Reader.hasPendingBody())) {
3630         InterestingDecls.push_back(D);
3631         WasInteresting = true;
3632       }
3633     }
3634   }
3635 
3636   // Load the pending visible updates for this decl context, if it has any.
3637   auto I = PendingVisibleUpdates.find(ID);
3638   if (I != PendingVisibleUpdates.end()) {
3639     auto VisibleUpdates = std::move(I->second);
3640     PendingVisibleUpdates.erase(I);
3641 
3642     auto *DC = cast<DeclContext>(D)->getPrimaryContext();
3643     for (const PendingVisibleUpdate &Update : VisibleUpdates)
3644       Lookups[DC].Table.add(
3645           Update.Mod, Update.Data,
3646           reader::ASTDeclContextNameLookupTrait(*this, *Update.Mod));
3647     DC->setHasExternalVisibleStorage(true);
3648   }
3649 }
3650 
3651 void ASTReader::loadPendingDeclChain(Decl *FirstLocal, uint64_t LocalOffset) {
3652   // Attach FirstLocal to the end of the decl chain.
3653   Decl *CanonDecl = FirstLocal->getCanonicalDecl();
3654   if (FirstLocal != CanonDecl) {
3655     Decl *PrevMostRecent = ASTDeclReader::getMostRecentDecl(CanonDecl);
3656     ASTDeclReader::attachPreviousDecl(
3657         *this, FirstLocal, PrevMostRecent ? PrevMostRecent : CanonDecl,
3658         CanonDecl);
3659   }
3660 
3661   if (!LocalOffset) {
3662     ASTDeclReader::attachLatestDecl(CanonDecl, FirstLocal);
3663     return;
3664   }
3665 
3666   // Load the list of other redeclarations from this module file.
3667   ModuleFile *M = getOwningModuleFile(FirstLocal);
3668   assert(M && "imported decl from no module file");
3669 
3670   llvm::BitstreamCursor &Cursor = M->DeclsCursor;
3671   SavedStreamPosition SavedPosition(Cursor);
3672   Cursor.JumpToBit(LocalOffset);
3673 
3674   RecordData Record;
3675   unsigned Code = Cursor.ReadCode();
3676   unsigned RecCode = Cursor.readRecord(Code, Record);
3677   (void)RecCode;
3678   assert(RecCode == LOCAL_REDECLARATIONS && "expected LOCAL_REDECLARATIONS record!");
3679 
3680   // FIXME: We have several different dispatches on decl kind here; maybe
3681   // we should instead generate one loop per kind and dispatch up-front?
3682   Decl *MostRecent = FirstLocal;
3683   for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3684     auto *D = GetLocalDecl(*M, Record[N - I - 1]);
3685     ASTDeclReader::attachPreviousDecl(*this, D, MostRecent, CanonDecl);
3686     MostRecent = D;
3687   }
3688   ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent);
3689 }
3690 
3691 namespace {
3692   /// \brief Given an ObjC interface, goes through the modules and links to the
3693   /// interface all the categories for it.
3694   class ObjCCategoriesVisitor {
3695     ASTReader &Reader;
3696     ObjCInterfaceDecl *Interface;
3697     llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized;
3698     ObjCCategoryDecl *Tail;
3699     llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
3700     serialization::GlobalDeclID InterfaceID;
3701     unsigned PreviousGeneration;
3702 
3703     void add(ObjCCategoryDecl *Cat) {
3704       // Only process each category once.
3705       if (!Deserialized.erase(Cat))
3706         return;
3707 
3708       // Check for duplicate categories.
3709       if (Cat->getDeclName()) {
3710         ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
3711         if (Existing &&
3712             Reader.getOwningModuleFile(Existing)
3713                                           != Reader.getOwningModuleFile(Cat)) {
3714           // FIXME: We should not warn for duplicates in diamond:
3715           //
3716           //   MT     //
3717           //  /  \    //
3718           // ML  MR   //
3719           //  \  /    //
3720           //   MB     //
3721           //
3722           // If there are duplicates in ML/MR, there will be warning when
3723           // creating MB *and* when importing MB. We should not warn when
3724           // importing.
3725           Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
3726             << Interface->getDeclName() << Cat->getDeclName();
3727           Reader.Diag(Existing->getLocation(), diag::note_previous_definition);
3728         } else if (!Existing) {
3729           // Record this category.
3730           Existing = Cat;
3731         }
3732       }
3733 
3734       // Add this category to the end of the chain.
3735       if (Tail)
3736         ASTDeclReader::setNextObjCCategory(Tail, Cat);
3737       else
3738         Interface->setCategoryListRaw(Cat);
3739       Tail = Cat;
3740     }
3741 
3742   public:
3743     ObjCCategoriesVisitor(ASTReader &Reader,
3744                           ObjCInterfaceDecl *Interface,
3745                           llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized,
3746                           serialization::GlobalDeclID InterfaceID,
3747                           unsigned PreviousGeneration)
3748       : Reader(Reader), Interface(Interface), Deserialized(Deserialized),
3749         Tail(nullptr), InterfaceID(InterfaceID),
3750         PreviousGeneration(PreviousGeneration)
3751     {
3752       // Populate the name -> category map with the set of known categories.
3753       for (auto *Cat : Interface->known_categories()) {
3754         if (Cat->getDeclName())
3755           NameCategoryMap[Cat->getDeclName()] = Cat;
3756 
3757         // Keep track of the tail of the category list.
3758         Tail = Cat;
3759       }
3760     }
3761 
3762     bool operator()(ModuleFile &M) {
3763       // If we've loaded all of the category information we care about from
3764       // this module file, we're done.
3765       if (M.Generation <= PreviousGeneration)
3766         return true;
3767 
3768       // Map global ID of the definition down to the local ID used in this
3769       // module file. If there is no such mapping, we'll find nothing here
3770       // (or in any module it imports).
3771       DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID);
3772       if (!LocalID)
3773         return true;
3774 
3775       // Perform a binary search to find the local redeclarations for this
3776       // declaration (if any).
3777       const ObjCCategoriesInfo Compare = { LocalID, 0 };
3778       const ObjCCategoriesInfo *Result
3779         = std::lower_bound(M.ObjCCategoriesMap,
3780                            M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap,
3781                            Compare);
3782       if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap ||
3783           Result->DefinitionID != LocalID) {
3784         // We didn't find anything. If the class definition is in this module
3785         // file, then the module files it depends on cannot have any categories,
3786         // so suppress further lookup.
3787         return Reader.isDeclIDFromModule(InterfaceID, M);
3788       }
3789 
3790       // We found something. Dig out all of the categories.
3791       unsigned Offset = Result->Offset;
3792       unsigned N = M.ObjCCategories[Offset];
3793       M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again
3794       for (unsigned I = 0; I != N; ++I)
3795         add(cast_or_null<ObjCCategoryDecl>(
3796               Reader.GetLocalDecl(M, M.ObjCCategories[Offset++])));
3797       return true;
3798     }
3799   };
3800 } // end anonymous namespace
3801 
3802 void ASTReader::loadObjCCategories(serialization::GlobalDeclID ID,
3803                                    ObjCInterfaceDecl *D,
3804                                    unsigned PreviousGeneration) {
3805   ObjCCategoriesVisitor Visitor(*this, D, CategoriesDeserialized, ID,
3806                                 PreviousGeneration);
3807   ModuleMgr.visit(Visitor);
3808 }
3809 
3810 template<typename DeclT, typename Fn>
3811 static void forAllLaterRedecls(DeclT *D, Fn F) {
3812   F(D);
3813 
3814   // Check whether we've already merged D into its redeclaration chain.
3815   // MostRecent may or may not be nullptr if D has not been merged. If
3816   // not, walk the merged redecl chain and see if it's there.
3817   auto *MostRecent = D->getMostRecentDecl();
3818   bool Found = false;
3819   for (auto *Redecl = MostRecent; Redecl && !Found;
3820        Redecl = Redecl->getPreviousDecl())
3821     Found = (Redecl == D);
3822 
3823   // If this declaration is merged, apply the functor to all later decls.
3824   if (Found) {
3825     for (auto *Redecl = MostRecent; Redecl != D;
3826          Redecl = Redecl->getPreviousDecl())
3827       F(Redecl);
3828   }
3829 }
3830 
3831 void ASTDeclReader::UpdateDecl(Decl *D) {
3832   while (Record.getIdx() < Record.size()) {
3833     switch ((DeclUpdateKind)Record.readInt()) {
3834     case UPD_CXX_ADDED_IMPLICIT_MEMBER: {
3835       auto *RD = cast<CXXRecordDecl>(D);
3836       // FIXME: If we also have an update record for instantiating the
3837       // definition of D, we need that to happen before we get here.
3838       Decl *MD = Record.readDecl();
3839       assert(MD && "couldn't read decl from update record");
3840       // FIXME: We should call addHiddenDecl instead, to add the member
3841       // to its DeclContext.
3842       RD->addedMember(MD);
3843       break;
3844     }
3845 
3846     case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
3847       // It will be added to the template's specializations set when loaded.
3848       (void)Record.readDecl();
3849       break;
3850 
3851     case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
3852       NamespaceDecl *Anon = ReadDeclAs<NamespaceDecl>();
3853 
3854       // Each module has its own anonymous namespace, which is disjoint from
3855       // any other module's anonymous namespaces, so don't attach the anonymous
3856       // namespace at all.
3857       if (!Record.isModule()) {
3858         if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(D))
3859           TU->setAnonymousNamespace(Anon);
3860         else
3861           cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon);
3862       }
3863       break;
3864     }
3865 
3866     case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER:
3867       cast<VarDecl>(D)->getMemberSpecializationInfo()->setPointOfInstantiation(
3868           ReadSourceLocation());
3869       break;
3870 
3871     case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT: {
3872       auto Param = cast<ParmVarDecl>(D);
3873 
3874       // We have to read the default argument regardless of whether we use it
3875       // so that hypothetical further update records aren't messed up.
3876       // TODO: Add a function to skip over the next expr record.
3877       auto DefaultArg = Record.readExpr();
3878 
3879       // Only apply the update if the parameter still has an uninstantiated
3880       // default argument.
3881       if (Param->hasUninstantiatedDefaultArg())
3882         Param->setDefaultArg(DefaultArg);
3883       break;
3884     }
3885 
3886     case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER: {
3887       auto FD = cast<FieldDecl>(D);
3888       auto DefaultInit = Record.readExpr();
3889 
3890       // Only apply the update if the field still has an uninstantiated
3891       // default member initializer.
3892       if (FD->hasInClassInitializer() && !FD->getInClassInitializer()) {
3893         if (DefaultInit)
3894           FD->setInClassInitializer(DefaultInit);
3895         else
3896           // Instantiation failed. We can get here if we serialized an AST for
3897           // an invalid program.
3898           FD->removeInClassInitializer();
3899       }
3900       break;
3901     }
3902 
3903     case UPD_CXX_ADDED_FUNCTION_DEFINITION: {
3904       FunctionDecl *FD = cast<FunctionDecl>(D);
3905       if (Reader.PendingBodies[FD]) {
3906         // FIXME: Maybe check for ODR violations.
3907         // It's safe to stop now because this update record is always last.
3908         return;
3909       }
3910 
3911       if (Record.readInt()) {
3912         // Maintain AST consistency: any later redeclarations of this function
3913         // are inline if this one is. (We might have merged another declaration
3914         // into this one.)
3915         forAllLaterRedecls(FD, [](FunctionDecl *FD) {
3916           FD->setImplicitlyInline();
3917         });
3918       }
3919       FD->setInnerLocStart(ReadSourceLocation());
3920       ReadFunctionDefinition(FD);
3921       assert(Record.getIdx() == Record.size() && "lazy body must be last");
3922       break;
3923     }
3924 
3925     case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
3926       auto *RD = cast<CXXRecordDecl>(D);
3927       auto *OldDD = RD->getCanonicalDecl()->DefinitionData;
3928       bool HadRealDefinition =
3929           OldDD && (OldDD->Definition != RD ||
3930                     !Reader.PendingFakeDefinitionData.count(OldDD));
3931       ReadCXXRecordDefinition(RD, /*Update*/true);
3932 
3933       // Visible update is handled separately.
3934       uint64_t LexicalOffset = ReadLocalOffset();
3935       if (!HadRealDefinition && LexicalOffset) {
3936         Record.readLexicalDeclContextStorage(LexicalOffset, RD);
3937         Reader.PendingFakeDefinitionData.erase(OldDD);
3938       }
3939 
3940       auto TSK = (TemplateSpecializationKind)Record.readInt();
3941       SourceLocation POI = ReadSourceLocation();
3942       if (MemberSpecializationInfo *MSInfo =
3943               RD->getMemberSpecializationInfo()) {
3944         MSInfo->setTemplateSpecializationKind(TSK);
3945         MSInfo->setPointOfInstantiation(POI);
3946       } else {
3947         ClassTemplateSpecializationDecl *Spec =
3948             cast<ClassTemplateSpecializationDecl>(RD);
3949         Spec->setTemplateSpecializationKind(TSK);
3950         Spec->setPointOfInstantiation(POI);
3951 
3952         if (Record.readInt()) {
3953           auto PartialSpec =
3954               ReadDeclAs<ClassTemplatePartialSpecializationDecl>();
3955           SmallVector<TemplateArgument, 8> TemplArgs;
3956           Record.readTemplateArgumentList(TemplArgs);
3957           auto *TemplArgList = TemplateArgumentList::CreateCopy(
3958               Reader.getContext(), TemplArgs);
3959 
3960           // FIXME: If we already have a partial specialization set,
3961           // check that it matches.
3962           if (!Spec->getSpecializedTemplateOrPartial()
3963                    .is<ClassTemplatePartialSpecializationDecl *>())
3964             Spec->setInstantiationOf(PartialSpec, TemplArgList);
3965         }
3966       }
3967 
3968       RD->setTagKind((TagTypeKind)Record.readInt());
3969       RD->setLocation(ReadSourceLocation());
3970       RD->setLocStart(ReadSourceLocation());
3971       RD->setBraceRange(ReadSourceRange());
3972 
3973       if (Record.readInt()) {
3974         AttrVec Attrs;
3975         Record.readAttributes(Attrs);
3976         // If the declaration already has attributes, we assume that some other
3977         // AST file already loaded them.
3978         if (!D->hasAttrs())
3979           D->setAttrsImpl(Attrs, Reader.getContext());
3980       }
3981       break;
3982     }
3983 
3984     case UPD_CXX_RESOLVED_DTOR_DELETE: {
3985       // Set the 'operator delete' directly to avoid emitting another update
3986       // record.
3987       auto *Del = ReadDeclAs<FunctionDecl>();
3988       auto *First = cast<CXXDestructorDecl>(D->getCanonicalDecl());
3989       // FIXME: Check consistency if we have an old and new operator delete.
3990       if (!First->OperatorDelete)
3991         First->OperatorDelete = Del;
3992       break;
3993     }
3994 
3995     case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {
3996       FunctionProtoType::ExceptionSpecInfo ESI;
3997       SmallVector<QualType, 8> ExceptionStorage;
3998       Record.readExceptionSpec(ExceptionStorage, ESI);
3999 
4000       // Update this declaration's exception specification, if needed.
4001       auto *FD = cast<FunctionDecl>(D);
4002       auto *FPT = FD->getType()->castAs<FunctionProtoType>();
4003       // FIXME: If the exception specification is already present, check that it
4004       // matches.
4005       if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
4006         FD->setType(Reader.Context.getFunctionType(
4007             FPT->getReturnType(), FPT->getParamTypes(),
4008             FPT->getExtProtoInfo().withExceptionSpec(ESI)));
4009 
4010         // When we get to the end of deserializing, see if there are other decls
4011         // that we need to propagate this exception specification onto.
4012         Reader.PendingExceptionSpecUpdates.insert(
4013             std::make_pair(FD->getCanonicalDecl(), FD));
4014       }
4015       break;
4016     }
4017 
4018     case UPD_CXX_DEDUCED_RETURN_TYPE: {
4019       // FIXME: Also do this when merging redecls.
4020       QualType DeducedResultType = Record.readType();
4021       for (auto *Redecl : merged_redecls(D)) {
4022         // FIXME: If the return type is already deduced, check that it matches.
4023         FunctionDecl *FD = cast<FunctionDecl>(Redecl);
4024         Reader.Context.adjustDeducedFunctionResultType(FD, DeducedResultType);
4025       }
4026       break;
4027     }
4028 
4029     case UPD_DECL_MARKED_USED: {
4030       // Maintain AST consistency: any later redeclarations are used too.
4031       D->markUsed(Reader.Context);
4032       break;
4033     }
4034 
4035     case UPD_MANGLING_NUMBER:
4036       Reader.Context.setManglingNumber(cast<NamedDecl>(D), Record.readInt());
4037       break;
4038 
4039     case UPD_STATIC_LOCAL_NUMBER:
4040       Reader.Context.setStaticLocalNumber(cast<VarDecl>(D), Record.readInt());
4041       break;
4042 
4043     case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
4044       D->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
4045           Reader.Context, ReadSourceRange()));
4046       break;
4047 
4048     case UPD_DECL_EXPORTED: {
4049       unsigned SubmoduleID = readSubmoduleID();
4050       auto *Exported = cast<NamedDecl>(D);
4051       if (auto *TD = dyn_cast<TagDecl>(Exported))
4052         Exported = TD->getDefinition();
4053       Module *Owner = SubmoduleID ? Reader.getSubmodule(SubmoduleID) : nullptr;
4054       if (Reader.getContext().getLangOpts().ModulesLocalVisibility) {
4055         Reader.getContext().mergeDefinitionIntoModule(cast<NamedDecl>(Exported),
4056                                                       Owner);
4057         Reader.PendingMergedDefinitionsToDeduplicate.insert(
4058             cast<NamedDecl>(Exported));
4059       } else if (Owner && Owner->NameVisibility != Module::AllVisible) {
4060         // If Owner is made visible at some later point, make this declaration
4061         // visible too.
4062         Reader.HiddenNamesMap[Owner].push_back(Exported);
4063       } else {
4064         // The declaration is now visible.
4065         Exported->Hidden = false;
4066       }
4067       break;
4068     }
4069 
4070     case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
4071     case UPD_ADDED_ATTR_TO_RECORD:
4072       AttrVec Attrs;
4073       Record.readAttributes(Attrs);
4074       assert(Attrs.size() == 1);
4075       D->addAttr(Attrs[0]);
4076       break;
4077     }
4078   }
4079 }
4080