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