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