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