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