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