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