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