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