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