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