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