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