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