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