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