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