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