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