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