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   llvm::FoldingSetNodeID Cand1ID, Cand2ID;
2917   auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
2918   auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
2919 
2920   for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
2921     Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
2922     Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
2923 
2924     // Return false if the number of enable_if attributes is different.
2925     if (!Cand1A || !Cand2A)
2926       return false;
2927 
2928     Cand1ID.clear();
2929     Cand2ID.clear();
2930 
2931     (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
2932     (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
2933 
2934     // Return false if any of the enable_if expressions of A and B are
2935     // different.
2936     if (Cand1ID != Cand2ID)
2937       return false;
2938   }
2939   return true;
2940 }
2941 
2942 /// Determine whether the two declarations refer to the same entity.
2943 static bool isSameEntity(NamedDecl *X, NamedDecl *Y) {
2944   assert(X->getDeclName() == Y->getDeclName() && "Declaration name mismatch!");
2945 
2946   if (X == Y)
2947     return true;
2948 
2949   // Must be in the same context.
2950   //
2951   // Note that we can't use DeclContext::Equals here, because the DeclContexts
2952   // could be two different declarations of the same function. (We will fix the
2953   // semantic DC to refer to the primary definition after merging.)
2954   if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
2955                           cast<Decl>(Y->getDeclContext()->getRedeclContext())))
2956     return false;
2957 
2958   // Two typedefs refer to the same entity if they have the same underlying
2959   // type.
2960   if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
2961     if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
2962       return X->getASTContext().hasSameType(TypedefX->getUnderlyingType(),
2963                                             TypedefY->getUnderlyingType());
2964 
2965   // Must have the same kind.
2966   if (X->getKind() != Y->getKind())
2967     return false;
2968 
2969   // Objective-C classes and protocols with the same name always match.
2970   if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
2971     return true;
2972 
2973   if (isa<ClassTemplateSpecializationDecl>(X)) {
2974     // No need to handle these here: we merge them when adding them to the
2975     // template.
2976     return false;
2977   }
2978 
2979   // Compatible tags match.
2980   if (const auto *TagX = dyn_cast<TagDecl>(X)) {
2981     const auto *TagY = cast<TagDecl>(Y);
2982     return (TagX->getTagKind() == TagY->getTagKind()) ||
2983       ((TagX->getTagKind() == TTK_Struct || TagX->getTagKind() == TTK_Class ||
2984         TagX->getTagKind() == TTK_Interface) &&
2985        (TagY->getTagKind() == TTK_Struct || TagY->getTagKind() == TTK_Class ||
2986         TagY->getTagKind() == TTK_Interface));
2987   }
2988 
2989   // Functions with the same type and linkage match.
2990   // FIXME: This needs to cope with merging of prototyped/non-prototyped
2991   // functions, etc.
2992   if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
2993     const auto *FuncY = cast<FunctionDecl>(Y);
2994     if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
2995       const auto *CtorY = cast<CXXConstructorDecl>(Y);
2996       if (CtorX->getInheritedConstructor() &&
2997           !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
2998                         CtorY->getInheritedConstructor().getConstructor()))
2999         return false;
3000     }
3001 
3002     if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
3003       return false;
3004 
3005     // Multiversioned functions with different feature strings are represented
3006     // as separate declarations.
3007     if (FuncX->isMultiVersion()) {
3008       const auto *TAX = FuncX->getAttr<TargetAttr>();
3009       const auto *TAY = FuncY->getAttr<TargetAttr>();
3010       assert(TAX && TAY && "Multiversion Function without target attribute");
3011 
3012       if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
3013         return false;
3014     }
3015 
3016     ASTContext &C = FuncX->getASTContext();
3017     auto GetTypeAsWritten = [](const FunctionDecl *FD) {
3018       // Map to the first declaration that we've already merged into this one.
3019       // The TSI of redeclarations might not match (due to calling conventions
3020       // being inherited onto the type but not the TSI), but the TSI type of
3021       // the first declaration of the function should match across modules.
3022       FD = FD->getCanonicalDecl();
3023       return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
3024                                      : FD->getType();
3025     };
3026     QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
3027     if (!C.hasSameType(XT, YT)) {
3028       // We can get functions with different types on the redecl chain in C++17
3029       // if they have differing exception specifications and at least one of
3030       // the excpetion specs is unresolved.
3031       auto *XFPT = XT->getAs<FunctionProtoType>();
3032       auto *YFPT = YT->getAs<FunctionProtoType>();
3033       if (C.getLangOpts().CPlusPlus17 && XFPT && YFPT &&
3034           (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
3035            isUnresolvedExceptionSpec(YFPT->getExceptionSpecType())) &&
3036           C.hasSameFunctionTypeIgnoringExceptionSpec(XT, YT))
3037         return true;
3038       return false;
3039     }
3040     return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
3041            hasSameOverloadableAttrs(FuncX, FuncY);
3042   }
3043 
3044   // Variables with the same type and linkage match.
3045   if (const auto *VarX = dyn_cast<VarDecl>(X)) {
3046     const auto *VarY = cast<VarDecl>(Y);
3047     if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
3048       ASTContext &C = VarX->getASTContext();
3049       if (C.hasSameType(VarX->getType(), VarY->getType()))
3050         return true;
3051 
3052       // We can get decls with different types on the redecl chain. Eg.
3053       // template <typename T> struct S { static T Var[]; }; // #1
3054       // template <typename T> T S<T>::Var[sizeof(T)]; // #2
3055       // Only? happens when completing an incomplete array type. In this case
3056       // when comparing #1 and #2 we should go through their element type.
3057       const ArrayType *VarXTy = C.getAsArrayType(VarX->getType());
3058       const ArrayType *VarYTy = C.getAsArrayType(VarY->getType());
3059       if (!VarXTy || !VarYTy)
3060         return false;
3061       if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
3062         return C.hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
3063     }
3064     return false;
3065   }
3066 
3067   // Namespaces with the same name and inlinedness match.
3068   if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
3069     const auto *NamespaceY = cast<NamespaceDecl>(Y);
3070     return NamespaceX->isInline() == NamespaceY->isInline();
3071   }
3072 
3073   // Identical template names and kinds match if their template parameter lists
3074   // and patterns match.
3075   if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
3076     const auto *TemplateY = cast<TemplateDecl>(Y);
3077     return isSameEntity(TemplateX->getTemplatedDecl(),
3078                         TemplateY->getTemplatedDecl()) &&
3079            isSameTemplateParameterList(TemplateX->getTemplateParameters(),
3080                                        TemplateY->getTemplateParameters());
3081   }
3082 
3083   // Fields with the same name and the same type match.
3084   if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
3085     const auto *FDY = cast<FieldDecl>(Y);
3086     // FIXME: Also check the bitwidth is odr-equivalent, if any.
3087     return X->getASTContext().hasSameType(FDX->getType(), FDY->getType());
3088   }
3089 
3090   // Indirect fields with the same target field match.
3091   if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
3092     const auto *IFDY = cast<IndirectFieldDecl>(Y);
3093     return IFDX->getAnonField()->getCanonicalDecl() ==
3094            IFDY->getAnonField()->getCanonicalDecl();
3095   }
3096 
3097   // Enumerators with the same name match.
3098   if (isa<EnumConstantDecl>(X))
3099     // FIXME: Also check the value is odr-equivalent.
3100     return true;
3101 
3102   // Using shadow declarations with the same target match.
3103   if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
3104     const auto *USY = cast<UsingShadowDecl>(Y);
3105     return USX->getTargetDecl() == USY->getTargetDecl();
3106   }
3107 
3108   // Using declarations with the same qualifier match. (We already know that
3109   // the name matches.)
3110   if (const auto *UX = dyn_cast<UsingDecl>(X)) {
3111     const auto *UY = cast<UsingDecl>(Y);
3112     return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
3113            UX->hasTypename() == UY->hasTypename() &&
3114            UX->isAccessDeclaration() == UY->isAccessDeclaration();
3115   }
3116   if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
3117     const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
3118     return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
3119            UX->isAccessDeclaration() == UY->isAccessDeclaration();
3120   }
3121   if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X))
3122     return isSameQualifier(
3123         UX->getQualifier(),
3124         cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
3125 
3126   // Namespace alias definitions with the same target match.
3127   if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
3128     const auto *NAY = cast<NamespaceAliasDecl>(Y);
3129     return NAX->getNamespace()->Equals(NAY->getNamespace());
3130   }
3131 
3132   return false;
3133 }
3134 
3135 /// Find the context in which we should search for previous declarations when
3136 /// looking for declarations to merge.
3137 DeclContext *ASTDeclReader::getPrimaryContextForMerging(ASTReader &Reader,
3138                                                         DeclContext *DC) {
3139   if (auto *ND = dyn_cast<NamespaceDecl>(DC))
3140     return ND->getOriginalNamespace();
3141 
3142   if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
3143     // Try to dig out the definition.
3144     auto *DD = RD->DefinitionData;
3145     if (!DD)
3146       DD = RD->getCanonicalDecl()->DefinitionData;
3147 
3148     // If there's no definition yet, then DC's definition is added by an update
3149     // record, but we've not yet loaded that update record. In this case, we
3150     // commit to DC being the canonical definition now, and will fix this when
3151     // we load the update record.
3152     if (!DD) {
3153       DD = new (Reader.getContext()) struct CXXRecordDecl::DefinitionData(RD);
3154       RD->setCompleteDefinition(true);
3155       RD->DefinitionData = DD;
3156       RD->getCanonicalDecl()->DefinitionData = DD;
3157 
3158       // Track that we did this horrible thing so that we can fix it later.
3159       Reader.PendingFakeDefinitionData.insert(
3160           std::make_pair(DD, ASTReader::PendingFakeDefinitionKind::Fake));
3161     }
3162 
3163     return DD->Definition;
3164   }
3165 
3166   if (auto *ED = dyn_cast<EnumDecl>(DC))
3167     return ED->getASTContext().getLangOpts().CPlusPlus? ED->getDefinition()
3168                                                       : nullptr;
3169 
3170   // We can see the TU here only if we have no Sema object. In that case,
3171   // there's no TU scope to look in, so using the DC alone is sufficient.
3172   if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
3173     return TU;
3174 
3175   return nullptr;
3176 }
3177 
3178 ASTDeclReader::FindExistingResult::~FindExistingResult() {
3179   // Record that we had a typedef name for linkage whether or not we merge
3180   // with that declaration.
3181   if (TypedefNameForLinkage) {
3182     DeclContext *DC = New->getDeclContext()->getRedeclContext();
3183     Reader.ImportedTypedefNamesForLinkage.insert(
3184         std::make_pair(std::make_pair(DC, TypedefNameForLinkage), New));
3185     return;
3186   }
3187 
3188   if (!AddResult || Existing)
3189     return;
3190 
3191   DeclarationName Name = New->getDeclName();
3192   DeclContext *DC = New->getDeclContext()->getRedeclContext();
3193   if (needsAnonymousDeclarationNumber(New)) {
3194     setAnonymousDeclForMerging(Reader, New->getLexicalDeclContext(),
3195                                AnonymousDeclNumber, New);
3196   } else if (DC->isTranslationUnit() &&
3197              !Reader.getContext().getLangOpts().CPlusPlus) {
3198     if (Reader.getIdResolver().tryAddTopLevelDecl(New, Name))
3199       Reader.PendingFakeLookupResults[Name.getAsIdentifierInfo()]
3200             .push_back(New);
3201   } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
3202     // Add the declaration to its redeclaration context so later merging
3203     // lookups will find it.
3204     MergeDC->makeDeclVisibleInContextImpl(New, /*Internal*/true);
3205   }
3206 }
3207 
3208 /// Find the declaration that should be merged into, given the declaration found
3209 /// by name lookup. If we're merging an anonymous declaration within a typedef,
3210 /// we need a matching typedef, and we merge with the type inside it.
3211 static NamedDecl *getDeclForMerging(NamedDecl *Found,
3212                                     bool IsTypedefNameForLinkage) {
3213   if (!IsTypedefNameForLinkage)
3214     return Found;
3215 
3216   // If we found a typedef declaration that gives a name to some other
3217   // declaration, then we want that inner declaration. Declarations from
3218   // AST files are handled via ImportedTypedefNamesForLinkage.
3219   if (Found->isFromASTFile())
3220     return nullptr;
3221 
3222   if (auto *TND = dyn_cast<TypedefNameDecl>(Found))
3223     return TND->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
3224 
3225   return nullptr;
3226 }
3227 
3228 /// Find the declaration to use to populate the anonymous declaration table
3229 /// for the given lexical DeclContext. We only care about finding local
3230 /// definitions of the context; we'll merge imported ones as we go.
3231 DeclContext *
3232 ASTDeclReader::getPrimaryDCForAnonymousDecl(DeclContext *LexicalDC) {
3233   // For classes, we track the definition as we merge.
3234   if (auto *RD = dyn_cast<CXXRecordDecl>(LexicalDC)) {
3235     auto *DD = RD->getCanonicalDecl()->DefinitionData;
3236     return DD ? DD->Definition : nullptr;
3237   }
3238 
3239   // For anything else, walk its merged redeclarations looking for a definition.
3240   // Note that we can't just call getDefinition here because the redeclaration
3241   // chain isn't wired up.
3242   for (auto *D : merged_redecls(cast<Decl>(LexicalDC))) {
3243     if (auto *FD = dyn_cast<FunctionDecl>(D))
3244       if (FD->isThisDeclarationADefinition())
3245         return FD;
3246     if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
3247       if (MD->isThisDeclarationADefinition())
3248         return MD;
3249   }
3250 
3251   // No merged definition yet.
3252   return nullptr;
3253 }
3254 
3255 NamedDecl *ASTDeclReader::getAnonymousDeclForMerging(ASTReader &Reader,
3256                                                      DeclContext *DC,
3257                                                      unsigned Index) {
3258   // If the lexical context has been merged, look into the now-canonical
3259   // definition.
3260   auto *CanonDC = cast<Decl>(DC)->getCanonicalDecl();
3261 
3262   // If we've seen this before, return the canonical declaration.
3263   auto &Previous = Reader.AnonymousDeclarationsForMerging[CanonDC];
3264   if (Index < Previous.size() && Previous[Index])
3265     return Previous[Index];
3266 
3267   // If this is the first time, but we have parsed a declaration of the context,
3268   // build the anonymous declaration list from the parsed declaration.
3269   auto *PrimaryDC = getPrimaryDCForAnonymousDecl(DC);
3270   if (PrimaryDC && !cast<Decl>(PrimaryDC)->isFromASTFile()) {
3271     numberAnonymousDeclsWithin(PrimaryDC, [&](NamedDecl *ND, unsigned Number) {
3272       if (Previous.size() == Number)
3273         Previous.push_back(cast<NamedDecl>(ND->getCanonicalDecl()));
3274       else
3275         Previous[Number] = cast<NamedDecl>(ND->getCanonicalDecl());
3276     });
3277   }
3278 
3279   return Index < Previous.size() ? Previous[Index] : nullptr;
3280 }
3281 
3282 void ASTDeclReader::setAnonymousDeclForMerging(ASTReader &Reader,
3283                                                DeclContext *DC, unsigned Index,
3284                                                NamedDecl *D) {
3285   auto *CanonDC = cast<Decl>(DC)->getCanonicalDecl();
3286 
3287   auto &Previous = Reader.AnonymousDeclarationsForMerging[CanonDC];
3288   if (Index >= Previous.size())
3289     Previous.resize(Index + 1);
3290   if (!Previous[Index])
3291     Previous[Index] = D;
3292 }
3293 
3294 ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) {
3295   DeclarationName Name = TypedefNameForLinkage ? TypedefNameForLinkage
3296                                                : D->getDeclName();
3297 
3298   if (!Name && !needsAnonymousDeclarationNumber(D)) {
3299     // Don't bother trying to find unnamed declarations that are in
3300     // unmergeable contexts.
3301     FindExistingResult Result(Reader, D, /*Existing=*/nullptr,
3302                               AnonymousDeclNumber, TypedefNameForLinkage);
3303     Result.suppress();
3304     return Result;
3305   }
3306 
3307   DeclContext *DC = D->getDeclContext()->getRedeclContext();
3308   if (TypedefNameForLinkage) {
3309     auto It = Reader.ImportedTypedefNamesForLinkage.find(
3310         std::make_pair(DC, TypedefNameForLinkage));
3311     if (It != Reader.ImportedTypedefNamesForLinkage.end())
3312       if (isSameEntity(It->second, D))
3313         return FindExistingResult(Reader, D, It->second, AnonymousDeclNumber,
3314                                   TypedefNameForLinkage);
3315     // Go on to check in other places in case an existing typedef name
3316     // was not imported.
3317   }
3318 
3319   if (needsAnonymousDeclarationNumber(D)) {
3320     // This is an anonymous declaration that we may need to merge. Look it up
3321     // in its context by number.
3322     if (auto *Existing = getAnonymousDeclForMerging(
3323             Reader, D->getLexicalDeclContext(), AnonymousDeclNumber))
3324       if (isSameEntity(Existing, D))
3325         return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3326                                   TypedefNameForLinkage);
3327   } else if (DC->isTranslationUnit() &&
3328              !Reader.getContext().getLangOpts().CPlusPlus) {
3329     IdentifierResolver &IdResolver = Reader.getIdResolver();
3330 
3331     // Temporarily consider the identifier to be up-to-date. We don't want to
3332     // cause additional lookups here.
3333     class UpToDateIdentifierRAII {
3334       IdentifierInfo *II;
3335       bool WasOutToDate = false;
3336 
3337     public:
3338       explicit UpToDateIdentifierRAII(IdentifierInfo *II) : II(II) {
3339         if (II) {
3340           WasOutToDate = II->isOutOfDate();
3341           if (WasOutToDate)
3342             II->setOutOfDate(false);
3343         }
3344       }
3345 
3346       ~UpToDateIdentifierRAII() {
3347         if (WasOutToDate)
3348           II->setOutOfDate(true);
3349       }
3350     } UpToDate(Name.getAsIdentifierInfo());
3351 
3352     for (IdentifierResolver::iterator I = IdResolver.begin(Name),
3353                                    IEnd = IdResolver.end();
3354          I != IEnd; ++I) {
3355       if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
3356         if (isSameEntity(Existing, D))
3357           return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3358                                     TypedefNameForLinkage);
3359     }
3360   } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
3361     DeclContext::lookup_result R = MergeDC->noload_lookup(Name);
3362     for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
3363       if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
3364         if (isSameEntity(Existing, D))
3365           return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3366                                     TypedefNameForLinkage);
3367     }
3368   } else {
3369     // Not in a mergeable context.
3370     return FindExistingResult(Reader);
3371   }
3372 
3373   // If this declaration is from a merged context, make a note that we need to
3374   // check that the canonical definition of that context contains the decl.
3375   //
3376   // FIXME: We should do something similar if we merge two definitions of the
3377   // same template specialization into the same CXXRecordDecl.
3378   auto MergedDCIt = Reader.MergedDeclContexts.find(D->getLexicalDeclContext());
3379   if (MergedDCIt != Reader.MergedDeclContexts.end() &&
3380       MergedDCIt->second == D->getDeclContext())
3381     Reader.PendingOdrMergeChecks.push_back(D);
3382 
3383   return FindExistingResult(Reader, D, /*Existing=*/nullptr,
3384                             AnonymousDeclNumber, TypedefNameForLinkage);
3385 }
3386 
3387 template<typename DeclT>
3388 Decl *ASTDeclReader::getMostRecentDeclImpl(Redeclarable<DeclT> *D) {
3389   return D->RedeclLink.getLatestNotUpdated();
3390 }
3391 
3392 Decl *ASTDeclReader::getMostRecentDeclImpl(...) {
3393   llvm_unreachable("getMostRecentDecl on non-redeclarable declaration");
3394 }
3395 
3396 Decl *ASTDeclReader::getMostRecentDecl(Decl *D) {
3397   assert(D);
3398 
3399   switch (D->getKind()) {
3400 #define ABSTRACT_DECL(TYPE)
3401 #define DECL(TYPE, BASE)                               \
3402   case Decl::TYPE:                                     \
3403     return getMostRecentDeclImpl(cast<TYPE##Decl>(D));
3404 #include "clang/AST/DeclNodes.inc"
3405   }
3406   llvm_unreachable("unknown decl kind");
3407 }
3408 
3409 Decl *ASTReader::getMostRecentExistingDecl(Decl *D) {
3410   return ASTDeclReader::getMostRecentDecl(D->getCanonicalDecl());
3411 }
3412 
3413 template<typename DeclT>
3414 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3415                                            Redeclarable<DeclT> *D,
3416                                            Decl *Previous, Decl *Canon) {
3417   D->RedeclLink.setPrevious(cast<DeclT>(Previous));
3418   D->First = cast<DeclT>(Previous)->First;
3419 }
3420 
3421 namespace clang {
3422 
3423 template<>
3424 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3425                                            Redeclarable<VarDecl> *D,
3426                                            Decl *Previous, Decl *Canon) {
3427   auto *VD = static_cast<VarDecl *>(D);
3428   auto *PrevVD = cast<VarDecl>(Previous);
3429   D->RedeclLink.setPrevious(PrevVD);
3430   D->First = PrevVD->First;
3431 
3432   // We should keep at most one definition on the chain.
3433   // FIXME: Cache the definition once we've found it. Building a chain with
3434   // N definitions currently takes O(N^2) time here.
3435   if (VD->isThisDeclarationADefinition() == VarDecl::Definition) {
3436     for (VarDecl *CurD = PrevVD; CurD; CurD = CurD->getPreviousDecl()) {
3437       if (CurD->isThisDeclarationADefinition() == VarDecl::Definition) {
3438         Reader.mergeDefinitionVisibility(CurD, VD);
3439         VD->demoteThisDefinitionToDeclaration();
3440         break;
3441       }
3442     }
3443   }
3444 }
3445 
3446 static bool isUndeducedReturnType(QualType T) {
3447   auto *DT = T->getContainedDeducedType();
3448   return DT && !DT->isDeduced();
3449 }
3450 
3451 template<>
3452 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3453                                            Redeclarable<FunctionDecl> *D,
3454                                            Decl *Previous, Decl *Canon) {
3455   auto *FD = static_cast<FunctionDecl *>(D);
3456   auto *PrevFD = cast<FunctionDecl>(Previous);
3457 
3458   FD->RedeclLink.setPrevious(PrevFD);
3459   FD->First = PrevFD->First;
3460 
3461   // If the previous declaration is an inline function declaration, then this
3462   // declaration is too.
3463   if (PrevFD->isInlined() != FD->isInlined()) {
3464     // FIXME: [dcl.fct.spec]p4:
3465     //   If a function with external linkage is declared inline in one
3466     //   translation unit, it shall be declared inline in all translation
3467     //   units in which it appears.
3468     //
3469     // Be careful of this case:
3470     //
3471     // module A:
3472     //   template<typename T> struct X { void f(); };
3473     //   template<typename T> inline void X<T>::f() {}
3474     //
3475     // module B instantiates the declaration of X<int>::f
3476     // module C instantiates the definition of X<int>::f
3477     //
3478     // If module B and C are merged, we do not have a violation of this rule.
3479     FD->setImplicitlyInline(true);
3480   }
3481 
3482   auto *FPT = FD->getType()->getAs<FunctionProtoType>();
3483   auto *PrevFPT = PrevFD->getType()->getAs<FunctionProtoType>();
3484   if (FPT && PrevFPT) {
3485     // If we need to propagate an exception specification along the redecl
3486     // chain, make a note of that so that we can do so later.
3487     bool IsUnresolved = isUnresolvedExceptionSpec(FPT->getExceptionSpecType());
3488     bool WasUnresolved =
3489         isUnresolvedExceptionSpec(PrevFPT->getExceptionSpecType());
3490     if (IsUnresolved != WasUnresolved)
3491       Reader.PendingExceptionSpecUpdates.insert(
3492           {Canon, IsUnresolved ? PrevFD : FD});
3493 
3494     // If we need to propagate a deduced return type along the redecl chain,
3495     // make a note of that so that we can do it later.
3496     bool IsUndeduced = isUndeducedReturnType(FPT->getReturnType());
3497     bool WasUndeduced = isUndeducedReturnType(PrevFPT->getReturnType());
3498     if (IsUndeduced != WasUndeduced)
3499       Reader.PendingDeducedTypeUpdates.insert(
3500           {cast<FunctionDecl>(Canon),
3501            (IsUndeduced ? PrevFPT : FPT)->getReturnType()});
3502   }
3503 }
3504 
3505 } // namespace clang
3506 
3507 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader, ...) {
3508   llvm_unreachable("attachPreviousDecl on non-redeclarable declaration");
3509 }
3510 
3511 /// Inherit the default template argument from \p From to \p To. Returns
3512 /// \c false if there is no default template for \p From.
3513 template <typename ParmDecl>
3514 static bool inheritDefaultTemplateArgument(ASTContext &Context, ParmDecl *From,
3515                                            Decl *ToD) {
3516   auto *To = cast<ParmDecl>(ToD);
3517   if (!From->hasDefaultArgument())
3518     return false;
3519   To->setInheritedDefaultArgument(Context, From);
3520   return true;
3521 }
3522 
3523 static void inheritDefaultTemplateArguments(ASTContext &Context,
3524                                             TemplateDecl *From,
3525                                             TemplateDecl *To) {
3526   auto *FromTP = From->getTemplateParameters();
3527   auto *ToTP = To->getTemplateParameters();
3528   assert(FromTP->size() == ToTP->size() && "merged mismatched templates?");
3529 
3530   for (unsigned I = 0, N = FromTP->size(); I != N; ++I) {
3531     NamedDecl *FromParam = FromTP->getParam(I);
3532     NamedDecl *ToParam = ToTP->getParam(I);
3533 
3534     if (auto *FTTP = dyn_cast<TemplateTypeParmDecl>(FromParam))
3535       inheritDefaultTemplateArgument(Context, FTTP, ToParam);
3536     else if (auto *FNTTP = dyn_cast<NonTypeTemplateParmDecl>(FromParam))
3537       inheritDefaultTemplateArgument(Context, FNTTP, ToParam);
3538     else
3539       inheritDefaultTemplateArgument(
3540               Context, cast<TemplateTemplateParmDecl>(FromParam), ToParam);
3541   }
3542 }
3543 
3544 void ASTDeclReader::attachPreviousDecl(ASTReader &Reader, Decl *D,
3545                                        Decl *Previous, Decl *Canon) {
3546   assert(D && Previous);
3547 
3548   switch (D->getKind()) {
3549 #define ABSTRACT_DECL(TYPE)
3550 #define DECL(TYPE, BASE)                                                  \
3551   case Decl::TYPE:                                                        \
3552     attachPreviousDeclImpl(Reader, cast<TYPE##Decl>(D), Previous, Canon); \
3553     break;
3554 #include "clang/AST/DeclNodes.inc"
3555   }
3556 
3557   // If the declaration was visible in one module, a redeclaration of it in
3558   // another module remains visible even if it wouldn't be visible by itself.
3559   //
3560   // FIXME: In this case, the declaration should only be visible if a module
3561   //        that makes it visible has been imported.
3562   D->IdentifierNamespace |=
3563       Previous->IdentifierNamespace &
3564       (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
3565 
3566   // If the declaration declares a template, it may inherit default arguments
3567   // from the previous declaration.
3568   if (auto *TD = dyn_cast<TemplateDecl>(D))
3569     inheritDefaultTemplateArguments(Reader.getContext(),
3570                                     cast<TemplateDecl>(Previous), TD);
3571 }
3572 
3573 template<typename DeclT>
3574 void ASTDeclReader::attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest) {
3575   D->RedeclLink.setLatest(cast<DeclT>(Latest));
3576 }
3577 
3578 void ASTDeclReader::attachLatestDeclImpl(...) {
3579   llvm_unreachable("attachLatestDecl on non-redeclarable declaration");
3580 }
3581 
3582 void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {
3583   assert(D && Latest);
3584 
3585   switch (D->getKind()) {
3586 #define ABSTRACT_DECL(TYPE)
3587 #define DECL(TYPE, BASE)                                  \
3588   case Decl::TYPE:                                        \
3589     attachLatestDeclImpl(cast<TYPE##Decl>(D), Latest); \
3590     break;
3591 #include "clang/AST/DeclNodes.inc"
3592   }
3593 }
3594 
3595 template<typename DeclT>
3596 void ASTDeclReader::markIncompleteDeclChainImpl(Redeclarable<DeclT> *D) {
3597   D->RedeclLink.markIncomplete();
3598 }
3599 
3600 void ASTDeclReader::markIncompleteDeclChainImpl(...) {
3601   llvm_unreachable("markIncompleteDeclChain on non-redeclarable declaration");
3602 }
3603 
3604 void ASTReader::markIncompleteDeclChain(Decl *D) {
3605   switch (D->getKind()) {
3606 #define ABSTRACT_DECL(TYPE)
3607 #define DECL(TYPE, BASE)                                             \
3608   case Decl::TYPE:                                                   \
3609     ASTDeclReader::markIncompleteDeclChainImpl(cast<TYPE##Decl>(D)); \
3610     break;
3611 #include "clang/AST/DeclNodes.inc"
3612   }
3613 }
3614 
3615 /// Read the declaration at the given offset from the AST file.
3616 Decl *ASTReader::ReadDeclRecord(DeclID ID) {
3617   unsigned Index = ID - NUM_PREDEF_DECL_IDS;
3618   SourceLocation DeclLoc;
3619   RecordLocation Loc = DeclCursorForID(ID, DeclLoc);
3620   llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
3621   // Keep track of where we are in the stream, then jump back there
3622   // after reading this declaration.
3623   SavedStreamPosition SavedPosition(DeclsCursor);
3624 
3625   ReadingKindTracker ReadingKind(Read_Decl, *this);
3626 
3627   // Note that we are loading a declaration record.
3628   Deserializing ADecl(this);
3629 
3630   DeclsCursor.JumpToBit(Loc.Offset);
3631   ASTRecordReader Record(*this, *Loc.F);
3632   ASTDeclReader Reader(*this, Record, Loc, ID, DeclLoc);
3633   unsigned Code = DeclsCursor.ReadCode();
3634 
3635   ASTContext &Context = getContext();
3636   Decl *D = nullptr;
3637   switch ((DeclCode)Record.readRecord(DeclsCursor, Code)) {
3638   case DECL_CONTEXT_LEXICAL:
3639   case DECL_CONTEXT_VISIBLE:
3640     llvm_unreachable("Record cannot be de-serialized with ReadDeclRecord");
3641   case DECL_TYPEDEF:
3642     D = TypedefDecl::CreateDeserialized(Context, ID);
3643     break;
3644   case DECL_TYPEALIAS:
3645     D = TypeAliasDecl::CreateDeserialized(Context, ID);
3646     break;
3647   case DECL_ENUM:
3648     D = EnumDecl::CreateDeserialized(Context, ID);
3649     break;
3650   case DECL_RECORD:
3651     D = RecordDecl::CreateDeserialized(Context, ID);
3652     break;
3653   case DECL_ENUM_CONSTANT:
3654     D = EnumConstantDecl::CreateDeserialized(Context, ID);
3655     break;
3656   case DECL_FUNCTION:
3657     D = FunctionDecl::CreateDeserialized(Context, ID);
3658     break;
3659   case DECL_LINKAGE_SPEC:
3660     D = LinkageSpecDecl::CreateDeserialized(Context, ID);
3661     break;
3662   case DECL_EXPORT:
3663     D = ExportDecl::CreateDeserialized(Context, ID);
3664     break;
3665   case DECL_LABEL:
3666     D = LabelDecl::CreateDeserialized(Context, ID);
3667     break;
3668   case DECL_NAMESPACE:
3669     D = NamespaceDecl::CreateDeserialized(Context, ID);
3670     break;
3671   case DECL_NAMESPACE_ALIAS:
3672     D = NamespaceAliasDecl::CreateDeserialized(Context, ID);
3673     break;
3674   case DECL_USING:
3675     D = UsingDecl::CreateDeserialized(Context, ID);
3676     break;
3677   case DECL_USING_PACK:
3678     D = UsingPackDecl::CreateDeserialized(Context, ID, Record.readInt());
3679     break;
3680   case DECL_USING_SHADOW:
3681     D = UsingShadowDecl::CreateDeserialized(Context, ID);
3682     break;
3683   case DECL_CONSTRUCTOR_USING_SHADOW:
3684     D = ConstructorUsingShadowDecl::CreateDeserialized(Context, ID);
3685     break;
3686   case DECL_USING_DIRECTIVE:
3687     D = UsingDirectiveDecl::CreateDeserialized(Context, ID);
3688     break;
3689   case DECL_UNRESOLVED_USING_VALUE:
3690     D = UnresolvedUsingValueDecl::CreateDeserialized(Context, ID);
3691     break;
3692   case DECL_UNRESOLVED_USING_TYPENAME:
3693     D = UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID);
3694     break;
3695   case DECL_CXX_RECORD:
3696     D = CXXRecordDecl::CreateDeserialized(Context, ID);
3697     break;
3698   case DECL_CXX_DEDUCTION_GUIDE:
3699     D = CXXDeductionGuideDecl::CreateDeserialized(Context, ID);
3700     break;
3701   case DECL_CXX_METHOD:
3702     D = CXXMethodDecl::CreateDeserialized(Context, ID);
3703     break;
3704   case DECL_CXX_CONSTRUCTOR:
3705     D = CXXConstructorDecl::CreateDeserialized(Context, ID, false);
3706     break;
3707   case DECL_CXX_INHERITED_CONSTRUCTOR:
3708     D = CXXConstructorDecl::CreateDeserialized(Context, ID, true);
3709     break;
3710   case DECL_CXX_DESTRUCTOR:
3711     D = CXXDestructorDecl::CreateDeserialized(Context, ID);
3712     break;
3713   case DECL_CXX_CONVERSION:
3714     D = CXXConversionDecl::CreateDeserialized(Context, ID);
3715     break;
3716   case DECL_ACCESS_SPEC:
3717     D = AccessSpecDecl::CreateDeserialized(Context, ID);
3718     break;
3719   case DECL_FRIEND:
3720     D = FriendDecl::CreateDeserialized(Context, ID, Record.readInt());
3721     break;
3722   case DECL_FRIEND_TEMPLATE:
3723     D = FriendTemplateDecl::CreateDeserialized(Context, ID);
3724     break;
3725   case DECL_CLASS_TEMPLATE:
3726     D = ClassTemplateDecl::CreateDeserialized(Context, ID);
3727     break;
3728   case DECL_CLASS_TEMPLATE_SPECIALIZATION:
3729     D = ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3730     break;
3731   case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
3732     D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3733     break;
3734   case DECL_VAR_TEMPLATE:
3735     D = VarTemplateDecl::CreateDeserialized(Context, ID);
3736     break;
3737   case DECL_VAR_TEMPLATE_SPECIALIZATION:
3738     D = VarTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3739     break;
3740   case DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION:
3741     D = VarTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3742     break;
3743   case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
3744     D = ClassScopeFunctionSpecializationDecl::CreateDeserialized(Context, ID);
3745     break;
3746   case DECL_FUNCTION_TEMPLATE:
3747     D = FunctionTemplateDecl::CreateDeserialized(Context, ID);
3748     break;
3749   case DECL_TEMPLATE_TYPE_PARM:
3750     D = TemplateTypeParmDecl::CreateDeserialized(Context, ID);
3751     break;
3752   case DECL_NON_TYPE_TEMPLATE_PARM:
3753     D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID);
3754     break;
3755   case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK:
3756     D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID,
3757                                                     Record.readInt());
3758     break;
3759   case DECL_TEMPLATE_TEMPLATE_PARM:
3760     D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID);
3761     break;
3762   case DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK:
3763     D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID,
3764                                                      Record.readInt());
3765     break;
3766   case DECL_TYPE_ALIAS_TEMPLATE:
3767     D = TypeAliasTemplateDecl::CreateDeserialized(Context, ID);
3768     break;
3769   case DECL_STATIC_ASSERT:
3770     D = StaticAssertDecl::CreateDeserialized(Context, ID);
3771     break;
3772   case DECL_OBJC_METHOD:
3773     D = ObjCMethodDecl::CreateDeserialized(Context, ID);
3774     break;
3775   case DECL_OBJC_INTERFACE:
3776     D = ObjCInterfaceDecl::CreateDeserialized(Context, ID);
3777     break;
3778   case DECL_OBJC_IVAR:
3779     D = ObjCIvarDecl::CreateDeserialized(Context, ID);
3780     break;
3781   case DECL_OBJC_PROTOCOL:
3782     D = ObjCProtocolDecl::CreateDeserialized(Context, ID);
3783     break;
3784   case DECL_OBJC_AT_DEFS_FIELD:
3785     D = ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID);
3786     break;
3787   case DECL_OBJC_CATEGORY:
3788     D = ObjCCategoryDecl::CreateDeserialized(Context, ID);
3789     break;
3790   case DECL_OBJC_CATEGORY_IMPL:
3791     D = ObjCCategoryImplDecl::CreateDeserialized(Context, ID);
3792     break;
3793   case DECL_OBJC_IMPLEMENTATION:
3794     D = ObjCImplementationDecl::CreateDeserialized(Context, ID);
3795     break;
3796   case DECL_OBJC_COMPATIBLE_ALIAS:
3797     D = ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID);
3798     break;
3799   case DECL_OBJC_PROPERTY:
3800     D = ObjCPropertyDecl::CreateDeserialized(Context, ID);
3801     break;
3802   case DECL_OBJC_PROPERTY_IMPL:
3803     D = ObjCPropertyImplDecl::CreateDeserialized(Context, ID);
3804     break;
3805   case DECL_FIELD:
3806     D = FieldDecl::CreateDeserialized(Context, ID);
3807     break;
3808   case DECL_INDIRECTFIELD:
3809     D = IndirectFieldDecl::CreateDeserialized(Context, ID);
3810     break;
3811   case DECL_VAR:
3812     D = VarDecl::CreateDeserialized(Context, ID);
3813     break;
3814   case DECL_IMPLICIT_PARAM:
3815     D = ImplicitParamDecl::CreateDeserialized(Context, ID);
3816     break;
3817   case DECL_PARM_VAR:
3818     D = ParmVarDecl::CreateDeserialized(Context, ID);
3819     break;
3820   case DECL_DECOMPOSITION:
3821     D = DecompositionDecl::CreateDeserialized(Context, ID, Record.readInt());
3822     break;
3823   case DECL_BINDING:
3824     D = BindingDecl::CreateDeserialized(Context, ID);
3825     break;
3826   case DECL_FILE_SCOPE_ASM:
3827     D = FileScopeAsmDecl::CreateDeserialized(Context, ID);
3828     break;
3829   case DECL_BLOCK:
3830     D = BlockDecl::CreateDeserialized(Context, ID);
3831     break;
3832   case DECL_MS_PROPERTY:
3833     D = MSPropertyDecl::CreateDeserialized(Context, ID);
3834     break;
3835   case DECL_CAPTURED:
3836     D = CapturedDecl::CreateDeserialized(Context, ID, Record.readInt());
3837     break;
3838   case DECL_CXX_BASE_SPECIFIERS:
3839     Error("attempt to read a C++ base-specifier record as a declaration");
3840     return nullptr;
3841   case DECL_CXX_CTOR_INITIALIZERS:
3842     Error("attempt to read a C++ ctor initializer record as a declaration");
3843     return nullptr;
3844   case DECL_IMPORT:
3845     // Note: last entry of the ImportDecl record is the number of stored source
3846     // locations.
3847     D = ImportDecl::CreateDeserialized(Context, ID, Record.back());
3848     break;
3849   case DECL_OMP_THREADPRIVATE:
3850     D = OMPThreadPrivateDecl::CreateDeserialized(Context, ID, Record.readInt());
3851     break;
3852   case DECL_OMP_REQUIRES:
3853     D = OMPRequiresDecl::CreateDeserialized(Context, ID, Record.readInt());
3854     break;
3855   case DECL_OMP_DECLARE_REDUCTION:
3856     D = OMPDeclareReductionDecl::CreateDeserialized(Context, ID);
3857     break;
3858   case DECL_OMP_CAPTUREDEXPR:
3859     D = OMPCapturedExprDecl::CreateDeserialized(Context, ID);
3860     break;
3861   case DECL_PRAGMA_COMMENT:
3862     D = PragmaCommentDecl::CreateDeserialized(Context, ID, Record.readInt());
3863     break;
3864   case DECL_PRAGMA_DETECT_MISMATCH:
3865     D = PragmaDetectMismatchDecl::CreateDeserialized(Context, ID,
3866                                                      Record.readInt());
3867     break;
3868   case DECL_EMPTY:
3869     D = EmptyDecl::CreateDeserialized(Context, ID);
3870     break;
3871   case DECL_OBJC_TYPE_PARAM:
3872     D = ObjCTypeParamDecl::CreateDeserialized(Context, ID);
3873     break;
3874   }
3875 
3876   assert(D && "Unknown declaration reading AST file");
3877   LoadedDecl(Index, D);
3878   // Set the DeclContext before doing any deserialization, to make sure internal
3879   // calls to Decl::getASTContext() by Decl's methods will find the
3880   // TranslationUnitDecl without crashing.
3881   D->setDeclContext(Context.getTranslationUnitDecl());
3882   Reader.Visit(D);
3883 
3884   // If this declaration is also a declaration context, get the
3885   // offsets for its tables of lexical and visible declarations.
3886   if (auto *DC = dyn_cast<DeclContext>(D)) {
3887     std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
3888     if (Offsets.first &&
3889         ReadLexicalDeclContextStorage(*Loc.F, DeclsCursor, Offsets.first, DC))
3890       return nullptr;
3891     if (Offsets.second &&
3892         ReadVisibleDeclContextStorage(*Loc.F, DeclsCursor, Offsets.second, ID))
3893       return nullptr;
3894   }
3895   assert(Record.getIdx() == Record.size());
3896 
3897   // Load any relevant update records.
3898   PendingUpdateRecords.push_back(
3899       PendingUpdateRecord(ID, D, /*JustLoaded=*/true));
3900 
3901   // Load the categories after recursive loading is finished.
3902   if (auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
3903     // If we already have a definition when deserializing the ObjCInterfaceDecl,
3904     // we put the Decl in PendingDefinitions so we can pull the categories here.
3905     if (Class->isThisDeclarationADefinition() ||
3906         PendingDefinitions.count(Class))
3907       loadObjCCategories(ID, Class);
3908 
3909   // If we have deserialized a declaration that has a definition the
3910   // AST consumer might need to know about, queue it.
3911   // We don't pass it to the consumer immediately because we may be in recursive
3912   // loading, and some declarations may still be initializing.
3913   PotentiallyInterestingDecls.push_back(
3914       InterestingDecl(D, Reader.hasPendingBody()));
3915 
3916   return D;
3917 }
3918 
3919 void ASTReader::PassInterestingDeclsToConsumer() {
3920   assert(Consumer);
3921 
3922   if (PassingDeclsToConsumer)
3923     return;
3924 
3925   // Guard variable to avoid recursively redoing the process of passing
3926   // decls to consumer.
3927   SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
3928                                                    true);
3929 
3930   // Ensure that we've loaded all potentially-interesting declarations
3931   // that need to be eagerly loaded.
3932   for (auto ID : EagerlyDeserializedDecls)
3933     GetDecl(ID);
3934   EagerlyDeserializedDecls.clear();
3935 
3936   while (!PotentiallyInterestingDecls.empty()) {
3937     InterestingDecl D = PotentiallyInterestingDecls.front();
3938     PotentiallyInterestingDecls.pop_front();
3939     if (isConsumerInterestedIn(getContext(), D.getDecl(), D.hasPendingBody()))
3940       PassInterestingDeclToConsumer(D.getDecl());
3941   }
3942 }
3943 
3944 void ASTReader::loadDeclUpdateRecords(PendingUpdateRecord &Record) {
3945   // The declaration may have been modified by files later in the chain.
3946   // If this is the case, read the record containing the updates from each file
3947   // and pass it to ASTDeclReader to make the modifications.
3948   serialization::GlobalDeclID ID = Record.ID;
3949   Decl *D = Record.D;
3950   ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
3951   DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
3952 
3953   SmallVector<serialization::DeclID, 8> PendingLazySpecializationIDs;
3954 
3955   if (UpdI != DeclUpdateOffsets.end()) {
3956     auto UpdateOffsets = std::move(UpdI->second);
3957     DeclUpdateOffsets.erase(UpdI);
3958 
3959     // Check if this decl was interesting to the consumer. If we just loaded
3960     // the declaration, then we know it was interesting and we skip the call
3961     // to isConsumerInterestedIn because it is unsafe to call in the
3962     // current ASTReader state.
3963     bool WasInteresting =
3964         Record.JustLoaded || isConsumerInterestedIn(getContext(), D, false);
3965     for (auto &FileAndOffset : UpdateOffsets) {
3966       ModuleFile *F = FileAndOffset.first;
3967       uint64_t Offset = FileAndOffset.second;
3968       llvm::BitstreamCursor &Cursor = F->DeclsCursor;
3969       SavedStreamPosition SavedPosition(Cursor);
3970       Cursor.JumpToBit(Offset);
3971       unsigned Code = Cursor.ReadCode();
3972       ASTRecordReader Record(*this, *F);
3973       unsigned RecCode = Record.readRecord(Cursor, Code);
3974       (void)RecCode;
3975       assert(RecCode == DECL_UPDATES && "Expected DECL_UPDATES record!");
3976 
3977       ASTDeclReader Reader(*this, Record, RecordLocation(F, Offset), ID,
3978                            SourceLocation());
3979       Reader.UpdateDecl(D, PendingLazySpecializationIDs);
3980 
3981       // We might have made this declaration interesting. If so, remember that
3982       // we need to hand it off to the consumer.
3983       if (!WasInteresting &&
3984           isConsumerInterestedIn(getContext(), D, Reader.hasPendingBody())) {
3985         PotentiallyInterestingDecls.push_back(
3986             InterestingDecl(D, Reader.hasPendingBody()));
3987         WasInteresting = true;
3988       }
3989     }
3990   }
3991   // Add the lazy specializations to the template.
3992   assert((PendingLazySpecializationIDs.empty() || isa<ClassTemplateDecl>(D) ||
3993           isa<FunctionTemplateDecl>(D) || isa<VarTemplateDecl>(D)) &&
3994          "Must not have pending specializations");
3995   if (auto *CTD = dyn_cast<ClassTemplateDecl>(D))
3996     ASTDeclReader::AddLazySpecializations(CTD, PendingLazySpecializationIDs);
3997   else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
3998     ASTDeclReader::AddLazySpecializations(FTD, PendingLazySpecializationIDs);
3999   else if (auto *VTD = dyn_cast<VarTemplateDecl>(D))
4000     ASTDeclReader::AddLazySpecializations(VTD, PendingLazySpecializationIDs);
4001   PendingLazySpecializationIDs.clear();
4002 
4003   // Load the pending visible updates for this decl context, if it has any.
4004   auto I = PendingVisibleUpdates.find(ID);
4005   if (I != PendingVisibleUpdates.end()) {
4006     auto VisibleUpdates = std::move(I->second);
4007     PendingVisibleUpdates.erase(I);
4008 
4009     auto *DC = cast<DeclContext>(D)->getPrimaryContext();
4010     for (const auto &Update : VisibleUpdates)
4011       Lookups[DC].Table.add(
4012           Update.Mod, Update.Data,
4013           reader::ASTDeclContextNameLookupTrait(*this, *Update.Mod));
4014     DC->setHasExternalVisibleStorage(true);
4015   }
4016 }
4017 
4018 void ASTReader::loadPendingDeclChain(Decl *FirstLocal, uint64_t LocalOffset) {
4019   // Attach FirstLocal to the end of the decl chain.
4020   Decl *CanonDecl = FirstLocal->getCanonicalDecl();
4021   if (FirstLocal != CanonDecl) {
4022     Decl *PrevMostRecent = ASTDeclReader::getMostRecentDecl(CanonDecl);
4023     ASTDeclReader::attachPreviousDecl(
4024         *this, FirstLocal, PrevMostRecent ? PrevMostRecent : CanonDecl,
4025         CanonDecl);
4026   }
4027 
4028   if (!LocalOffset) {
4029     ASTDeclReader::attachLatestDecl(CanonDecl, FirstLocal);
4030     return;
4031   }
4032 
4033   // Load the list of other redeclarations from this module file.
4034   ModuleFile *M = getOwningModuleFile(FirstLocal);
4035   assert(M && "imported decl from no module file");
4036 
4037   llvm::BitstreamCursor &Cursor = M->DeclsCursor;
4038   SavedStreamPosition SavedPosition(Cursor);
4039   Cursor.JumpToBit(LocalOffset);
4040 
4041   RecordData Record;
4042   unsigned Code = Cursor.ReadCode();
4043   unsigned RecCode = Cursor.readRecord(Code, Record);
4044   (void)RecCode;
4045   assert(RecCode == LOCAL_REDECLARATIONS && "expected LOCAL_REDECLARATIONS record!");
4046 
4047   // FIXME: We have several different dispatches on decl kind here; maybe
4048   // we should instead generate one loop per kind and dispatch up-front?
4049   Decl *MostRecent = FirstLocal;
4050   for (unsigned I = 0, N = Record.size(); I != N; ++I) {
4051     auto *D = GetLocalDecl(*M, Record[N - I - 1]);
4052     ASTDeclReader::attachPreviousDecl(*this, D, MostRecent, CanonDecl);
4053     MostRecent = D;
4054   }
4055   ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent);
4056 }
4057 
4058 namespace {
4059 
4060   /// Given an ObjC interface, goes through the modules and links to the
4061   /// interface all the categories for it.
4062   class ObjCCategoriesVisitor {
4063     ASTReader &Reader;
4064     ObjCInterfaceDecl *Interface;
4065     llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized;
4066     ObjCCategoryDecl *Tail = nullptr;
4067     llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
4068     serialization::GlobalDeclID InterfaceID;
4069     unsigned PreviousGeneration;
4070 
4071     void add(ObjCCategoryDecl *Cat) {
4072       // Only process each category once.
4073       if (!Deserialized.erase(Cat))
4074         return;
4075 
4076       // Check for duplicate categories.
4077       if (Cat->getDeclName()) {
4078         ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
4079         if (Existing &&
4080             Reader.getOwningModuleFile(Existing)
4081                                           != Reader.getOwningModuleFile(Cat)) {
4082           // FIXME: We should not warn for duplicates in diamond:
4083           //
4084           //   MT     //
4085           //  /  \    //
4086           // ML  MR   //
4087           //  \  /    //
4088           //   MB     //
4089           //
4090           // If there are duplicates in ML/MR, there will be warning when
4091           // creating MB *and* when importing MB. We should not warn when
4092           // importing.
4093           Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
4094             << Interface->getDeclName() << Cat->getDeclName();
4095           Reader.Diag(Existing->getLocation(), diag::note_previous_definition);
4096         } else if (!Existing) {
4097           // Record this category.
4098           Existing = Cat;
4099         }
4100       }
4101 
4102       // Add this category to the end of the chain.
4103       if (Tail)
4104         ASTDeclReader::setNextObjCCategory(Tail, Cat);
4105       else
4106         Interface->setCategoryListRaw(Cat);
4107       Tail = Cat;
4108     }
4109 
4110   public:
4111     ObjCCategoriesVisitor(ASTReader &Reader,
4112                           ObjCInterfaceDecl *Interface,
4113                           llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized,
4114                           serialization::GlobalDeclID InterfaceID,
4115                           unsigned PreviousGeneration)
4116         : Reader(Reader), Interface(Interface), Deserialized(Deserialized),
4117           InterfaceID(InterfaceID), PreviousGeneration(PreviousGeneration) {
4118       // Populate the name -> category map with the set of known categories.
4119       for (auto *Cat : Interface->known_categories()) {
4120         if (Cat->getDeclName())
4121           NameCategoryMap[Cat->getDeclName()] = Cat;
4122 
4123         // Keep track of the tail of the category list.
4124         Tail = Cat;
4125       }
4126     }
4127 
4128     bool operator()(ModuleFile &M) {
4129       // If we've loaded all of the category information we care about from
4130       // this module file, we're done.
4131       if (M.Generation <= PreviousGeneration)
4132         return true;
4133 
4134       // Map global ID of the definition down to the local ID used in this
4135       // module file. If there is no such mapping, we'll find nothing here
4136       // (or in any module it imports).
4137       DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID);
4138       if (!LocalID)
4139         return true;
4140 
4141       // Perform a binary search to find the local redeclarations for this
4142       // declaration (if any).
4143       const ObjCCategoriesInfo Compare = { LocalID, 0 };
4144       const ObjCCategoriesInfo *Result
4145         = std::lower_bound(M.ObjCCategoriesMap,
4146                            M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap,
4147                            Compare);
4148       if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap ||
4149           Result->DefinitionID != LocalID) {
4150         // We didn't find anything. If the class definition is in this module
4151         // file, then the module files it depends on cannot have any categories,
4152         // so suppress further lookup.
4153         return Reader.isDeclIDFromModule(InterfaceID, M);
4154       }
4155 
4156       // We found something. Dig out all of the categories.
4157       unsigned Offset = Result->Offset;
4158       unsigned N = M.ObjCCategories[Offset];
4159       M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again
4160       for (unsigned I = 0; I != N; ++I)
4161         add(cast_or_null<ObjCCategoryDecl>(
4162               Reader.GetLocalDecl(M, M.ObjCCategories[Offset++])));
4163       return true;
4164     }
4165   };
4166 
4167 } // namespace
4168 
4169 void ASTReader::loadObjCCategories(serialization::GlobalDeclID ID,
4170                                    ObjCInterfaceDecl *D,
4171                                    unsigned PreviousGeneration) {
4172   ObjCCategoriesVisitor Visitor(*this, D, CategoriesDeserialized, ID,
4173                                 PreviousGeneration);
4174   ModuleMgr.visit(Visitor);
4175 }
4176 
4177 template<typename DeclT, typename Fn>
4178 static void forAllLaterRedecls(DeclT *D, Fn F) {
4179   F(D);
4180 
4181   // Check whether we've already merged D into its redeclaration chain.
4182   // MostRecent may or may not be nullptr if D has not been merged. If
4183   // not, walk the merged redecl chain and see if it's there.
4184   auto *MostRecent = D->getMostRecentDecl();
4185   bool Found = false;
4186   for (auto *Redecl = MostRecent; Redecl && !Found;
4187        Redecl = Redecl->getPreviousDecl())
4188     Found = (Redecl == D);
4189 
4190   // If this declaration is merged, apply the functor to all later decls.
4191   if (Found) {
4192     for (auto *Redecl = MostRecent; Redecl != D;
4193          Redecl = Redecl->getPreviousDecl())
4194       F(Redecl);
4195   }
4196 }
4197 
4198 void ASTDeclReader::UpdateDecl(Decl *D,
4199    llvm::SmallVectorImpl<serialization::DeclID> &PendingLazySpecializationIDs) {
4200   while (Record.getIdx() < Record.size()) {
4201     switch ((DeclUpdateKind)Record.readInt()) {
4202     case UPD_CXX_ADDED_IMPLICIT_MEMBER: {
4203       auto *RD = cast<CXXRecordDecl>(D);
4204       // FIXME: If we also have an update record for instantiating the
4205       // definition of D, we need that to happen before we get here.
4206       Decl *MD = Record.readDecl();
4207       assert(MD && "couldn't read decl from update record");
4208       // FIXME: We should call addHiddenDecl instead, to add the member
4209       // to its DeclContext.
4210       RD->addedMember(MD);
4211       break;
4212     }
4213 
4214     case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4215       // It will be added to the template's lazy specialization set.
4216       PendingLazySpecializationIDs.push_back(ReadDeclID());
4217       break;
4218 
4219     case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
4220       auto *Anon = ReadDeclAs<NamespaceDecl>();
4221 
4222       // Each module has its own anonymous namespace, which is disjoint from
4223       // any other module's anonymous namespaces, so don't attach the anonymous
4224       // namespace at all.
4225       if (!Record.isModule()) {
4226         if (auto *TU = dyn_cast<TranslationUnitDecl>(D))
4227           TU->setAnonymousNamespace(Anon);
4228         else
4229           cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon);
4230       }
4231       break;
4232     }
4233 
4234     case UPD_CXX_ADDED_VAR_DEFINITION: {
4235       auto *VD = cast<VarDecl>(D);
4236       VD->NonParmVarDeclBits.IsInline = Record.readInt();
4237       VD->NonParmVarDeclBits.IsInlineSpecified = Record.readInt();
4238       uint64_t Val = Record.readInt();
4239       if (Val && !VD->getInit()) {
4240         VD->setInit(Record.readExpr());
4241         if (Val > 1) { // IsInitKnownICE = 1, IsInitNotICE = 2, IsInitICE = 3
4242           EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
4243           Eval->CheckedICE = true;
4244           Eval->IsICE = Val == 3;
4245         }
4246       }
4247       break;
4248     }
4249 
4250     case UPD_CXX_POINT_OF_INSTANTIATION: {
4251       SourceLocation POI = Record.readSourceLocation();
4252       if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
4253         VTSD->setPointOfInstantiation(POI);
4254       } else if (auto *VD = dyn_cast<VarDecl>(D)) {
4255         VD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
4256       } else {
4257         auto *FD = cast<FunctionDecl>(D);
4258         if (auto *FTSInfo = FD->TemplateOrSpecialization
4259                     .dyn_cast<FunctionTemplateSpecializationInfo *>())
4260           FTSInfo->setPointOfInstantiation(POI);
4261         else
4262           FD->TemplateOrSpecialization.get<MemberSpecializationInfo *>()
4263               ->setPointOfInstantiation(POI);
4264       }
4265       break;
4266     }
4267 
4268     case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT: {
4269       auto *Param = cast<ParmVarDecl>(D);
4270 
4271       // We have to read the default argument regardless of whether we use it
4272       // so that hypothetical further update records aren't messed up.
4273       // TODO: Add a function to skip over the next expr record.
4274       auto *DefaultArg = Record.readExpr();
4275 
4276       // Only apply the update if the parameter still has an uninstantiated
4277       // default argument.
4278       if (Param->hasUninstantiatedDefaultArg())
4279         Param->setDefaultArg(DefaultArg);
4280       break;
4281     }
4282 
4283     case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER: {
4284       auto *FD = cast<FieldDecl>(D);
4285       auto *DefaultInit = Record.readExpr();
4286 
4287       // Only apply the update if the field still has an uninstantiated
4288       // default member initializer.
4289       if (FD->hasInClassInitializer() && !FD->getInClassInitializer()) {
4290         if (DefaultInit)
4291           FD->setInClassInitializer(DefaultInit);
4292         else
4293           // Instantiation failed. We can get here if we serialized an AST for
4294           // an invalid program.
4295           FD->removeInClassInitializer();
4296       }
4297       break;
4298     }
4299 
4300     case UPD_CXX_ADDED_FUNCTION_DEFINITION: {
4301       auto *FD = cast<FunctionDecl>(D);
4302       if (Reader.PendingBodies[FD]) {
4303         // FIXME: Maybe check for ODR violations.
4304         // It's safe to stop now because this update record is always last.
4305         return;
4306       }
4307 
4308       if (Record.readInt()) {
4309         // Maintain AST consistency: any later redeclarations of this function
4310         // are inline if this one is. (We might have merged another declaration
4311         // into this one.)
4312         forAllLaterRedecls(FD, [](FunctionDecl *FD) {
4313           FD->setImplicitlyInline();
4314         });
4315       }
4316       FD->setInnerLocStart(ReadSourceLocation());
4317       ReadFunctionDefinition(FD);
4318       assert(Record.getIdx() == Record.size() && "lazy body must be last");
4319       break;
4320     }
4321 
4322     case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4323       auto *RD = cast<CXXRecordDecl>(D);
4324       auto *OldDD = RD->getCanonicalDecl()->DefinitionData;
4325       bool HadRealDefinition =
4326           OldDD && (OldDD->Definition != RD ||
4327                     !Reader.PendingFakeDefinitionData.count(OldDD));
4328       RD->setParamDestroyedInCallee(Record.readInt());
4329       RD->setArgPassingRestrictions(
4330           (RecordDecl::ArgPassingKind)Record.readInt());
4331       ReadCXXRecordDefinition(RD, /*Update*/true);
4332 
4333       // Visible update is handled separately.
4334       uint64_t LexicalOffset = ReadLocalOffset();
4335       if (!HadRealDefinition && LexicalOffset) {
4336         Record.readLexicalDeclContextStorage(LexicalOffset, RD);
4337         Reader.PendingFakeDefinitionData.erase(OldDD);
4338       }
4339 
4340       auto TSK = (TemplateSpecializationKind)Record.readInt();
4341       SourceLocation POI = ReadSourceLocation();
4342       if (MemberSpecializationInfo *MSInfo =
4343               RD->getMemberSpecializationInfo()) {
4344         MSInfo->setTemplateSpecializationKind(TSK);
4345         MSInfo->setPointOfInstantiation(POI);
4346       } else {
4347         auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4348         Spec->setTemplateSpecializationKind(TSK);
4349         Spec->setPointOfInstantiation(POI);
4350 
4351         if (Record.readInt()) {
4352           auto *PartialSpec =
4353               ReadDeclAs<ClassTemplatePartialSpecializationDecl>();
4354           SmallVector<TemplateArgument, 8> TemplArgs;
4355           Record.readTemplateArgumentList(TemplArgs);
4356           auto *TemplArgList = TemplateArgumentList::CreateCopy(
4357               Reader.getContext(), TemplArgs);
4358 
4359           // FIXME: If we already have a partial specialization set,
4360           // check that it matches.
4361           if (!Spec->getSpecializedTemplateOrPartial()
4362                    .is<ClassTemplatePartialSpecializationDecl *>())
4363             Spec->setInstantiationOf(PartialSpec, TemplArgList);
4364         }
4365       }
4366 
4367       RD->setTagKind((TagTypeKind)Record.readInt());
4368       RD->setLocation(ReadSourceLocation());
4369       RD->setLocStart(ReadSourceLocation());
4370       RD->setBraceRange(ReadSourceRange());
4371 
4372       if (Record.readInt()) {
4373         AttrVec Attrs;
4374         Record.readAttributes(Attrs);
4375         // If the declaration already has attributes, we assume that some other
4376         // AST file already loaded them.
4377         if (!D->hasAttrs())
4378           D->setAttrsImpl(Attrs, Reader.getContext());
4379       }
4380       break;
4381     }
4382 
4383     case UPD_CXX_RESOLVED_DTOR_DELETE: {
4384       // Set the 'operator delete' directly to avoid emitting another update
4385       // record.
4386       auto *Del = ReadDeclAs<FunctionDecl>();
4387       auto *First = cast<CXXDestructorDecl>(D->getCanonicalDecl());
4388       auto *ThisArg = Record.readExpr();
4389       // FIXME: Check consistency if we have an old and new operator delete.
4390       if (!First->OperatorDelete) {
4391         First->OperatorDelete = Del;
4392         First->OperatorDeleteThisArg = ThisArg;
4393       }
4394       break;
4395     }
4396 
4397     case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {
4398       FunctionProtoType::ExceptionSpecInfo ESI;
4399       SmallVector<QualType, 8> ExceptionStorage;
4400       Record.readExceptionSpec(ExceptionStorage, ESI);
4401 
4402       // Update this declaration's exception specification, if needed.
4403       auto *FD = cast<FunctionDecl>(D);
4404       auto *FPT = FD->getType()->castAs<FunctionProtoType>();
4405       // FIXME: If the exception specification is already present, check that it
4406       // matches.
4407       if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
4408         FD->setType(Reader.getContext().getFunctionType(
4409             FPT->getReturnType(), FPT->getParamTypes(),
4410             FPT->getExtProtoInfo().withExceptionSpec(ESI)));
4411 
4412         // When we get to the end of deserializing, see if there are other decls
4413         // that we need to propagate this exception specification onto.
4414         Reader.PendingExceptionSpecUpdates.insert(
4415             std::make_pair(FD->getCanonicalDecl(), FD));
4416       }
4417       break;
4418     }
4419 
4420     case UPD_CXX_DEDUCED_RETURN_TYPE: {
4421       auto *FD = cast<FunctionDecl>(D);
4422       QualType DeducedResultType = Record.readType();
4423       Reader.PendingDeducedTypeUpdates.insert(
4424           {FD->getCanonicalDecl(), DeducedResultType});
4425       break;
4426     }
4427 
4428     case UPD_DECL_MARKED_USED:
4429       // Maintain AST consistency: any later redeclarations are used too.
4430       D->markUsed(Reader.getContext());
4431       break;
4432 
4433     case UPD_MANGLING_NUMBER:
4434       Reader.getContext().setManglingNumber(cast<NamedDecl>(D),
4435                                             Record.readInt());
4436       break;
4437 
4438     case UPD_STATIC_LOCAL_NUMBER:
4439       Reader.getContext().setStaticLocalNumber(cast<VarDecl>(D),
4440                                                Record.readInt());
4441       break;
4442 
4443     case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
4444       D->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(Reader.getContext(),
4445                                                           ReadSourceRange()));
4446       break;
4447 
4448     case UPD_DECL_EXPORTED: {
4449       unsigned SubmoduleID = readSubmoduleID();
4450       auto *Exported = cast<NamedDecl>(D);
4451       Module *Owner = SubmoduleID ? Reader.getSubmodule(SubmoduleID) : nullptr;
4452       Reader.getContext().mergeDefinitionIntoModule(Exported, Owner);
4453       Reader.PendingMergedDefinitionsToDeduplicate.insert(Exported);
4454       break;
4455     }
4456 
4457     case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
4458       D->addAttr(OMPDeclareTargetDeclAttr::CreateImplicit(
4459           Reader.getContext(),
4460           static_cast<OMPDeclareTargetDeclAttr::MapTypeTy>(Record.readInt()),
4461           ReadSourceRange()));
4462       break;
4463 
4464     case UPD_ADDED_ATTR_TO_RECORD:
4465       AttrVec Attrs;
4466       Record.readAttributes(Attrs);
4467       assert(Attrs.size() == 1);
4468       D->addAttr(Attrs[0]);
4469       break;
4470     }
4471   }
4472 }
4473