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