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