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