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