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