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