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