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
1591       = (Capture*)Reader.Context.Allocate(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.Context.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.Context.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 
2534 #include "clang/Serialization/AttrPCHRead.inc"
2535 
2536     assert(New && "Unable to decode attribute?");
2537     Attrs.push_back(New);
2538   }
2539 }
2540 
2541 //===----------------------------------------------------------------------===//
2542 // ASTReader Implementation
2543 //===----------------------------------------------------------------------===//
2544 
2545 /// \brief Note that we have loaded the declaration with the given
2546 /// Index.
2547 ///
2548 /// This routine notes that this declaration has already been loaded,
2549 /// so that future GetDecl calls will return this declaration rather
2550 /// than trying to load a new declaration.
2551 inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
2552   assert(!DeclsLoaded[Index] && "Decl loaded twice?");
2553   DeclsLoaded[Index] = D;
2554 }
2555 
2556 
2557 /// \brief Determine whether the consumer will be interested in seeing
2558 /// this declaration (via HandleTopLevelDecl).
2559 ///
2560 /// This routine should return true for anything that might affect
2561 /// code generation, e.g., inline function definitions, Objective-C
2562 /// declarations with metadata, etc.
2563 static bool isConsumerInterestedIn(ASTContext &Ctx, Decl *D, bool HasBody) {
2564   // An ObjCMethodDecl is never considered as "interesting" because its
2565   // implementation container always is.
2566 
2567   // An ImportDecl or VarDecl imported from a module will get emitted when
2568   // we import the relevant module.
2569   if ((isa<ImportDecl>(D) || isa<VarDecl>(D)) && D->getImportedOwningModule() &&
2570       Ctx.DeclMustBeEmitted(D))
2571     return false;
2572 
2573   if (isa<FileScopeAsmDecl>(D) ||
2574       isa<ObjCProtocolDecl>(D) ||
2575       isa<ObjCImplDecl>(D) ||
2576       isa<ImportDecl>(D) ||
2577       isa<PragmaCommentDecl>(D) ||
2578       isa<PragmaDetectMismatchDecl>(D))
2579     return true;
2580   if (isa<OMPThreadPrivateDecl>(D) || isa<OMPDeclareReductionDecl>(D))
2581     return !D->getDeclContext()->isFunctionOrMethod();
2582   if (VarDecl *Var = dyn_cast<VarDecl>(D))
2583     return Var->isFileVarDecl() &&
2584            Var->isThisDeclarationADefinition() == VarDecl::Definition;
2585   if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
2586     return Func->doesThisDeclarationHaveABody() || HasBody;
2587 
2588   if (auto *ES = D->getASTContext().getExternalSource())
2589     if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
2590       return true;
2591 
2592   return false;
2593 }
2594 
2595 /// \brief Get the correct cursor and offset for loading a declaration.
2596 ASTReader::RecordLocation
2597 ASTReader::DeclCursorForID(DeclID ID, SourceLocation &Loc) {
2598   GlobalDeclMapType::iterator I = GlobalDeclMap.find(ID);
2599   assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
2600   ModuleFile *M = I->second;
2601   const DeclOffset &DOffs =
2602       M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS];
2603   Loc = TranslateSourceLocation(*M, DOffs.getLocation());
2604   return RecordLocation(M, DOffs.BitOffset);
2605 }
2606 
2607 ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
2608   ContinuousRangeMap<uint64_t, ModuleFile*, 4>::iterator I
2609     = GlobalBitOffsetsMap.find(GlobalOffset);
2610 
2611   assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map");
2612   return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
2613 }
2614 
2615 uint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset) {
2616   return LocalOffset + M.GlobalBitOffset;
2617 }
2618 
2619 static bool isSameTemplateParameterList(const TemplateParameterList *X,
2620                                         const TemplateParameterList *Y);
2621 
2622 /// \brief Determine whether two template parameters are similar enough
2623 /// that they may be used in declarations of the same template.
2624 static bool isSameTemplateParameter(const NamedDecl *X,
2625                                     const NamedDecl *Y) {
2626   if (X->getKind() != Y->getKind())
2627     return false;
2628 
2629   if (const TemplateTypeParmDecl *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
2630     const TemplateTypeParmDecl *TY = cast<TemplateTypeParmDecl>(Y);
2631     return TX->isParameterPack() == TY->isParameterPack();
2632   }
2633 
2634   if (const NonTypeTemplateParmDecl *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
2635     const NonTypeTemplateParmDecl *TY = cast<NonTypeTemplateParmDecl>(Y);
2636     return TX->isParameterPack() == TY->isParameterPack() &&
2637            TX->getASTContext().hasSameType(TX->getType(), TY->getType());
2638   }
2639 
2640   const TemplateTemplateParmDecl *TX = cast<TemplateTemplateParmDecl>(X);
2641   const TemplateTemplateParmDecl *TY = cast<TemplateTemplateParmDecl>(Y);
2642   return TX->isParameterPack() == TY->isParameterPack() &&
2643          isSameTemplateParameterList(TX->getTemplateParameters(),
2644                                      TY->getTemplateParameters());
2645 }
2646 
2647 static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) {
2648   if (auto *NS = X->getAsNamespace())
2649     return NS;
2650   if (auto *NAS = X->getAsNamespaceAlias())
2651     return NAS->getNamespace();
2652   return nullptr;
2653 }
2654 
2655 static bool isSameQualifier(const NestedNameSpecifier *X,
2656                             const NestedNameSpecifier *Y) {
2657   if (auto *NSX = getNamespace(X)) {
2658     auto *NSY = getNamespace(Y);
2659     if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
2660       return false;
2661   } else if (X->getKind() != Y->getKind())
2662     return false;
2663 
2664   // FIXME: For namespaces and types, we're permitted to check that the entity
2665   // is named via the same tokens. We should probably do so.
2666   switch (X->getKind()) {
2667   case NestedNameSpecifier::Identifier:
2668     if (X->getAsIdentifier() != Y->getAsIdentifier())
2669       return false;
2670     break;
2671   case NestedNameSpecifier::Namespace:
2672   case NestedNameSpecifier::NamespaceAlias:
2673     // We've already checked that we named the same namespace.
2674     break;
2675   case NestedNameSpecifier::TypeSpec:
2676   case NestedNameSpecifier::TypeSpecWithTemplate:
2677     if (X->getAsType()->getCanonicalTypeInternal() !=
2678         Y->getAsType()->getCanonicalTypeInternal())
2679       return false;
2680     break;
2681   case NestedNameSpecifier::Global:
2682   case NestedNameSpecifier::Super:
2683     return true;
2684   }
2685 
2686   // Recurse into earlier portion of NNS, if any.
2687   auto *PX = X->getPrefix();
2688   auto *PY = Y->getPrefix();
2689   if (PX && PY)
2690     return isSameQualifier(PX, PY);
2691   return !PX && !PY;
2692 }
2693 
2694 /// \brief Determine whether two template parameter lists are similar enough
2695 /// that they may be used in declarations of the same template.
2696 static bool isSameTemplateParameterList(const TemplateParameterList *X,
2697                                         const TemplateParameterList *Y) {
2698   if (X->size() != Y->size())
2699     return false;
2700 
2701   for (unsigned I = 0, N = X->size(); I != N; ++I)
2702     if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
2703       return false;
2704 
2705   return true;
2706 }
2707 
2708 /// Determine whether the attributes we can overload on are identical for A and
2709 /// B. Will ignore any overloadable attrs represented in the type of A and B.
2710 static bool hasSameOverloadableAttrs(const FunctionDecl *A,
2711                                      const FunctionDecl *B) {
2712   // Note that pass_object_size attributes are represented in the function's
2713   // ExtParameterInfo, so we don't need to check them here.
2714 
2715   SmallVector<const EnableIfAttr *, 4> AEnableIfs;
2716   // Since this is an equality check, we can ignore that enable_if attrs show up
2717   // in reverse order.
2718   for (const auto *EIA : A->specific_attrs<EnableIfAttr>())
2719     AEnableIfs.push_back(EIA);
2720 
2721   SmallVector<const EnableIfAttr *, 4> BEnableIfs;
2722   for (const auto *EIA : B->specific_attrs<EnableIfAttr>())
2723     BEnableIfs.push_back(EIA);
2724 
2725   // Two very common cases: either we have 0 enable_if attrs, or we have an
2726   // unequal number of enable_if attrs.
2727   if (AEnableIfs.empty() && BEnableIfs.empty())
2728     return true;
2729 
2730   if (AEnableIfs.size() != BEnableIfs.size())
2731     return false;
2732 
2733   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
2734   for (unsigned I = 0, E = AEnableIfs.size(); I != E; ++I) {
2735     Cand1ID.clear();
2736     Cand2ID.clear();
2737 
2738     AEnableIfs[I]->getCond()->Profile(Cand1ID, A->getASTContext(), true);
2739     BEnableIfs[I]->getCond()->Profile(Cand2ID, B->getASTContext(), true);
2740     if (Cand1ID != Cand2ID)
2741       return false;
2742   }
2743 
2744   return true;
2745 }
2746 
2747 /// \brief Determine whether the two declarations refer to the same entity.
2748 static bool isSameEntity(NamedDecl *X, NamedDecl *Y) {
2749   assert(X->getDeclName() == Y->getDeclName() && "Declaration name mismatch!");
2750 
2751   if (X == Y)
2752     return true;
2753 
2754   // Must be in the same context.
2755   if (!X->getDeclContext()->getRedeclContext()->Equals(
2756          Y->getDeclContext()->getRedeclContext()))
2757     return false;
2758 
2759   // Two typedefs refer to the same entity if they have the same underlying
2760   // type.
2761   if (TypedefNameDecl *TypedefX = dyn_cast<TypedefNameDecl>(X))
2762     if (TypedefNameDecl *TypedefY = dyn_cast<TypedefNameDecl>(Y))
2763       return X->getASTContext().hasSameType(TypedefX->getUnderlyingType(),
2764                                             TypedefY->getUnderlyingType());
2765 
2766   // Must have the same kind.
2767   if (X->getKind() != Y->getKind())
2768     return false;
2769 
2770   // Objective-C classes and protocols with the same name always match.
2771   if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
2772     return true;
2773 
2774   if (isa<ClassTemplateSpecializationDecl>(X)) {
2775     // No need to handle these here: we merge them when adding them to the
2776     // template.
2777     return false;
2778   }
2779 
2780   // Compatible tags match.
2781   if (TagDecl *TagX = dyn_cast<TagDecl>(X)) {
2782     TagDecl *TagY = cast<TagDecl>(Y);
2783     return (TagX->getTagKind() == TagY->getTagKind()) ||
2784       ((TagX->getTagKind() == TTK_Struct || TagX->getTagKind() == TTK_Class ||
2785         TagX->getTagKind() == TTK_Interface) &&
2786        (TagY->getTagKind() == TTK_Struct || TagY->getTagKind() == TTK_Class ||
2787         TagY->getTagKind() == TTK_Interface));
2788   }
2789 
2790   // Functions with the same type and linkage match.
2791   // FIXME: This needs to cope with merging of prototyped/non-prototyped
2792   // functions, etc.
2793   if (FunctionDecl *FuncX = dyn_cast<FunctionDecl>(X)) {
2794     FunctionDecl *FuncY = cast<FunctionDecl>(Y);
2795     if (CXXConstructorDecl *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
2796       CXXConstructorDecl *CtorY = cast<CXXConstructorDecl>(Y);
2797       if (CtorX->getInheritedConstructor() &&
2798           !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
2799                         CtorY->getInheritedConstructor().getConstructor()))
2800         return false;
2801     }
2802     ASTContext &C = FuncX->getASTContext();
2803     if (!C.hasSameType(FuncX->getType(), FuncY->getType())) {
2804       // We can get functions with different types on the redecl chain in C++17
2805       // if they have differing exception specifications and at least one of
2806       // the excpetion specs is unresolved.
2807       // FIXME: Do we need to check for C++14 deduced return types here too?
2808       auto *XFPT = FuncX->getType()->getAs<FunctionProtoType>();
2809       auto *YFPT = FuncY->getType()->getAs<FunctionProtoType>();
2810       if (C.getLangOpts().CPlusPlus1z && XFPT && YFPT &&
2811           (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
2812            isUnresolvedExceptionSpec(YFPT->getExceptionSpecType())) &&
2813           C.hasSameFunctionTypeIgnoringExceptionSpec(FuncX->getType(),
2814                                                      FuncY->getType()))
2815         return true;
2816       return false;
2817     }
2818     return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
2819            hasSameOverloadableAttrs(FuncX, FuncY);
2820   }
2821 
2822   // Variables with the same type and linkage match.
2823   if (VarDecl *VarX = dyn_cast<VarDecl>(X)) {
2824     VarDecl *VarY = cast<VarDecl>(Y);
2825     if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
2826       ASTContext &C = VarX->getASTContext();
2827       if (C.hasSameType(VarX->getType(), VarY->getType()))
2828         return true;
2829 
2830       // We can get decls with different types on the redecl chain. Eg.
2831       // template <typename T> struct S { static T Var[]; }; // #1
2832       // template <typename T> T S<T>::Var[sizeof(T)]; // #2
2833       // Only? happens when completing an incomplete array type. In this case
2834       // when comparing #1 and #2 we should go through their element type.
2835       const ArrayType *VarXTy = C.getAsArrayType(VarX->getType());
2836       const ArrayType *VarYTy = C.getAsArrayType(VarY->getType());
2837       if (!VarXTy || !VarYTy)
2838         return false;
2839       if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
2840         return C.hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
2841     }
2842     return false;
2843   }
2844 
2845   // Namespaces with the same name and inlinedness match.
2846   if (NamespaceDecl *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
2847     NamespaceDecl *NamespaceY = cast<NamespaceDecl>(Y);
2848     return NamespaceX->isInline() == NamespaceY->isInline();
2849   }
2850 
2851   // Identical template names and kinds match if their template parameter lists
2852   // and patterns match.
2853   if (TemplateDecl *TemplateX = dyn_cast<TemplateDecl>(X)) {
2854     TemplateDecl *TemplateY = cast<TemplateDecl>(Y);
2855     return isSameEntity(TemplateX->getTemplatedDecl(),
2856                         TemplateY->getTemplatedDecl()) &&
2857            isSameTemplateParameterList(TemplateX->getTemplateParameters(),
2858                                        TemplateY->getTemplateParameters());
2859   }
2860 
2861   // Fields with the same name and the same type match.
2862   if (FieldDecl *FDX = dyn_cast<FieldDecl>(X)) {
2863     FieldDecl *FDY = cast<FieldDecl>(Y);
2864     // FIXME: Also check the bitwidth is odr-equivalent, if any.
2865     return X->getASTContext().hasSameType(FDX->getType(), FDY->getType());
2866   }
2867 
2868   // Indirect fields with the same target field match.
2869   if (auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
2870     auto *IFDY = cast<IndirectFieldDecl>(Y);
2871     return IFDX->getAnonField()->getCanonicalDecl() ==
2872            IFDY->getAnonField()->getCanonicalDecl();
2873   }
2874 
2875   // Enumerators with the same name match.
2876   if (isa<EnumConstantDecl>(X))
2877     // FIXME: Also check the value is odr-equivalent.
2878     return true;
2879 
2880   // Using shadow declarations with the same target match.
2881   if (UsingShadowDecl *USX = dyn_cast<UsingShadowDecl>(X)) {
2882     UsingShadowDecl *USY = cast<UsingShadowDecl>(Y);
2883     return USX->getTargetDecl() == USY->getTargetDecl();
2884   }
2885 
2886   // Using declarations with the same qualifier match. (We already know that
2887   // the name matches.)
2888   if (auto *UX = dyn_cast<UsingDecl>(X)) {
2889     auto *UY = cast<UsingDecl>(Y);
2890     return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
2891            UX->hasTypename() == UY->hasTypename() &&
2892            UX->isAccessDeclaration() == UY->isAccessDeclaration();
2893   }
2894   if (auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
2895     auto *UY = cast<UnresolvedUsingValueDecl>(Y);
2896     return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
2897            UX->isAccessDeclaration() == UY->isAccessDeclaration();
2898   }
2899   if (auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X))
2900     return isSameQualifier(
2901         UX->getQualifier(),
2902         cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
2903 
2904   // Namespace alias definitions with the same target match.
2905   if (auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
2906     auto *NAY = cast<NamespaceAliasDecl>(Y);
2907     return NAX->getNamespace()->Equals(NAY->getNamespace());
2908   }
2909 
2910   return false;
2911 }
2912 
2913 /// Find the context in which we should search for previous declarations when
2914 /// looking for declarations to merge.
2915 DeclContext *ASTDeclReader::getPrimaryContextForMerging(ASTReader &Reader,
2916                                                         DeclContext *DC) {
2917   if (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
2918     return ND->getOriginalNamespace();
2919 
2920   if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
2921     // Try to dig out the definition.
2922     auto *DD = RD->DefinitionData;
2923     if (!DD)
2924       DD = RD->getCanonicalDecl()->DefinitionData;
2925 
2926     // If there's no definition yet, then DC's definition is added by an update
2927     // record, but we've not yet loaded that update record. In this case, we
2928     // commit to DC being the canonical definition now, and will fix this when
2929     // we load the update record.
2930     if (!DD) {
2931       DD = new (Reader.Context) struct CXXRecordDecl::DefinitionData(RD);
2932       RD->IsCompleteDefinition = true;
2933       RD->DefinitionData = DD;
2934       RD->getCanonicalDecl()->DefinitionData = DD;
2935 
2936       // Track that we did this horrible thing so that we can fix it later.
2937       Reader.PendingFakeDefinitionData.insert(
2938           std::make_pair(DD, ASTReader::PendingFakeDefinitionKind::Fake));
2939     }
2940 
2941     return DD->Definition;
2942   }
2943 
2944   if (EnumDecl *ED = dyn_cast<EnumDecl>(DC))
2945     return ED->getASTContext().getLangOpts().CPlusPlus? ED->getDefinition()
2946                                                       : nullptr;
2947 
2948   // We can see the TU here only if we have no Sema object. In that case,
2949   // there's no TU scope to look in, so using the DC alone is sufficient.
2950   if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
2951     return TU;
2952 
2953   return nullptr;
2954 }
2955 
2956 ASTDeclReader::FindExistingResult::~FindExistingResult() {
2957   // Record that we had a typedef name for linkage whether or not we merge
2958   // with that declaration.
2959   if (TypedefNameForLinkage) {
2960     DeclContext *DC = New->getDeclContext()->getRedeclContext();
2961     Reader.ImportedTypedefNamesForLinkage.insert(
2962         std::make_pair(std::make_pair(DC, TypedefNameForLinkage), New));
2963     return;
2964   }
2965 
2966   if (!AddResult || Existing)
2967     return;
2968 
2969   DeclarationName Name = New->getDeclName();
2970   DeclContext *DC = New->getDeclContext()->getRedeclContext();
2971   if (needsAnonymousDeclarationNumber(New)) {
2972     setAnonymousDeclForMerging(Reader, New->getLexicalDeclContext(),
2973                                AnonymousDeclNumber, New);
2974   } else if (DC->isTranslationUnit() &&
2975              !Reader.getContext().getLangOpts().CPlusPlus) {
2976     if (Reader.getIdResolver().tryAddTopLevelDecl(New, Name))
2977       Reader.PendingFakeLookupResults[Name.getAsIdentifierInfo()]
2978             .push_back(New);
2979   } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
2980     // Add the declaration to its redeclaration context so later merging
2981     // lookups will find it.
2982     MergeDC->makeDeclVisibleInContextImpl(New, /*Internal*/true);
2983   }
2984 }
2985 
2986 /// Find the declaration that should be merged into, given the declaration found
2987 /// by name lookup. If we're merging an anonymous declaration within a typedef,
2988 /// we need a matching typedef, and we merge with the type inside it.
2989 static NamedDecl *getDeclForMerging(NamedDecl *Found,
2990                                     bool IsTypedefNameForLinkage) {
2991   if (!IsTypedefNameForLinkage)
2992     return Found;
2993 
2994   // If we found a typedef declaration that gives a name to some other
2995   // declaration, then we want that inner declaration. Declarations from
2996   // AST files are handled via ImportedTypedefNamesForLinkage.
2997   if (Found->isFromASTFile())
2998     return nullptr;
2999 
3000   if (auto *TND = dyn_cast<TypedefNameDecl>(Found))
3001     return TND->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
3002 
3003   return nullptr;
3004 }
3005 
3006 NamedDecl *ASTDeclReader::getAnonymousDeclForMerging(ASTReader &Reader,
3007                                                      DeclContext *DC,
3008                                                      unsigned Index) {
3009   // If the lexical context has been merged, look into the now-canonical
3010   // definition.
3011   if (auto *Merged = Reader.MergedDeclContexts.lookup(DC))
3012     DC = Merged;
3013 
3014   // If we've seen this before, return the canonical declaration.
3015   auto &Previous = Reader.AnonymousDeclarationsForMerging[DC];
3016   if (Index < Previous.size() && Previous[Index])
3017     return Previous[Index];
3018 
3019   // If this is the first time, but we have parsed a declaration of the context,
3020   // build the anonymous declaration list from the parsed declaration.
3021   if (!cast<Decl>(DC)->isFromASTFile()) {
3022     numberAnonymousDeclsWithin(DC, [&](NamedDecl *ND, unsigned Number) {
3023       if (Previous.size() == Number)
3024         Previous.push_back(cast<NamedDecl>(ND->getCanonicalDecl()));
3025       else
3026         Previous[Number] = cast<NamedDecl>(ND->getCanonicalDecl());
3027     });
3028   }
3029 
3030   return Index < Previous.size() ? Previous[Index] : nullptr;
3031 }
3032 
3033 void ASTDeclReader::setAnonymousDeclForMerging(ASTReader &Reader,
3034                                                DeclContext *DC, unsigned Index,
3035                                                NamedDecl *D) {
3036   if (auto *Merged = Reader.MergedDeclContexts.lookup(DC))
3037     DC = Merged;
3038 
3039   auto &Previous = Reader.AnonymousDeclarationsForMerging[DC];
3040   if (Index >= Previous.size())
3041     Previous.resize(Index + 1);
3042   if (!Previous[Index])
3043     Previous[Index] = D;
3044 }
3045 
3046 ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) {
3047   DeclarationName Name = TypedefNameForLinkage ? TypedefNameForLinkage
3048                                                : D->getDeclName();
3049 
3050   if (!Name && !needsAnonymousDeclarationNumber(D)) {
3051     // Don't bother trying to find unnamed declarations that are in
3052     // unmergeable contexts.
3053     FindExistingResult Result(Reader, D, /*Existing=*/nullptr,
3054                               AnonymousDeclNumber, TypedefNameForLinkage);
3055     Result.suppress();
3056     return Result;
3057   }
3058 
3059   DeclContext *DC = D->getDeclContext()->getRedeclContext();
3060   if (TypedefNameForLinkage) {
3061     auto It = Reader.ImportedTypedefNamesForLinkage.find(
3062         std::make_pair(DC, TypedefNameForLinkage));
3063     if (It != Reader.ImportedTypedefNamesForLinkage.end())
3064       if (isSameEntity(It->second, D))
3065         return FindExistingResult(Reader, D, It->second, AnonymousDeclNumber,
3066                                   TypedefNameForLinkage);
3067     // Go on to check in other places in case an existing typedef name
3068     // was not imported.
3069   }
3070 
3071   if (needsAnonymousDeclarationNumber(D)) {
3072     // This is an anonymous declaration that we may need to merge. Look it up
3073     // in its context by number.
3074     if (auto *Existing = getAnonymousDeclForMerging(
3075             Reader, D->getLexicalDeclContext(), AnonymousDeclNumber))
3076       if (isSameEntity(Existing, D))
3077         return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3078                                   TypedefNameForLinkage);
3079   } else if (DC->isTranslationUnit() &&
3080              !Reader.getContext().getLangOpts().CPlusPlus) {
3081     IdentifierResolver &IdResolver = Reader.getIdResolver();
3082 
3083     // Temporarily consider the identifier to be up-to-date. We don't want to
3084     // cause additional lookups here.
3085     class UpToDateIdentifierRAII {
3086       IdentifierInfo *II;
3087       bool WasOutToDate;
3088 
3089     public:
3090       explicit UpToDateIdentifierRAII(IdentifierInfo *II)
3091         : II(II), WasOutToDate(false)
3092       {
3093         if (II) {
3094           WasOutToDate = II->isOutOfDate();
3095           if (WasOutToDate)
3096             II->setOutOfDate(false);
3097         }
3098       }
3099 
3100       ~UpToDateIdentifierRAII() {
3101         if (WasOutToDate)
3102           II->setOutOfDate(true);
3103       }
3104     } UpToDate(Name.getAsIdentifierInfo());
3105 
3106     for (IdentifierResolver::iterator I = IdResolver.begin(Name),
3107                                    IEnd = IdResolver.end();
3108          I != IEnd; ++I) {
3109       if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
3110         if (isSameEntity(Existing, D))
3111           return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3112                                     TypedefNameForLinkage);
3113     }
3114   } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
3115     DeclContext::lookup_result R = MergeDC->noload_lookup(Name);
3116     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
3117       if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
3118         if (isSameEntity(Existing, D))
3119           return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3120                                     TypedefNameForLinkage);
3121     }
3122   } else {
3123     // Not in a mergeable context.
3124     return FindExistingResult(Reader);
3125   }
3126 
3127   // If this declaration is from a merged context, make a note that we need to
3128   // check that the canonical definition of that context contains the decl.
3129   //
3130   // FIXME: We should do something similar if we merge two definitions of the
3131   // same template specialization into the same CXXRecordDecl.
3132   auto MergedDCIt = Reader.MergedDeclContexts.find(D->getLexicalDeclContext());
3133   if (MergedDCIt != Reader.MergedDeclContexts.end() &&
3134       MergedDCIt->second == D->getDeclContext())
3135     Reader.PendingOdrMergeChecks.push_back(D);
3136 
3137   return FindExistingResult(Reader, D, /*Existing=*/nullptr,
3138                             AnonymousDeclNumber, TypedefNameForLinkage);
3139 }
3140 
3141 template<typename DeclT>
3142 Decl *ASTDeclReader::getMostRecentDeclImpl(Redeclarable<DeclT> *D) {
3143   return D->RedeclLink.getLatestNotUpdated();
3144 }
3145 Decl *ASTDeclReader::getMostRecentDeclImpl(...) {
3146   llvm_unreachable("getMostRecentDecl on non-redeclarable declaration");
3147 }
3148 
3149 Decl *ASTDeclReader::getMostRecentDecl(Decl *D) {
3150   assert(D);
3151 
3152   switch (D->getKind()) {
3153 #define ABSTRACT_DECL(TYPE)
3154 #define DECL(TYPE, BASE)                               \
3155   case Decl::TYPE:                                     \
3156     return getMostRecentDeclImpl(cast<TYPE##Decl>(D));
3157 #include "clang/AST/DeclNodes.inc"
3158   }
3159   llvm_unreachable("unknown decl kind");
3160 }
3161 
3162 Decl *ASTReader::getMostRecentExistingDecl(Decl *D) {
3163   return ASTDeclReader::getMostRecentDecl(D->getCanonicalDecl());
3164 }
3165 
3166 template<typename DeclT>
3167 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3168                                            Redeclarable<DeclT> *D,
3169                                            Decl *Previous, Decl *Canon) {
3170   D->RedeclLink.setPrevious(cast<DeclT>(Previous));
3171   D->First = cast<DeclT>(Previous)->First;
3172 }
3173 
3174 namespace clang {
3175 template<>
3176 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3177                                            Redeclarable<VarDecl> *D,
3178                                            Decl *Previous, Decl *Canon) {
3179   VarDecl *VD = static_cast<VarDecl*>(D);
3180   VarDecl *PrevVD = cast<VarDecl>(Previous);
3181   D->RedeclLink.setPrevious(PrevVD);
3182   D->First = PrevVD->First;
3183 
3184   // We should keep at most one definition on the chain.
3185   // FIXME: Cache the definition once we've found it. Building a chain with
3186   // N definitions currently takes O(N^2) time here.
3187   if (VD->isThisDeclarationADefinition() == VarDecl::Definition) {
3188     for (VarDecl *CurD = PrevVD; CurD; CurD = CurD->getPreviousDecl()) {
3189       if (CurD->isThisDeclarationADefinition() == VarDecl::Definition) {
3190         Reader.mergeDefinitionVisibility(CurD, VD);
3191         VD->demoteThisDefinitionToDeclaration();
3192         break;
3193       }
3194     }
3195   }
3196 }
3197 
3198 template<>
3199 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3200                                            Redeclarable<FunctionDecl> *D,
3201                                            Decl *Previous, Decl *Canon) {
3202   FunctionDecl *FD = static_cast<FunctionDecl*>(D);
3203   FunctionDecl *PrevFD = cast<FunctionDecl>(Previous);
3204 
3205   FD->RedeclLink.setPrevious(PrevFD);
3206   FD->First = PrevFD->First;
3207 
3208   // If the previous declaration is an inline function declaration, then this
3209   // declaration is too.
3210   if (PrevFD->IsInline != FD->IsInline) {
3211     // FIXME: [dcl.fct.spec]p4:
3212     //   If a function with external linkage is declared inline in one
3213     //   translation unit, it shall be declared inline in all translation
3214     //   units in which it appears.
3215     //
3216     // Be careful of this case:
3217     //
3218     // module A:
3219     //   template<typename T> struct X { void f(); };
3220     //   template<typename T> inline void X<T>::f() {}
3221     //
3222     // module B instantiates the declaration of X<int>::f
3223     // module C instantiates the definition of X<int>::f
3224     //
3225     // If module B and C are merged, we do not have a violation of this rule.
3226     FD->IsInline = true;
3227   }
3228 
3229   // If we need to propagate an exception specification along the redecl
3230   // chain, make a note of that so that we can do so later.
3231   auto *FPT = FD->getType()->getAs<FunctionProtoType>();
3232   auto *PrevFPT = PrevFD->getType()->getAs<FunctionProtoType>();
3233   if (FPT && PrevFPT) {
3234     bool IsUnresolved = isUnresolvedExceptionSpec(FPT->getExceptionSpecType());
3235     bool WasUnresolved =
3236         isUnresolvedExceptionSpec(PrevFPT->getExceptionSpecType());
3237     if (IsUnresolved != WasUnresolved)
3238       Reader.PendingExceptionSpecUpdates.insert(
3239           std::make_pair(Canon, IsUnresolved ? PrevFD : FD));
3240   }
3241 }
3242 } // end namespace clang
3243 
3244 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader, ...) {
3245   llvm_unreachable("attachPreviousDecl on non-redeclarable declaration");
3246 }
3247 
3248 /// Inherit the default template argument from \p From to \p To. Returns
3249 /// \c false if there is no default template for \p From.
3250 template <typename ParmDecl>
3251 static bool inheritDefaultTemplateArgument(ASTContext &Context, ParmDecl *From,
3252                                            Decl *ToD) {
3253   auto *To = cast<ParmDecl>(ToD);
3254   if (!From->hasDefaultArgument())
3255     return false;
3256   To->setInheritedDefaultArgument(Context, From);
3257   return true;
3258 }
3259 
3260 static void inheritDefaultTemplateArguments(ASTContext &Context,
3261                                             TemplateDecl *From,
3262                                             TemplateDecl *To) {
3263   auto *FromTP = From->getTemplateParameters();
3264   auto *ToTP = To->getTemplateParameters();
3265   assert(FromTP->size() == ToTP->size() && "merged mismatched templates?");
3266 
3267   for (unsigned I = 0, N = FromTP->size(); I != N; ++I) {
3268     NamedDecl *FromParam = FromTP->getParam(N - I - 1);
3269     if (FromParam->isParameterPack())
3270       continue;
3271     NamedDecl *ToParam = ToTP->getParam(N - I - 1);
3272 
3273     if (auto *FTTP = dyn_cast<TemplateTypeParmDecl>(FromParam)) {
3274       if (!inheritDefaultTemplateArgument(Context, FTTP, ToParam))
3275         break;
3276     } else if (auto *FNTTP = dyn_cast<NonTypeTemplateParmDecl>(FromParam)) {
3277       if (!inheritDefaultTemplateArgument(Context, FNTTP, ToParam))
3278         break;
3279     } else {
3280       if (!inheritDefaultTemplateArgument(
3281               Context, cast<TemplateTemplateParmDecl>(FromParam), ToParam))
3282         break;
3283     }
3284   }
3285 }
3286 
3287 void ASTDeclReader::attachPreviousDecl(ASTReader &Reader, Decl *D,
3288                                        Decl *Previous, Decl *Canon) {
3289   assert(D && Previous);
3290 
3291   switch (D->getKind()) {
3292 #define ABSTRACT_DECL(TYPE)
3293 #define DECL(TYPE, BASE)                                                  \
3294   case Decl::TYPE:                                                        \
3295     attachPreviousDeclImpl(Reader, cast<TYPE##Decl>(D), Previous, Canon); \
3296     break;
3297 #include "clang/AST/DeclNodes.inc"
3298   }
3299 
3300   // If the declaration was visible in one module, a redeclaration of it in
3301   // another module remains visible even if it wouldn't be visible by itself.
3302   //
3303   // FIXME: In this case, the declaration should only be visible if a module
3304   //        that makes it visible has been imported.
3305   D->IdentifierNamespace |=
3306       Previous->IdentifierNamespace &
3307       (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
3308 
3309   // If the declaration declares a template, it may inherit default arguments
3310   // from the previous declaration.
3311   if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
3312     inheritDefaultTemplateArguments(Reader.getContext(),
3313                                     cast<TemplateDecl>(Previous), TD);
3314 }
3315 
3316 template<typename DeclT>
3317 void ASTDeclReader::attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest) {
3318   D->RedeclLink.setLatest(cast<DeclT>(Latest));
3319 }
3320 void ASTDeclReader::attachLatestDeclImpl(...) {
3321   llvm_unreachable("attachLatestDecl on non-redeclarable declaration");
3322 }
3323 
3324 void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {
3325   assert(D && Latest);
3326 
3327   switch (D->getKind()) {
3328 #define ABSTRACT_DECL(TYPE)
3329 #define DECL(TYPE, BASE)                                  \
3330   case Decl::TYPE:                                        \
3331     attachLatestDeclImpl(cast<TYPE##Decl>(D), Latest); \
3332     break;
3333 #include "clang/AST/DeclNodes.inc"
3334   }
3335 }
3336 
3337 template<typename DeclT>
3338 void ASTDeclReader::markIncompleteDeclChainImpl(Redeclarable<DeclT> *D) {
3339   D->RedeclLink.markIncomplete();
3340 }
3341 void ASTDeclReader::markIncompleteDeclChainImpl(...) {
3342   llvm_unreachable("markIncompleteDeclChain on non-redeclarable declaration");
3343 }
3344 
3345 void ASTReader::markIncompleteDeclChain(Decl *D) {
3346   switch (D->getKind()) {
3347 #define ABSTRACT_DECL(TYPE)
3348 #define DECL(TYPE, BASE)                                             \
3349   case Decl::TYPE:                                                   \
3350     ASTDeclReader::markIncompleteDeclChainImpl(cast<TYPE##Decl>(D)); \
3351     break;
3352 #include "clang/AST/DeclNodes.inc"
3353   }
3354 }
3355 
3356 /// \brief Read the declaration at the given offset from the AST file.
3357 Decl *ASTReader::ReadDeclRecord(DeclID ID) {
3358   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
3359   SourceLocation DeclLoc;
3360   RecordLocation Loc = DeclCursorForID(ID, DeclLoc);
3361   llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
3362   // Keep track of where we are in the stream, then jump back there
3363   // after reading this declaration.
3364   SavedStreamPosition SavedPosition(DeclsCursor);
3365 
3366   ReadingKindTracker ReadingKind(Read_Decl, *this);
3367 
3368   // Note that we are loading a declaration record.
3369   Deserializing ADecl(this);
3370 
3371   DeclsCursor.JumpToBit(Loc.Offset);
3372   ASTRecordReader Record(*this, *Loc.F);
3373   ASTDeclReader Reader(*this, Record, Loc, ID, DeclLoc);
3374   unsigned Code = DeclsCursor.ReadCode();
3375 
3376   Decl *D = nullptr;
3377   switch ((DeclCode)Record.readRecord(DeclsCursor, Code)) {
3378   case DECL_CONTEXT_LEXICAL:
3379   case DECL_CONTEXT_VISIBLE:
3380     llvm_unreachable("Record cannot be de-serialized with ReadDeclRecord");
3381   case DECL_TYPEDEF:
3382     D = TypedefDecl::CreateDeserialized(Context, ID);
3383     break;
3384   case DECL_TYPEALIAS:
3385     D = TypeAliasDecl::CreateDeserialized(Context, ID);
3386     break;
3387   case DECL_ENUM:
3388     D = EnumDecl::CreateDeserialized(Context, ID);
3389     break;
3390   case DECL_RECORD:
3391     D = RecordDecl::CreateDeserialized(Context, ID);
3392     break;
3393   case DECL_ENUM_CONSTANT:
3394     D = EnumConstantDecl::CreateDeserialized(Context, ID);
3395     break;
3396   case DECL_FUNCTION:
3397     D = FunctionDecl::CreateDeserialized(Context, ID);
3398     break;
3399   case DECL_LINKAGE_SPEC:
3400     D = LinkageSpecDecl::CreateDeserialized(Context, ID);
3401     break;
3402   case DECL_EXPORT:
3403     D = ExportDecl::CreateDeserialized(Context, ID);
3404     break;
3405   case DECL_LABEL:
3406     D = LabelDecl::CreateDeserialized(Context, ID);
3407     break;
3408   case DECL_NAMESPACE:
3409     D = NamespaceDecl::CreateDeserialized(Context, ID);
3410     break;
3411   case DECL_NAMESPACE_ALIAS:
3412     D = NamespaceAliasDecl::CreateDeserialized(Context, ID);
3413     break;
3414   case DECL_USING:
3415     D = UsingDecl::CreateDeserialized(Context, ID);
3416     break;
3417   case DECL_USING_PACK:
3418     D = UsingPackDecl::CreateDeserialized(Context, ID, Record.readInt());
3419     break;
3420   case DECL_USING_SHADOW:
3421     D = UsingShadowDecl::CreateDeserialized(Context, ID);
3422     break;
3423   case DECL_CONSTRUCTOR_USING_SHADOW:
3424     D = ConstructorUsingShadowDecl::CreateDeserialized(Context, ID);
3425     break;
3426   case DECL_USING_DIRECTIVE:
3427     D = UsingDirectiveDecl::CreateDeserialized(Context, ID);
3428     break;
3429   case DECL_UNRESOLVED_USING_VALUE:
3430     D = UnresolvedUsingValueDecl::CreateDeserialized(Context, ID);
3431     break;
3432   case DECL_UNRESOLVED_USING_TYPENAME:
3433     D = UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID);
3434     break;
3435   case DECL_CXX_RECORD:
3436     D = CXXRecordDecl::CreateDeserialized(Context, ID);
3437     break;
3438   case DECL_CXX_DEDUCTION_GUIDE:
3439     D = CXXDeductionGuideDecl::CreateDeserialized(Context, ID);
3440     break;
3441   case DECL_CXX_METHOD:
3442     D = CXXMethodDecl::CreateDeserialized(Context, ID);
3443     break;
3444   case DECL_CXX_CONSTRUCTOR:
3445     D = CXXConstructorDecl::CreateDeserialized(Context, ID, false);
3446     break;
3447   case DECL_CXX_INHERITED_CONSTRUCTOR:
3448     D = CXXConstructorDecl::CreateDeserialized(Context, ID, true);
3449     break;
3450   case DECL_CXX_DESTRUCTOR:
3451     D = CXXDestructorDecl::CreateDeserialized(Context, ID);
3452     break;
3453   case DECL_CXX_CONVERSION:
3454     D = CXXConversionDecl::CreateDeserialized(Context, ID);
3455     break;
3456   case DECL_ACCESS_SPEC:
3457     D = AccessSpecDecl::CreateDeserialized(Context, ID);
3458     break;
3459   case DECL_FRIEND:
3460     D = FriendDecl::CreateDeserialized(Context, ID, Record.readInt());
3461     break;
3462   case DECL_FRIEND_TEMPLATE:
3463     D = FriendTemplateDecl::CreateDeserialized(Context, ID);
3464     break;
3465   case DECL_CLASS_TEMPLATE:
3466     D = ClassTemplateDecl::CreateDeserialized(Context, ID);
3467     break;
3468   case DECL_CLASS_TEMPLATE_SPECIALIZATION:
3469     D = ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3470     break;
3471   case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
3472     D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3473     break;
3474   case DECL_VAR_TEMPLATE:
3475     D = VarTemplateDecl::CreateDeserialized(Context, ID);
3476     break;
3477   case DECL_VAR_TEMPLATE_SPECIALIZATION:
3478     D = VarTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3479     break;
3480   case DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION:
3481     D = VarTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3482     break;
3483   case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
3484     D = ClassScopeFunctionSpecializationDecl::CreateDeserialized(Context, ID);
3485     break;
3486   case DECL_FUNCTION_TEMPLATE:
3487     D = FunctionTemplateDecl::CreateDeserialized(Context, ID);
3488     break;
3489   case DECL_TEMPLATE_TYPE_PARM:
3490     D = TemplateTypeParmDecl::CreateDeserialized(Context, ID);
3491     break;
3492   case DECL_NON_TYPE_TEMPLATE_PARM:
3493     D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID);
3494     break;
3495   case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK:
3496     D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID,
3497                                                     Record.readInt());
3498     break;
3499   case DECL_TEMPLATE_TEMPLATE_PARM:
3500     D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID);
3501     break;
3502   case DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK:
3503     D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID,
3504                                                      Record.readInt());
3505     break;
3506   case DECL_TYPE_ALIAS_TEMPLATE:
3507     D = TypeAliasTemplateDecl::CreateDeserialized(Context, ID);
3508     break;
3509   case DECL_STATIC_ASSERT:
3510     D = StaticAssertDecl::CreateDeserialized(Context, ID);
3511     break;
3512   case DECL_OBJC_METHOD:
3513     D = ObjCMethodDecl::CreateDeserialized(Context, ID);
3514     break;
3515   case DECL_OBJC_INTERFACE:
3516     D = ObjCInterfaceDecl::CreateDeserialized(Context, ID);
3517     break;
3518   case DECL_OBJC_IVAR:
3519     D = ObjCIvarDecl::CreateDeserialized(Context, ID);
3520     break;
3521   case DECL_OBJC_PROTOCOL:
3522     D = ObjCProtocolDecl::CreateDeserialized(Context, ID);
3523     break;
3524   case DECL_OBJC_AT_DEFS_FIELD:
3525     D = ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID);
3526     break;
3527   case DECL_OBJC_CATEGORY:
3528     D = ObjCCategoryDecl::CreateDeserialized(Context, ID);
3529     break;
3530   case DECL_OBJC_CATEGORY_IMPL:
3531     D = ObjCCategoryImplDecl::CreateDeserialized(Context, ID);
3532     break;
3533   case DECL_OBJC_IMPLEMENTATION:
3534     D = ObjCImplementationDecl::CreateDeserialized(Context, ID);
3535     break;
3536   case DECL_OBJC_COMPATIBLE_ALIAS:
3537     D = ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID);
3538     break;
3539   case DECL_OBJC_PROPERTY:
3540     D = ObjCPropertyDecl::CreateDeserialized(Context, ID);
3541     break;
3542   case DECL_OBJC_PROPERTY_IMPL:
3543     D = ObjCPropertyImplDecl::CreateDeserialized(Context, ID);
3544     break;
3545   case DECL_FIELD:
3546     D = FieldDecl::CreateDeserialized(Context, ID);
3547     break;
3548   case DECL_INDIRECTFIELD:
3549     D = IndirectFieldDecl::CreateDeserialized(Context, ID);
3550     break;
3551   case DECL_VAR:
3552     D = VarDecl::CreateDeserialized(Context, ID);
3553     break;
3554   case DECL_IMPLICIT_PARAM:
3555     D = ImplicitParamDecl::CreateDeserialized(Context, ID);
3556     break;
3557   case DECL_PARM_VAR:
3558     D = ParmVarDecl::CreateDeserialized(Context, ID);
3559     break;
3560   case DECL_DECOMPOSITION:
3561     D = DecompositionDecl::CreateDeserialized(Context, ID, Record.readInt());
3562     break;
3563   case DECL_BINDING:
3564     D = BindingDecl::CreateDeserialized(Context, ID);
3565     break;
3566   case DECL_FILE_SCOPE_ASM:
3567     D = FileScopeAsmDecl::CreateDeserialized(Context, ID);
3568     break;
3569   case DECL_BLOCK:
3570     D = BlockDecl::CreateDeserialized(Context, ID);
3571     break;
3572   case DECL_MS_PROPERTY:
3573     D = MSPropertyDecl::CreateDeserialized(Context, ID);
3574     break;
3575   case DECL_CAPTURED:
3576     D = CapturedDecl::CreateDeserialized(Context, ID, Record.readInt());
3577     break;
3578   case DECL_CXX_BASE_SPECIFIERS:
3579     Error("attempt to read a C++ base-specifier record as a declaration");
3580     return nullptr;
3581   case DECL_CXX_CTOR_INITIALIZERS:
3582     Error("attempt to read a C++ ctor initializer record as a declaration");
3583     return nullptr;
3584   case DECL_IMPORT:
3585     // Note: last entry of the ImportDecl record is the number of stored source
3586     // locations.
3587     D = ImportDecl::CreateDeserialized(Context, ID, Record.back());
3588     break;
3589   case DECL_OMP_THREADPRIVATE:
3590     D = OMPThreadPrivateDecl::CreateDeserialized(Context, ID, Record.readInt());
3591     break;
3592   case DECL_OMP_DECLARE_REDUCTION:
3593     D = OMPDeclareReductionDecl::CreateDeserialized(Context, ID);
3594     break;
3595   case DECL_OMP_CAPTUREDEXPR:
3596     D = OMPCapturedExprDecl::CreateDeserialized(Context, ID);
3597     break;
3598   case DECL_PRAGMA_COMMENT:
3599     D = PragmaCommentDecl::CreateDeserialized(Context, ID, Record.readInt());
3600     break;
3601   case DECL_PRAGMA_DETECT_MISMATCH:
3602     D = PragmaDetectMismatchDecl::CreateDeserialized(Context, ID,
3603                                                      Record.readInt());
3604     break;
3605   case DECL_EMPTY:
3606     D = EmptyDecl::CreateDeserialized(Context, ID);
3607     break;
3608   case DECL_OBJC_TYPE_PARAM:
3609     D = ObjCTypeParamDecl::CreateDeserialized(Context, ID);
3610     break;
3611   }
3612 
3613   assert(D && "Unknown declaration reading AST file");
3614   LoadedDecl(Index, D);
3615   // Set the DeclContext before doing any deserialization, to make sure internal
3616   // calls to Decl::getASTContext() by Decl's methods will find the
3617   // TranslationUnitDecl without crashing.
3618   D->setDeclContext(Context.getTranslationUnitDecl());
3619   Reader.Visit(D);
3620 
3621   // If this declaration is also a declaration context, get the
3622   // offsets for its tables of lexical and visible declarations.
3623   if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
3624     std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
3625     if (Offsets.first &&
3626         ReadLexicalDeclContextStorage(*Loc.F, DeclsCursor, Offsets.first, DC))
3627       return nullptr;
3628     if (Offsets.second &&
3629         ReadVisibleDeclContextStorage(*Loc.F, DeclsCursor, Offsets.second, ID))
3630       return nullptr;
3631   }
3632   assert(Record.getIdx() == Record.size());
3633 
3634   // Load any relevant update records.
3635   PendingUpdateRecords.push_back(
3636       PendingUpdateRecord(ID, D, /*JustLoaded=*/true));
3637 
3638   // Load the categories after recursive loading is finished.
3639   if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3640     // If we already have a definition when deserializing the ObjCInterfaceDecl,
3641     // we put the Decl in PendingDefinitions so we can pull the categories here.
3642     if (Class->isThisDeclarationADefinition() ||
3643         PendingDefinitions.count(Class))
3644       loadObjCCategories(ID, Class);
3645 
3646   // If we have deserialized a declaration that has a definition the
3647   // AST consumer might need to know about, queue it.
3648   // We don't pass it to the consumer immediately because we may be in recursive
3649   // loading, and some declarations may still be initializing.
3650   PotentiallyInterestingDecls.push_back(
3651       InterestingDecl(D, Reader.hasPendingBody()));
3652 
3653   return D;
3654 }
3655 
3656 void ASTReader::PassInterestingDeclsToConsumer() {
3657   assert(Consumer);
3658 
3659   if (PassingDeclsToConsumer)
3660     return;
3661 
3662   // Guard variable to avoid recursively redoing the process of passing
3663   // decls to consumer.
3664   SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
3665                                                    true);
3666 
3667   // Ensure that we've loaded all potentially-interesting declarations
3668   // that need to be eagerly loaded.
3669   for (auto ID : EagerlyDeserializedDecls)
3670     GetDecl(ID);
3671   EagerlyDeserializedDecls.clear();
3672 
3673   while (!PotentiallyInterestingDecls.empty()) {
3674     InterestingDecl D = PotentiallyInterestingDecls.front();
3675     PotentiallyInterestingDecls.pop_front();
3676     if (isConsumerInterestedIn(Context, D.getDecl(), D.hasPendingBody()))
3677       PassInterestingDeclToConsumer(D.getDecl());
3678   }
3679 }
3680 
3681 void ASTReader::loadDeclUpdateRecords(PendingUpdateRecord &Record) {
3682   // The declaration may have been modified by files later in the chain.
3683   // If this is the case, read the record containing the updates from each file
3684   // and pass it to ASTDeclReader to make the modifications.
3685   serialization::GlobalDeclID ID = Record.ID;
3686   Decl *D = Record.D;
3687   ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
3688   DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
3689   if (UpdI != DeclUpdateOffsets.end()) {
3690     auto UpdateOffsets = std::move(UpdI->second);
3691     DeclUpdateOffsets.erase(UpdI);
3692 
3693     // Check if this decl was interesting to the consumer. If we just loaded
3694     // the declaration, then we know it was interesting and we skip the call
3695     // to isConsumerInterestedIn because it is unsafe to call in the
3696     // current ASTReader state.
3697     bool WasInteresting =
3698         Record.JustLoaded || isConsumerInterestedIn(Context, D, false);
3699     for (auto &FileAndOffset : UpdateOffsets) {
3700       ModuleFile *F = FileAndOffset.first;
3701       uint64_t Offset = FileAndOffset.second;
3702       llvm::BitstreamCursor &Cursor = F->DeclsCursor;
3703       SavedStreamPosition SavedPosition(Cursor);
3704       Cursor.JumpToBit(Offset);
3705       unsigned Code = Cursor.ReadCode();
3706       ASTRecordReader Record(*this, *F);
3707       unsigned RecCode = Record.readRecord(Cursor, Code);
3708       (void)RecCode;
3709       assert(RecCode == DECL_UPDATES && "Expected DECL_UPDATES record!");
3710 
3711       ASTDeclReader Reader(*this, Record, RecordLocation(F, Offset), ID,
3712                            SourceLocation());
3713       Reader.UpdateDecl(D);
3714 
3715       // We might have made this declaration interesting. If so, remember that
3716       // we need to hand it off to the consumer.
3717       if (!WasInteresting &&
3718           isConsumerInterestedIn(Context, D, Reader.hasPendingBody())) {
3719         PotentiallyInterestingDecls.push_back(
3720             InterestingDecl(D, Reader.hasPendingBody()));
3721         WasInteresting = true;
3722       }
3723     }
3724   }
3725 
3726   // Load the pending visible updates for this decl context, if it has any.
3727   auto I = PendingVisibleUpdates.find(ID);
3728   if (I != PendingVisibleUpdates.end()) {
3729     auto VisibleUpdates = std::move(I->second);
3730     PendingVisibleUpdates.erase(I);
3731 
3732     auto *DC = cast<DeclContext>(D)->getPrimaryContext();
3733     for (const PendingVisibleUpdate &Update : VisibleUpdates)
3734       Lookups[DC].Table.add(
3735           Update.Mod, Update.Data,
3736           reader::ASTDeclContextNameLookupTrait(*this, *Update.Mod));
3737     DC->setHasExternalVisibleStorage(true);
3738   }
3739 }
3740 
3741 void ASTReader::loadPendingDeclChain(Decl *FirstLocal, uint64_t LocalOffset) {
3742   // Attach FirstLocal to the end of the decl chain.
3743   Decl *CanonDecl = FirstLocal->getCanonicalDecl();
3744   if (FirstLocal != CanonDecl) {
3745     Decl *PrevMostRecent = ASTDeclReader::getMostRecentDecl(CanonDecl);
3746     ASTDeclReader::attachPreviousDecl(
3747         *this, FirstLocal, PrevMostRecent ? PrevMostRecent : CanonDecl,
3748         CanonDecl);
3749   }
3750 
3751   if (!LocalOffset) {
3752     ASTDeclReader::attachLatestDecl(CanonDecl, FirstLocal);
3753     return;
3754   }
3755 
3756   // Load the list of other redeclarations from this module file.
3757   ModuleFile *M = getOwningModuleFile(FirstLocal);
3758   assert(M && "imported decl from no module file");
3759 
3760   llvm::BitstreamCursor &Cursor = M->DeclsCursor;
3761   SavedStreamPosition SavedPosition(Cursor);
3762   Cursor.JumpToBit(LocalOffset);
3763 
3764   RecordData Record;
3765   unsigned Code = Cursor.ReadCode();
3766   unsigned RecCode = Cursor.readRecord(Code, Record);
3767   (void)RecCode;
3768   assert(RecCode == LOCAL_REDECLARATIONS && "expected LOCAL_REDECLARATIONS record!");
3769 
3770   // FIXME: We have several different dispatches on decl kind here; maybe
3771   // we should instead generate one loop per kind and dispatch up-front?
3772   Decl *MostRecent = FirstLocal;
3773   for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3774     auto *D = GetLocalDecl(*M, Record[N - I - 1]);
3775     ASTDeclReader::attachPreviousDecl(*this, D, MostRecent, CanonDecl);
3776     MostRecent = D;
3777   }
3778   ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent);
3779 }
3780 
3781 namespace {
3782   /// \brief Given an ObjC interface, goes through the modules and links to the
3783   /// interface all the categories for it.
3784   class ObjCCategoriesVisitor {
3785     ASTReader &Reader;
3786     ObjCInterfaceDecl *Interface;
3787     llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized;
3788     ObjCCategoryDecl *Tail;
3789     llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
3790     serialization::GlobalDeclID InterfaceID;
3791     unsigned PreviousGeneration;
3792 
3793     void add(ObjCCategoryDecl *Cat) {
3794       // Only process each category once.
3795       if (!Deserialized.erase(Cat))
3796         return;
3797 
3798       // Check for duplicate categories.
3799       if (Cat->getDeclName()) {
3800         ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
3801         if (Existing &&
3802             Reader.getOwningModuleFile(Existing)
3803                                           != Reader.getOwningModuleFile(Cat)) {
3804           // FIXME: We should not warn for duplicates in diamond:
3805           //
3806           //   MT     //
3807           //  /  \    //
3808           // ML  MR   //
3809           //  \  /    //
3810           //   MB     //
3811           //
3812           // If there are duplicates in ML/MR, there will be warning when
3813           // creating MB *and* when importing MB. We should not warn when
3814           // importing.
3815           Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
3816             << Interface->getDeclName() << Cat->getDeclName();
3817           Reader.Diag(Existing->getLocation(), diag::note_previous_definition);
3818         } else if (!Existing) {
3819           // Record this category.
3820           Existing = Cat;
3821         }
3822       }
3823 
3824       // Add this category to the end of the chain.
3825       if (Tail)
3826         ASTDeclReader::setNextObjCCategory(Tail, Cat);
3827       else
3828         Interface->setCategoryListRaw(Cat);
3829       Tail = Cat;
3830     }
3831 
3832   public:
3833     ObjCCategoriesVisitor(ASTReader &Reader,
3834                           ObjCInterfaceDecl *Interface,
3835                           llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized,
3836                           serialization::GlobalDeclID InterfaceID,
3837                           unsigned PreviousGeneration)
3838       : Reader(Reader), Interface(Interface), Deserialized(Deserialized),
3839         Tail(nullptr), InterfaceID(InterfaceID),
3840         PreviousGeneration(PreviousGeneration)
3841     {
3842       // Populate the name -> category map with the set of known categories.
3843       for (auto *Cat : Interface->known_categories()) {
3844         if (Cat->getDeclName())
3845           NameCategoryMap[Cat->getDeclName()] = Cat;
3846 
3847         // Keep track of the tail of the category list.
3848         Tail = Cat;
3849       }
3850     }
3851 
3852     bool operator()(ModuleFile &M) {
3853       // If we've loaded all of the category information we care about from
3854       // this module file, we're done.
3855       if (M.Generation <= PreviousGeneration)
3856         return true;
3857 
3858       // Map global ID of the definition down to the local ID used in this
3859       // module file. If there is no such mapping, we'll find nothing here
3860       // (or in any module it imports).
3861       DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID);
3862       if (!LocalID)
3863         return true;
3864 
3865       // Perform a binary search to find the local redeclarations for this
3866       // declaration (if any).
3867       const ObjCCategoriesInfo Compare = { LocalID, 0 };
3868       const ObjCCategoriesInfo *Result
3869         = std::lower_bound(M.ObjCCategoriesMap,
3870                            M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap,
3871                            Compare);
3872       if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap ||
3873           Result->DefinitionID != LocalID) {
3874         // We didn't find anything. If the class definition is in this module
3875         // file, then the module files it depends on cannot have any categories,
3876         // so suppress further lookup.
3877         return Reader.isDeclIDFromModule(InterfaceID, M);
3878       }
3879 
3880       // We found something. Dig out all of the categories.
3881       unsigned Offset = Result->Offset;
3882       unsigned N = M.ObjCCategories[Offset];
3883       M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again
3884       for (unsigned I = 0; I != N; ++I)
3885         add(cast_or_null<ObjCCategoryDecl>(
3886               Reader.GetLocalDecl(M, M.ObjCCategories[Offset++])));
3887       return true;
3888     }
3889   };
3890 } // end anonymous namespace
3891 
3892 void ASTReader::loadObjCCategories(serialization::GlobalDeclID ID,
3893                                    ObjCInterfaceDecl *D,
3894                                    unsigned PreviousGeneration) {
3895   ObjCCategoriesVisitor Visitor(*this, D, CategoriesDeserialized, ID,
3896                                 PreviousGeneration);
3897   ModuleMgr.visit(Visitor);
3898 }
3899 
3900 template<typename DeclT, typename Fn>
3901 static void forAllLaterRedecls(DeclT *D, Fn F) {
3902   F(D);
3903 
3904   // Check whether we've already merged D into its redeclaration chain.
3905   // MostRecent may or may not be nullptr if D has not been merged. If
3906   // not, walk the merged redecl chain and see if it's there.
3907   auto *MostRecent = D->getMostRecentDecl();
3908   bool Found = false;
3909   for (auto *Redecl = MostRecent; Redecl && !Found;
3910        Redecl = Redecl->getPreviousDecl())
3911     Found = (Redecl == D);
3912 
3913   // If this declaration is merged, apply the functor to all later decls.
3914   if (Found) {
3915     for (auto *Redecl = MostRecent; Redecl != D;
3916          Redecl = Redecl->getPreviousDecl())
3917       F(Redecl);
3918   }
3919 }
3920 
3921 void ASTDeclReader::UpdateDecl(Decl *D) {
3922   while (Record.getIdx() < Record.size()) {
3923     switch ((DeclUpdateKind)Record.readInt()) {
3924     case UPD_CXX_ADDED_IMPLICIT_MEMBER: {
3925       auto *RD = cast<CXXRecordDecl>(D);
3926       // FIXME: If we also have an update record for instantiating the
3927       // definition of D, we need that to happen before we get here.
3928       Decl *MD = Record.readDecl();
3929       assert(MD && "couldn't read decl from update record");
3930       // FIXME: We should call addHiddenDecl instead, to add the member
3931       // to its DeclContext.
3932       RD->addedMember(MD);
3933       break;
3934     }
3935 
3936     case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
3937       // It will be added to the template's specializations set when loaded.
3938       (void)Record.readDecl();
3939       break;
3940 
3941     case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
3942       NamespaceDecl *Anon = ReadDeclAs<NamespaceDecl>();
3943 
3944       // Each module has its own anonymous namespace, which is disjoint from
3945       // any other module's anonymous namespaces, so don't attach the anonymous
3946       // namespace at all.
3947       if (!Record.isModule()) {
3948         if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(D))
3949           TU->setAnonymousNamespace(Anon);
3950         else
3951           cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon);
3952       }
3953       break;
3954     }
3955 
3956     case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER: {
3957       VarDecl *VD = cast<VarDecl>(D);
3958       VD->getMemberSpecializationInfo()->setPointOfInstantiation(
3959           ReadSourceLocation());
3960       uint64_t Val = Record.readInt();
3961       if (Val && !VD->getInit()) {
3962         VD->setInit(Record.readExpr());
3963         if (Val > 1) { // IsInitKnownICE = 1, IsInitNotICE = 2, IsInitICE = 3
3964           EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
3965           Eval->CheckedICE = true;
3966           Eval->IsICE = Val == 3;
3967         }
3968       }
3969       break;
3970     }
3971 
3972     case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT: {
3973       auto Param = cast<ParmVarDecl>(D);
3974 
3975       // We have to read the default argument regardless of whether we use it
3976       // so that hypothetical further update records aren't messed up.
3977       // TODO: Add a function to skip over the next expr record.
3978       auto DefaultArg = Record.readExpr();
3979 
3980       // Only apply the update if the parameter still has an uninstantiated
3981       // default argument.
3982       if (Param->hasUninstantiatedDefaultArg())
3983         Param->setDefaultArg(DefaultArg);
3984       break;
3985     }
3986 
3987     case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER: {
3988       auto FD = cast<FieldDecl>(D);
3989       auto DefaultInit = Record.readExpr();
3990 
3991       // Only apply the update if the field still has an uninstantiated
3992       // default member initializer.
3993       if (FD->hasInClassInitializer() && !FD->getInClassInitializer()) {
3994         if (DefaultInit)
3995           FD->setInClassInitializer(DefaultInit);
3996         else
3997           // Instantiation failed. We can get here if we serialized an AST for
3998           // an invalid program.
3999           FD->removeInClassInitializer();
4000       }
4001       break;
4002     }
4003 
4004     case UPD_CXX_ADDED_FUNCTION_DEFINITION: {
4005       FunctionDecl *FD = cast<FunctionDecl>(D);
4006       if (Reader.PendingBodies[FD]) {
4007         // FIXME: Maybe check for ODR violations.
4008         // It's safe to stop now because this update record is always last.
4009         return;
4010       }
4011 
4012       if (Record.readInt()) {
4013         // Maintain AST consistency: any later redeclarations of this function
4014         // are inline if this one is. (We might have merged another declaration
4015         // into this one.)
4016         forAllLaterRedecls(FD, [](FunctionDecl *FD) {
4017           FD->setImplicitlyInline();
4018         });
4019       }
4020       FD->setInnerLocStart(ReadSourceLocation());
4021       ReadFunctionDefinition(FD);
4022       assert(Record.getIdx() == Record.size() && "lazy body must be last");
4023       break;
4024     }
4025 
4026     case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4027       auto *RD = cast<CXXRecordDecl>(D);
4028       auto *OldDD = RD->getCanonicalDecl()->DefinitionData;
4029       bool HadRealDefinition =
4030           OldDD && (OldDD->Definition != RD ||
4031                     !Reader.PendingFakeDefinitionData.count(OldDD));
4032       ReadCXXRecordDefinition(RD, /*Update*/true);
4033 
4034       // Visible update is handled separately.
4035       uint64_t LexicalOffset = ReadLocalOffset();
4036       if (!HadRealDefinition && LexicalOffset) {
4037         Record.readLexicalDeclContextStorage(LexicalOffset, RD);
4038         Reader.PendingFakeDefinitionData.erase(OldDD);
4039       }
4040 
4041       auto TSK = (TemplateSpecializationKind)Record.readInt();
4042       SourceLocation POI = ReadSourceLocation();
4043       if (MemberSpecializationInfo *MSInfo =
4044               RD->getMemberSpecializationInfo()) {
4045         MSInfo->setTemplateSpecializationKind(TSK);
4046         MSInfo->setPointOfInstantiation(POI);
4047       } else {
4048         ClassTemplateSpecializationDecl *Spec =
4049             cast<ClassTemplateSpecializationDecl>(RD);
4050         Spec->setTemplateSpecializationKind(TSK);
4051         Spec->setPointOfInstantiation(POI);
4052 
4053         if (Record.readInt()) {
4054           auto PartialSpec =
4055               ReadDeclAs<ClassTemplatePartialSpecializationDecl>();
4056           SmallVector<TemplateArgument, 8> TemplArgs;
4057           Record.readTemplateArgumentList(TemplArgs);
4058           auto *TemplArgList = TemplateArgumentList::CreateCopy(
4059               Reader.getContext(), TemplArgs);
4060 
4061           // FIXME: If we already have a partial specialization set,
4062           // check that it matches.
4063           if (!Spec->getSpecializedTemplateOrPartial()
4064                    .is<ClassTemplatePartialSpecializationDecl *>())
4065             Spec->setInstantiationOf(PartialSpec, TemplArgList);
4066         }
4067       }
4068 
4069       RD->setTagKind((TagTypeKind)Record.readInt());
4070       RD->setLocation(ReadSourceLocation());
4071       RD->setLocStart(ReadSourceLocation());
4072       RD->setBraceRange(ReadSourceRange());
4073 
4074       if (Record.readInt()) {
4075         AttrVec Attrs;
4076         Record.readAttributes(Attrs);
4077         // If the declaration already has attributes, we assume that some other
4078         // AST file already loaded them.
4079         if (!D->hasAttrs())
4080           D->setAttrsImpl(Attrs, Reader.getContext());
4081       }
4082       break;
4083     }
4084 
4085     case UPD_CXX_RESOLVED_DTOR_DELETE: {
4086       // Set the 'operator delete' directly to avoid emitting another update
4087       // record.
4088       auto *Del = ReadDeclAs<FunctionDecl>();
4089       auto *First = cast<CXXDestructorDecl>(D->getCanonicalDecl());
4090       // FIXME: Check consistency if we have an old and new operator delete.
4091       if (!First->OperatorDelete)
4092         First->OperatorDelete = Del;
4093       break;
4094     }
4095 
4096     case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {
4097       FunctionProtoType::ExceptionSpecInfo ESI;
4098       SmallVector<QualType, 8> ExceptionStorage;
4099       Record.readExceptionSpec(ExceptionStorage, ESI);
4100 
4101       // Update this declaration's exception specification, if needed.
4102       auto *FD = cast<FunctionDecl>(D);
4103       auto *FPT = FD->getType()->castAs<FunctionProtoType>();
4104       // FIXME: If the exception specification is already present, check that it
4105       // matches.
4106       if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
4107         FD->setType(Reader.Context.getFunctionType(
4108             FPT->getReturnType(), FPT->getParamTypes(),
4109             FPT->getExtProtoInfo().withExceptionSpec(ESI)));
4110 
4111         // When we get to the end of deserializing, see if there are other decls
4112         // that we need to propagate this exception specification onto.
4113         Reader.PendingExceptionSpecUpdates.insert(
4114             std::make_pair(FD->getCanonicalDecl(), FD));
4115       }
4116       break;
4117     }
4118 
4119     case UPD_CXX_DEDUCED_RETURN_TYPE: {
4120       // FIXME: Also do this when merging redecls.
4121       QualType DeducedResultType = Record.readType();
4122       for (auto *Redecl : merged_redecls(D)) {
4123         // FIXME: If the return type is already deduced, check that it matches.
4124         FunctionDecl *FD = cast<FunctionDecl>(Redecl);
4125         Reader.Context.adjustDeducedFunctionResultType(FD, DeducedResultType);
4126       }
4127       break;
4128     }
4129 
4130     case UPD_DECL_MARKED_USED: {
4131       // Maintain AST consistency: any later redeclarations are used too.
4132       D->markUsed(Reader.Context);
4133       break;
4134     }
4135 
4136     case UPD_MANGLING_NUMBER:
4137       Reader.Context.setManglingNumber(cast<NamedDecl>(D), Record.readInt());
4138       break;
4139 
4140     case UPD_STATIC_LOCAL_NUMBER:
4141       Reader.Context.setStaticLocalNumber(cast<VarDecl>(D), Record.readInt());
4142       break;
4143 
4144     case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
4145       D->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
4146           Reader.Context, ReadSourceRange()));
4147       break;
4148 
4149     case UPD_DECL_EXPORTED: {
4150       unsigned SubmoduleID = readSubmoduleID();
4151       auto *Exported = cast<NamedDecl>(D);
4152       if (auto *TD = dyn_cast<TagDecl>(Exported))
4153         Exported = TD->getDefinition();
4154       Module *Owner = SubmoduleID ? Reader.getSubmodule(SubmoduleID) : nullptr;
4155       if (Reader.getContext().getLangOpts().ModulesLocalVisibility) {
4156         Reader.getContext().mergeDefinitionIntoModule(cast<NamedDecl>(Exported),
4157                                                       Owner);
4158         Reader.PendingMergedDefinitionsToDeduplicate.insert(
4159             cast<NamedDecl>(Exported));
4160       } else if (Owner && Owner->NameVisibility != Module::AllVisible) {
4161         // If Owner is made visible at some later point, make this declaration
4162         // visible too.
4163         Reader.HiddenNamesMap[Owner].push_back(Exported);
4164       } else {
4165         // The declaration is now visible.
4166         Exported->setVisibleDespiteOwningModule();
4167       }
4168       break;
4169     }
4170 
4171     case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
4172     case UPD_ADDED_ATTR_TO_RECORD:
4173       AttrVec Attrs;
4174       Record.readAttributes(Attrs);
4175       assert(Attrs.size() == 1);
4176       D->addAttr(Attrs[0]);
4177       break;
4178     }
4179   }
4180 }
4181