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