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