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