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