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