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