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