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