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