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