1 //===- ASTReaderDecl.cpp - Decl Deserialization ---------------------------===//
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
7 //===----------------------------------------------------------------------===//
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/ASTContext.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/AttrIterator.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclBase.h"
21 #include "clang/AST/DeclCXX.h"
22 #include "clang/AST/DeclFriend.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/DeclOpenMP.h"
25 #include "clang/AST/DeclTemplate.h"
26 #include "clang/AST/DeclVisitor.h"
27 #include "clang/AST/DeclarationName.h"
28 #include "clang/AST/Expr.h"
29 #include "clang/AST/ExternalASTSource.h"
30 #include "clang/AST/LambdaCapture.h"
31 #include "clang/AST/NestedNameSpecifier.h"
32 #include "clang/AST/OpenMPClause.h"
33 #include "clang/AST/Redeclarable.h"
34 #include "clang/AST/Stmt.h"
35 #include "clang/AST/TemplateBase.h"
36 #include "clang/AST/Type.h"
37 #include "clang/AST/UnresolvedSet.h"
38 #include "clang/Basic/AttrKinds.h"
39 #include "clang/Basic/ExceptionSpecificationType.h"
40 #include "clang/Basic/IdentifierTable.h"
41 #include "clang/Basic/LLVM.h"
42 #include "clang/Basic/Lambda.h"
43 #include "clang/Basic/LangOptions.h"
44 #include "clang/Basic/Linkage.h"
45 #include "clang/Basic/Module.h"
46 #include "clang/Basic/PragmaKinds.h"
47 #include "clang/Basic/SourceLocation.h"
48 #include "clang/Basic/Specifiers.h"
49 #include "clang/Sema/IdentifierResolver.h"
50 #include "clang/Serialization/ASTBitCodes.h"
51 #include "clang/Serialization/ASTRecordReader.h"
52 #include "clang/Serialization/ContinuousRangeMap.h"
53 #include "clang/Serialization/ModuleFile.h"
54 #include "llvm/ADT/DenseMap.h"
55 #include "llvm/ADT/FoldingSet.h"
56 #include "llvm/ADT/STLExtras.h"
57 #include "llvm/ADT/SmallPtrSet.h"
58 #include "llvm/ADT/SmallVector.h"
59 #include "llvm/ADT/iterator_range.h"
60 #include "llvm/Bitstream/BitstreamReader.h"
61 #include "llvm/Support/Casting.h"
62 #include "llvm/Support/ErrorHandling.h"
63 #include "llvm/Support/SaveAndRestore.h"
71 using namespace clang;
72 using namespace serialization;
74 //===----------------------------------------------------------------------===//
75 // Declaration deserialization
76 //===----------------------------------------------------------------------===//
80 class ASTDeclReader : public DeclVisitor<ASTDeclReader, void> {
82 ASTRecordReader &Record;
83 ASTReader::RecordLocation Loc;
84 const DeclID ThisDeclID;
85 const SourceLocation ThisDeclLoc;
87 using RecordData = ASTReader::RecordData;
89 TypeID DeferredTypeID = 0;
90 unsigned AnonymousDeclNumber;
91 GlobalDeclID NamedDeclForTagDecl = 0;
92 IdentifierInfo *TypedefNameForLinkage = nullptr;
94 bool HasPendingBody = false;
96 ///A flag to carry the information for a decl from the entity is
97 /// used. We use it to delay the marking of the canonical decl as used until
98 /// the entire declaration is deserialized and merged.
99 bool IsDeclMarkedUsed = false;
101 uint64_t GetCurrentCursorOffset();
103 uint64_t ReadLocalOffset() {
104 uint64_t LocalOffset = Record.readInt();
105 assert(LocalOffset < Loc.Offset && "offset point after current record");
106 return LocalOffset ? Loc.Offset - LocalOffset : 0;
109 uint64_t ReadGlobalOffset() {
110 uint64_t Local = ReadLocalOffset();
111 return Local ? Record.getGlobalBitOffset(Local) : 0;
114 SourceLocation readSourceLocation() {
115 return Record.readSourceLocation();
118 SourceRange readSourceRange() {
119 return Record.readSourceRange();
122 TypeSourceInfo *readTypeSourceInfo() {
123 return Record.readTypeSourceInfo();
126 serialization::DeclID readDeclID() {
127 return Record.readDeclID();
130 std::string readString() {
131 return Record.readString();
134 void readDeclIDList(SmallVectorImpl<DeclID> &IDs) {
135 for (unsigned I = 0, Size = Record.readInt(); I != Size; ++I)
136 IDs.push_back(readDeclID());
140 return Record.readDecl();
145 return Record.readDeclAs<T>();
148 serialization::SubmoduleID readSubmoduleID() {
149 if (Record.getIdx() == Record.size())
152 return Record.getGlobalSubmoduleID(Record.readInt());
155 Module *readModule() {
156 return Record.getSubmodule(readSubmoduleID());
159 void ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update);
160 void ReadCXXDefinitionData(struct CXXRecordDecl::DefinitionData &Data,
161 const CXXRecordDecl *D);
162 void MergeDefinitionData(CXXRecordDecl *D,
163 struct CXXRecordDecl::DefinitionData &&NewDD);
164 void ReadObjCDefinitionData(struct ObjCInterfaceDecl::DefinitionData &Data);
165 void MergeDefinitionData(ObjCInterfaceDecl *D,
166 struct ObjCInterfaceDecl::DefinitionData &&NewDD);
167 void ReadObjCDefinitionData(struct ObjCProtocolDecl::DefinitionData &Data);
168 void MergeDefinitionData(ObjCProtocolDecl *D,
169 struct ObjCProtocolDecl::DefinitionData &&NewDD);
171 static DeclContext *getPrimaryDCForAnonymousDecl(DeclContext *LexicalDC);
173 static NamedDecl *getAnonymousDeclForMerging(ASTReader &Reader,
176 static void setAnonymousDeclForMerging(ASTReader &Reader, DeclContext *DC,
177 unsigned Index, NamedDecl *D);
179 /// Results from loading a RedeclarableDecl.
180 class RedeclarableResult {
182 GlobalDeclID FirstID;
186 RedeclarableResult(Decl *MergeWith, GlobalDeclID FirstID, bool IsKeyDecl)
187 : MergeWith(MergeWith), FirstID(FirstID), IsKeyDecl(IsKeyDecl) {}
189 /// Retrieve the first ID.
190 GlobalDeclID getFirstID() const { return FirstID; }
192 /// Is this declaration a key declaration?
193 bool isKeyDecl() const { return IsKeyDecl; }
195 /// Get a known declaration that this should be merged with, if
197 Decl *getKnownMergeTarget() const { return MergeWith; }
200 /// Class used to capture the result of searching for an existing
201 /// declaration of a specific kind and name, along with the ability
202 /// to update the place where this result was found (the declaration
203 /// chain hanging off an identifier or the DeclContext we searched in)
205 class FindExistingResult {
207 NamedDecl *New = nullptr;
208 NamedDecl *Existing = nullptr;
209 bool AddResult = false;
210 unsigned AnonymousDeclNumber = 0;
211 IdentifierInfo *TypedefNameForLinkage = nullptr;
214 FindExistingResult(ASTReader &Reader) : Reader(Reader) {}
216 FindExistingResult(ASTReader &Reader, NamedDecl *New, NamedDecl *Existing,
217 unsigned AnonymousDeclNumber,
218 IdentifierInfo *TypedefNameForLinkage)
219 : Reader(Reader), New(New), Existing(Existing), AddResult(true),
220 AnonymousDeclNumber(AnonymousDeclNumber),
221 TypedefNameForLinkage(TypedefNameForLinkage) {}
223 FindExistingResult(FindExistingResult &&Other)
224 : Reader(Other.Reader), New(Other.New), Existing(Other.Existing),
225 AddResult(Other.AddResult),
226 AnonymousDeclNumber(Other.AnonymousDeclNumber),
227 TypedefNameForLinkage(Other.TypedefNameForLinkage) {
228 Other.AddResult = false;
231 FindExistingResult &operator=(FindExistingResult &&) = delete;
232 ~FindExistingResult();
234 /// Suppress the addition of this result into the known set of
236 void suppress() { AddResult = false; }
238 operator NamedDecl*() const { return Existing; }
241 operator T*() const { return dyn_cast_or_null<T>(Existing); }
244 static DeclContext *getPrimaryContextForMerging(ASTReader &Reader,
246 FindExistingResult findExisting(NamedDecl *D);
249 ASTDeclReader(ASTReader &Reader, ASTRecordReader &Record,
250 ASTReader::RecordLocation Loc,
251 DeclID thisDeclID, SourceLocation ThisDeclLoc)
252 : Reader(Reader), Record(Record), Loc(Loc), ThisDeclID(thisDeclID),
253 ThisDeclLoc(ThisDeclLoc) {}
255 template <typename T> static
256 void AddLazySpecializations(T *D,
257 SmallVectorImpl<serialization::DeclID>& IDs) {
261 // FIXME: We should avoid this pattern of getting the ASTContext.
262 ASTContext &C = D->getASTContext();
264 auto *&LazySpecializations = D->getCommonPtr()->LazySpecializations;
266 if (auto &Old = LazySpecializations) {
267 IDs.insert(IDs.end(), Old + 1, Old + 1 + Old[0]);
269 IDs.erase(std::unique(IDs.begin(), IDs.end()), IDs.end());
272 auto *Result = new (C) serialization::DeclID[1 + IDs.size()];
273 *Result = IDs.size();
274 std::copy(IDs.begin(), IDs.end(), Result + 1);
276 LazySpecializations = Result;
279 template <typename DeclT>
280 static Decl *getMostRecentDeclImpl(Redeclarable<DeclT> *D);
281 static Decl *getMostRecentDeclImpl(...);
282 static Decl *getMostRecentDecl(Decl *D);
284 template <typename DeclT>
285 static void attachPreviousDeclImpl(ASTReader &Reader,
286 Redeclarable<DeclT> *D, Decl *Previous,
288 static void attachPreviousDeclImpl(ASTReader &Reader, ...);
289 static void attachPreviousDecl(ASTReader &Reader, Decl *D, Decl *Previous,
292 template <typename DeclT>
293 static void attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest);
294 static void attachLatestDeclImpl(...);
295 static void attachLatestDecl(Decl *D, Decl *latest);
297 template <typename DeclT>
298 static void markIncompleteDeclChainImpl(Redeclarable<DeclT> *D);
299 static void markIncompleteDeclChainImpl(...);
301 /// Determine whether this declaration has a pending body.
302 bool hasPendingBody() const { return HasPendingBody; }
304 void ReadFunctionDefinition(FunctionDecl *FD);
307 void UpdateDecl(Decl *D, SmallVectorImpl<serialization::DeclID> &);
309 static void setNextObjCCategory(ObjCCategoryDecl *Cat,
310 ObjCCategoryDecl *Next) {
311 Cat->NextClassCategory = Next;
314 void VisitDecl(Decl *D);
315 void VisitPragmaCommentDecl(PragmaCommentDecl *D);
316 void VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D);
317 void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
318 void VisitNamedDecl(NamedDecl *ND);
319 void VisitLabelDecl(LabelDecl *LD);
320 void VisitNamespaceDecl(NamespaceDecl *D);
321 void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
322 void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
323 void VisitTypeDecl(TypeDecl *TD);
324 RedeclarableResult VisitTypedefNameDecl(TypedefNameDecl *TD);
325 void VisitTypedefDecl(TypedefDecl *TD);
326 void VisitTypeAliasDecl(TypeAliasDecl *TD);
327 void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
328 RedeclarableResult VisitTagDecl(TagDecl *TD);
329 void VisitEnumDecl(EnumDecl *ED);
330 RedeclarableResult VisitRecordDeclImpl(RecordDecl *RD);
331 void VisitRecordDecl(RecordDecl *RD) { VisitRecordDeclImpl(RD); }
332 RedeclarableResult VisitCXXRecordDeclImpl(CXXRecordDecl *D);
333 void VisitCXXRecordDecl(CXXRecordDecl *D) { VisitCXXRecordDeclImpl(D); }
334 RedeclarableResult VisitClassTemplateSpecializationDeclImpl(
335 ClassTemplateSpecializationDecl *D);
337 void VisitClassTemplateSpecializationDecl(
338 ClassTemplateSpecializationDecl *D) {
339 VisitClassTemplateSpecializationDeclImpl(D);
342 void VisitClassTemplatePartialSpecializationDecl(
343 ClassTemplatePartialSpecializationDecl *D);
344 void VisitClassScopeFunctionSpecializationDecl(
345 ClassScopeFunctionSpecializationDecl *D);
347 VisitVarTemplateSpecializationDeclImpl(VarTemplateSpecializationDecl *D);
349 void VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D) {
350 VisitVarTemplateSpecializationDeclImpl(D);
353 void VisitVarTemplatePartialSpecializationDecl(
354 VarTemplatePartialSpecializationDecl *D);
355 void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
356 void VisitValueDecl(ValueDecl *VD);
357 void VisitEnumConstantDecl(EnumConstantDecl *ECD);
358 void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
359 void VisitDeclaratorDecl(DeclaratorDecl *DD);
360 void VisitFunctionDecl(FunctionDecl *FD);
361 void VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *GD);
362 void VisitCXXMethodDecl(CXXMethodDecl *D);
363 void VisitCXXConstructorDecl(CXXConstructorDecl *D);
364 void VisitCXXDestructorDecl(CXXDestructorDecl *D);
365 void VisitCXXConversionDecl(CXXConversionDecl *D);
366 void VisitFieldDecl(FieldDecl *FD);
367 void VisitMSPropertyDecl(MSPropertyDecl *FD);
368 void VisitIndirectFieldDecl(IndirectFieldDecl *FD);
369 RedeclarableResult VisitVarDeclImpl(VarDecl *D);
370 void VisitVarDecl(VarDecl *VD) { VisitVarDeclImpl(VD); }
371 void VisitImplicitParamDecl(ImplicitParamDecl *PD);
372 void VisitParmVarDecl(ParmVarDecl *PD);
373 void VisitDecompositionDecl(DecompositionDecl *DD);
374 void VisitBindingDecl(BindingDecl *BD);
375 void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
376 DeclID VisitTemplateDecl(TemplateDecl *D);
377 void VisitConceptDecl(ConceptDecl *D);
378 void VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D);
379 RedeclarableResult VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);
380 void VisitClassTemplateDecl(ClassTemplateDecl *D);
381 void VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D);
382 void VisitVarTemplateDecl(VarTemplateDecl *D);
383 void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
384 void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
385 void VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
386 void VisitUsingDecl(UsingDecl *D);
387 void VisitUsingPackDecl(UsingPackDecl *D);
388 void VisitUsingShadowDecl(UsingShadowDecl *D);
389 void VisitConstructorUsingShadowDecl(ConstructorUsingShadowDecl *D);
390 void VisitLinkageSpecDecl(LinkageSpecDecl *D);
391 void VisitExportDecl(ExportDecl *D);
392 void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);
393 void VisitImportDecl(ImportDecl *D);
394 void VisitAccessSpecDecl(AccessSpecDecl *D);
395 void VisitFriendDecl(FriendDecl *D);
396 void VisitFriendTemplateDecl(FriendTemplateDecl *D);
397 void VisitStaticAssertDecl(StaticAssertDecl *D);
398 void VisitBlockDecl(BlockDecl *BD);
399 void VisitCapturedDecl(CapturedDecl *CD);
400 void VisitEmptyDecl(EmptyDecl *D);
401 void VisitLifetimeExtendedTemporaryDecl(LifetimeExtendedTemporaryDecl *D);
403 std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
406 RedeclarableResult VisitRedeclarable(Redeclarable<T> *D);
409 void mergeRedeclarable(Redeclarable<T> *D, RedeclarableResult &Redecl,
410 DeclID TemplatePatternID = 0);
413 void mergeRedeclarable(Redeclarable<T> *D, T *Existing,
414 RedeclarableResult &Redecl,
415 DeclID TemplatePatternID = 0);
418 void mergeMergeable(Mergeable<T> *D);
420 void mergeMergeable(LifetimeExtendedTemporaryDecl *D);
422 void mergeTemplatePattern(RedeclarableTemplateDecl *D,
423 RedeclarableTemplateDecl *Existing,
424 DeclID DsID, bool IsKeyDecl);
426 ObjCTypeParamList *ReadObjCTypeParamList();
428 // FIXME: Reorder according to DeclNodes.td?
429 void VisitObjCMethodDecl(ObjCMethodDecl *D);
430 void VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
431 void VisitObjCContainerDecl(ObjCContainerDecl *D);
432 void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
433 void VisitObjCIvarDecl(ObjCIvarDecl *D);
434 void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
435 void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
436 void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
437 void VisitObjCImplDecl(ObjCImplDecl *D);
438 void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
439 void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
440 void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
441 void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
442 void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
443 void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D);
444 void VisitOMPAllocateDecl(OMPAllocateDecl *D);
445 void VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D);
446 void VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D);
447 void VisitOMPRequiresDecl(OMPRequiresDecl *D);
448 void VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D);
455 /// Iterator over the redeclarations of a declaration that have already
456 /// been merged into the same redeclaration chain.
457 template<typename DeclT>
458 class MergedRedeclIterator {
460 DeclT *Canonical = nullptr;
461 DeclT *Current = nullptr;
464 MergedRedeclIterator() = default;
465 MergedRedeclIterator(DeclT *Start) : Start(Start), Current(Start) {}
467 DeclT *operator*() { return Current; }
469 MergedRedeclIterator &operator++() {
470 if (Current->isFirstDecl()) {
472 Current = Current->getMostRecentDecl();
474 Current = Current->getPreviousDecl();
476 // If we started in the merged portion, we'll reach our start position
477 // eventually. Otherwise, we'll never reach it, but the second declaration
478 // we reached was the canonical declaration, so stop when we see that one
480 if (Current == Start || Current == Canonical)
485 friend bool operator!=(const MergedRedeclIterator &A,
486 const MergedRedeclIterator &B) {
487 return A.Current != B.Current;
493 template <typename DeclT>
494 static llvm::iterator_range<MergedRedeclIterator<DeclT>>
495 merged_redecls(DeclT *D) {
496 return llvm::make_range(MergedRedeclIterator<DeclT>(D),
497 MergedRedeclIterator<DeclT>());
500 uint64_t ASTDeclReader::GetCurrentCursorOffset() {
501 return Loc.F->DeclsCursor.GetCurrentBitNo() + Loc.F->GlobalBitOffset;
504 void ASTDeclReader::ReadFunctionDefinition(FunctionDecl *FD) {
505 if (Record.readInt())
506 Reader.DefinitionSource[FD] = Loc.F->Kind == ModuleKind::MK_MainFile;
507 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD)) {
508 CD->setNumCtorInitializers(Record.readInt());
509 if (CD->getNumCtorInitializers())
510 CD->CtorInitializers = ReadGlobalOffset();
512 // Store the offset of the body so we can lazily load it later.
513 Reader.PendingBodies[FD] = GetCurrentCursorOffset();
514 HasPendingBody = true;
517 void ASTDeclReader::Visit(Decl *D) {
518 DeclVisitor<ASTDeclReader, void>::Visit(D);
520 // At this point we have deserialized and merged the decl and it is safe to
521 // update its canonical decl to signal that the entire entity is used.
522 D->getCanonicalDecl()->Used |= IsDeclMarkedUsed;
523 IsDeclMarkedUsed = false;
525 if (auto *DD = dyn_cast<DeclaratorDecl>(D)) {
526 if (auto *TInfo = DD->getTypeSourceInfo())
527 Record.readTypeLoc(TInfo->getTypeLoc());
530 if (auto *TD = dyn_cast<TypeDecl>(D)) {
531 // We have a fully initialized TypeDecl. Read its type now.
532 TD->setTypeForDecl(Reader.GetType(DeferredTypeID).getTypePtrOrNull());
534 // If this is a tag declaration with a typedef name for linkage, it's safe
535 // to load that typedef now.
536 if (NamedDeclForTagDecl)
537 cast<TagDecl>(D)->TypedefNameDeclOrQualifier =
538 cast<TypedefNameDecl>(Reader.GetDecl(NamedDeclForTagDecl));
539 } else if (auto *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
540 // if we have a fully initialized TypeDecl, we can safely read its type now.
541 ID->TypeForDecl = Reader.GetType(DeferredTypeID).getTypePtrOrNull();
542 } else if (auto *FD = dyn_cast<FunctionDecl>(D)) {
543 // FunctionDecl's body was written last after all other Stmts/Exprs.
544 // We only read it if FD doesn't already have a body (e.g., from another
546 // FIXME: Can we diagnose ODR violations somehow?
547 if (Record.readInt())
548 ReadFunctionDefinition(FD);
552 void ASTDeclReader::VisitDecl(Decl *D) {
553 if (D->isTemplateParameter() || D->isTemplateParameterPack() ||
554 isa<ParmVarDecl>(D) || isa<ObjCTypeParamDecl>(D)) {
555 // We don't want to deserialize the DeclContext of a template
556 // parameter or of a parameter of a function template immediately. These
557 // entities might be used in the formulation of its DeclContext (for
558 // example, a function parameter can be used in decltype() in trailing
559 // return type of the function). Use the translation unit DeclContext as a
561 GlobalDeclID SemaDCIDForTemplateParmDecl = readDeclID();
562 GlobalDeclID LexicalDCIDForTemplateParmDecl = readDeclID();
563 if (!LexicalDCIDForTemplateParmDecl)
564 LexicalDCIDForTemplateParmDecl = SemaDCIDForTemplateParmDecl;
565 Reader.addPendingDeclContextInfo(D,
566 SemaDCIDForTemplateParmDecl,
567 LexicalDCIDForTemplateParmDecl);
568 D->setDeclContext(Reader.getContext().getTranslationUnitDecl());
570 auto *SemaDC = readDeclAs<DeclContext>();
571 auto *LexicalDC = readDeclAs<DeclContext>();
574 DeclContext *MergedSemaDC = Reader.MergedDeclContexts.lookup(SemaDC);
575 // Avoid calling setLexicalDeclContext() directly because it uses
576 // Decl::getASTContext() internally which is unsafe during derialization.
577 D->setDeclContextsImpl(MergedSemaDC ? MergedSemaDC : SemaDC, LexicalDC,
578 Reader.getContext());
580 D->setLocation(ThisDeclLoc);
581 D->setInvalidDecl(Record.readInt());
582 if (Record.readInt()) { // hasAttrs
584 Record.readAttributes(Attrs);
585 // Avoid calling setAttrs() directly because it uses Decl::getASTContext()
586 // internally which is unsafe during derialization.
587 D->setAttrsImpl(Attrs, Reader.getContext());
589 D->setImplicit(Record.readInt());
590 D->Used = Record.readInt();
591 IsDeclMarkedUsed |= D->Used;
592 D->setReferenced(Record.readInt());
593 D->setTopLevelDeclInObjCContainer(Record.readInt());
594 D->setAccess((AccessSpecifier)Record.readInt());
595 D->FromASTFile = true;
596 bool ModulePrivate = Record.readInt();
598 // Determine whether this declaration is part of a (sub)module. If so, it
599 // may not yet be visible.
600 if (unsigned SubmoduleID = readSubmoduleID()) {
601 // Store the owning submodule ID in the declaration.
602 D->setModuleOwnershipKind(
603 ModulePrivate ? Decl::ModuleOwnershipKind::ModulePrivate
604 : Decl::ModuleOwnershipKind::VisibleWhenImported);
605 D->setOwningModuleID(SubmoduleID);
608 // Module-private declarations are never visible, so there is no work to
610 } else if (Reader.getContext().getLangOpts().ModulesLocalVisibility) {
611 // If local visibility is being tracked, this declaration will become
612 // hidden and visible as the owning module does.
613 } else if (Module *Owner = Reader.getSubmodule(SubmoduleID)) {
614 // Mark the declaration as visible when its owning module becomes visible.
615 if (Owner->NameVisibility == Module::AllVisible)
616 D->setVisibleDespiteOwningModule();
618 Reader.HiddenNamesMap[Owner].push_back(D);
620 } else if (ModulePrivate) {
621 D->setModuleOwnershipKind(Decl::ModuleOwnershipKind::ModulePrivate);
625 void ASTDeclReader::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
627 D->setLocation(readSourceLocation());
628 D->CommentKind = (PragmaMSCommentKind)Record.readInt();
629 std::string Arg = readString();
630 memcpy(D->getTrailingObjects<char>(), Arg.data(), Arg.size());
631 D->getTrailingObjects<char>()[Arg.size()] = '\0';
634 void ASTDeclReader::VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D) {
636 D->setLocation(readSourceLocation());
637 std::string Name = readString();
638 memcpy(D->getTrailingObjects<char>(), Name.data(), Name.size());
639 D->getTrailingObjects<char>()[Name.size()] = '\0';
641 D->ValueStart = Name.size() + 1;
642 std::string Value = readString();
643 memcpy(D->getTrailingObjects<char>() + D->ValueStart, Value.data(),
645 D->getTrailingObjects<char>()[D->ValueStart + Value.size()] = '\0';
648 void ASTDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
649 llvm_unreachable("Translation units are not serialized");
652 void ASTDeclReader::VisitNamedDecl(NamedDecl *ND) {
654 ND->setDeclName(Record.readDeclarationName());
655 AnonymousDeclNumber = Record.readInt();
658 void ASTDeclReader::VisitTypeDecl(TypeDecl *TD) {
660 TD->setLocStart(readSourceLocation());
661 // Delay type reading until after we have fully initialized the decl.
662 DeferredTypeID = Record.getGlobalTypeID(Record.readInt());
665 ASTDeclReader::RedeclarableResult
666 ASTDeclReader::VisitTypedefNameDecl(TypedefNameDecl *TD) {
667 RedeclarableResult Redecl = VisitRedeclarable(TD);
669 TypeSourceInfo *TInfo = readTypeSourceInfo();
670 if (Record.readInt()) { // isModed
671 QualType modedT = Record.readType();
672 TD->setModedTypeSourceInfo(TInfo, modedT);
674 TD->setTypeSourceInfo(TInfo);
675 // Read and discard the declaration for which this is a typedef name for
676 // linkage, if it exists. We cannot rely on our type to pull in this decl,
677 // because it might have been merged with a type from another module and
678 // thus might not refer to our version of the declaration.
683 void ASTDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
684 RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
685 mergeRedeclarable(TD, Redecl);
688 void ASTDeclReader::VisitTypeAliasDecl(TypeAliasDecl *TD) {
689 RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
690 if (auto *Template = readDeclAs<TypeAliasTemplateDecl>())
691 // Merged when we merge the template.
692 TD->setDescribedAliasTemplate(Template);
694 mergeRedeclarable(TD, Redecl);
697 ASTDeclReader::RedeclarableResult ASTDeclReader::VisitTagDecl(TagDecl *TD) {
698 RedeclarableResult Redecl = VisitRedeclarable(TD);
701 TD->IdentifierNamespace = Record.readInt();
702 TD->setTagKind((TagDecl::TagKind)Record.readInt());
703 if (!isa<CXXRecordDecl>(TD))
704 TD->setCompleteDefinition(Record.readInt());
705 TD->setEmbeddedInDeclarator(Record.readInt());
706 TD->setFreeStanding(Record.readInt());
707 TD->setCompleteDefinitionRequired(Record.readInt());
708 TD->setBraceRange(readSourceRange());
710 switch (Record.readInt()) {
714 auto *Info = new (Reader.getContext()) TagDecl::ExtInfo();
715 Record.readQualifierInfo(*Info);
716 TD->TypedefNameDeclOrQualifier = Info;
719 case 2: // TypedefNameForAnonDecl
720 NamedDeclForTagDecl = readDeclID();
721 TypedefNameForLinkage = Record.readIdentifier();
724 llvm_unreachable("unexpected tag info kind");
727 if (!isa<CXXRecordDecl>(TD))
728 mergeRedeclarable(TD, Redecl);
732 void ASTDeclReader::VisitEnumDecl(EnumDecl *ED) {
734 if (TypeSourceInfo *TI = readTypeSourceInfo())
735 ED->setIntegerTypeSourceInfo(TI);
737 ED->setIntegerType(Record.readType());
738 ED->setPromotionType(Record.readType());
739 ED->setNumPositiveBits(Record.readInt());
740 ED->setNumNegativeBits(Record.readInt());
741 ED->setScoped(Record.readInt());
742 ED->setScopedUsingClassTag(Record.readInt());
743 ED->setFixed(Record.readInt());
745 ED->setHasODRHash(true);
746 ED->ODRHash = Record.readInt();
748 // If this is a definition subject to the ODR, and we already have a
749 // definition, merge this one into it.
750 if (ED->isCompleteDefinition() &&
751 Reader.getContext().getLangOpts().Modules &&
752 Reader.getContext().getLangOpts().CPlusPlus) {
753 EnumDecl *&OldDef = Reader.EnumDefinitions[ED->getCanonicalDecl()];
755 // This is the first time we've seen an imported definition. Look for a
756 // local definition before deciding that we are the first definition.
757 for (auto *D : merged_redecls(ED->getCanonicalDecl())) {
758 if (!D->isFromASTFile() && D->isCompleteDefinition()) {
765 Reader.MergedDeclContexts.insert(std::make_pair(ED, OldDef));
766 ED->setCompleteDefinition(false);
767 Reader.mergeDefinitionVisibility(OldDef, ED);
768 if (OldDef->getODRHash() != ED->getODRHash())
769 Reader.PendingEnumOdrMergeFailures[OldDef].push_back(ED);
775 if (auto *InstED = readDeclAs<EnumDecl>()) {
776 auto TSK = (TemplateSpecializationKind)Record.readInt();
777 SourceLocation POI = readSourceLocation();
778 ED->setInstantiationOfMemberEnum(Reader.getContext(), InstED, TSK);
779 ED->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
783 ASTDeclReader::RedeclarableResult
784 ASTDeclReader::VisitRecordDeclImpl(RecordDecl *RD) {
785 RedeclarableResult Redecl = VisitTagDecl(RD);
786 RD->setHasFlexibleArrayMember(Record.readInt());
787 RD->setAnonymousStructOrUnion(Record.readInt());
788 RD->setHasObjectMember(Record.readInt());
789 RD->setHasVolatileMember(Record.readInt());
790 RD->setNonTrivialToPrimitiveDefaultInitialize(Record.readInt());
791 RD->setNonTrivialToPrimitiveCopy(Record.readInt());
792 RD->setNonTrivialToPrimitiveDestroy(Record.readInt());
793 RD->setHasNonTrivialToPrimitiveDefaultInitializeCUnion(Record.readInt());
794 RD->setHasNonTrivialToPrimitiveDestructCUnion(Record.readInt());
795 RD->setHasNonTrivialToPrimitiveCopyCUnion(Record.readInt());
796 RD->setParamDestroyedInCallee(Record.readInt());
797 RD->setArgPassingRestrictions((RecordDecl::ArgPassingKind)Record.readInt());
801 void ASTDeclReader::VisitValueDecl(ValueDecl *VD) {
803 // For function declarations, defer reading the type in case the function has
804 // a deduced return type that references an entity declared within the
806 if (isa<FunctionDecl>(VD))
807 DeferredTypeID = Record.getGlobalTypeID(Record.readInt());
809 VD->setType(Record.readType());
812 void ASTDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
814 if (Record.readInt())
815 ECD->setInitExpr(Record.readExpr());
816 ECD->setInitVal(Record.readAPSInt());
820 void ASTDeclReader::VisitDeclaratorDecl(DeclaratorDecl *DD) {
822 DD->setInnerLocStart(readSourceLocation());
823 if (Record.readInt()) { // hasExtInfo
824 auto *Info = new (Reader.getContext()) DeclaratorDecl::ExtInfo();
825 Record.readQualifierInfo(*Info);
826 Info->TrailingRequiresClause = Record.readExpr();
829 QualType TSIType = Record.readType();
830 DD->setTypeSourceInfo(
831 TSIType.isNull() ? nullptr
832 : Reader.getContext().CreateTypeSourceInfo(TSIType));
835 void ASTDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
836 RedeclarableResult Redecl = VisitRedeclarable(FD);
837 VisitDeclaratorDecl(FD);
839 // Attach a type to this function. Use the real type if possible, but fall
840 // back to the type as written if it involves a deduced return type.
841 if (FD->getTypeSourceInfo() &&
842 FD->getTypeSourceInfo()->getType()->castAs<FunctionType>()
843 ->getReturnType()->getContainedAutoType()) {
844 // We'll set up the real type in Visit, once we've finished loading the
846 FD->setType(FD->getTypeSourceInfo()->getType());
847 Reader.PendingFunctionTypes.push_back({FD, DeferredTypeID});
849 FD->setType(Reader.GetType(DeferredTypeID));
853 FD->DNLoc = Record.readDeclarationNameLoc(FD->getDeclName());
854 FD->IdentifierNamespace = Record.readInt();
856 // FunctionDecl's body is handled last at ASTDeclReader::Visit,
857 // after everything else is read.
859 FD->setStorageClass(static_cast<StorageClass>(Record.readInt()));
860 FD->setInlineSpecified(Record.readInt());
861 FD->setImplicitlyInline(Record.readInt());
862 FD->setVirtualAsWritten(Record.readInt());
863 FD->setPure(Record.readInt());
864 FD->setHasInheritedPrototype(Record.readInt());
865 FD->setHasWrittenPrototype(Record.readInt());
866 FD->setDeletedAsWritten(Record.readInt());
867 FD->setTrivial(Record.readInt());
868 FD->setTrivialForCall(Record.readInt());
869 FD->setDefaulted(Record.readInt());
870 FD->setExplicitlyDefaulted(Record.readInt());
871 FD->setHasImplicitReturnZero(Record.readInt());
872 FD->setConstexprKind(static_cast<ConstexprSpecKind>(Record.readInt()));
873 FD->setUsesSEHTry(Record.readInt());
874 FD->setHasSkippedBody(Record.readInt());
875 FD->setIsMultiVersion(Record.readInt());
876 FD->setLateTemplateParsed(Record.readInt());
878 FD->setCachedLinkage(static_cast<Linkage>(Record.readInt()));
879 FD->EndRangeLoc = readSourceLocation();
881 FD->ODRHash = Record.readInt();
882 FD->setHasODRHash(true);
883 FD->setUsesFPIntrin(Record.readInt());
885 if (FD->isDefaulted()) {
886 if (unsigned NumLookups = Record.readInt()) {
887 SmallVector<DeclAccessPair, 8> Lookups;
888 for (unsigned I = 0; I != NumLookups; ++I) {
889 NamedDecl *ND = Record.readDeclAs<NamedDecl>();
890 AccessSpecifier AS = (AccessSpecifier)Record.readInt();
891 Lookups.push_back(DeclAccessPair::make(ND, AS));
893 FD->setDefaultedFunctionInfo(FunctionDecl::DefaultedFunctionInfo::Create(
894 Reader.getContext(), Lookups));
898 switch ((FunctionDecl::TemplatedKind)Record.readInt()) {
899 case FunctionDecl::TK_NonTemplate:
900 mergeRedeclarable(FD, Redecl);
902 case FunctionDecl::TK_FunctionTemplate:
903 // Merged when we merge the template.
904 FD->setDescribedFunctionTemplate(readDeclAs<FunctionTemplateDecl>());
906 case FunctionDecl::TK_MemberSpecialization: {
907 auto *InstFD = readDeclAs<FunctionDecl>();
908 auto TSK = (TemplateSpecializationKind)Record.readInt();
909 SourceLocation POI = readSourceLocation();
910 FD->setInstantiationOfMemberFunction(Reader.getContext(), InstFD, TSK);
911 FD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
912 mergeRedeclarable(FD, Redecl);
915 case FunctionDecl::TK_FunctionTemplateSpecialization: {
916 auto *Template = readDeclAs<FunctionTemplateDecl>();
917 auto TSK = (TemplateSpecializationKind)Record.readInt();
919 // Template arguments.
920 SmallVector<TemplateArgument, 8> TemplArgs;
921 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
923 // Template args as written.
924 SmallVector<TemplateArgumentLoc, 8> TemplArgLocs;
925 SourceLocation LAngleLoc, RAngleLoc;
926 bool HasTemplateArgumentsAsWritten = Record.readInt();
927 if (HasTemplateArgumentsAsWritten) {
928 unsigned NumTemplateArgLocs = Record.readInt();
929 TemplArgLocs.reserve(NumTemplateArgLocs);
930 for (unsigned i = 0; i != NumTemplateArgLocs; ++i)
931 TemplArgLocs.push_back(Record.readTemplateArgumentLoc());
933 LAngleLoc = readSourceLocation();
934 RAngleLoc = readSourceLocation();
937 SourceLocation POI = readSourceLocation();
939 ASTContext &C = Reader.getContext();
940 TemplateArgumentList *TemplArgList
941 = TemplateArgumentList::CreateCopy(C, TemplArgs);
942 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
943 for (unsigned i = 0, e = TemplArgLocs.size(); i != e; ++i)
944 TemplArgsInfo.addArgument(TemplArgLocs[i]);
946 MemberSpecializationInfo *MSInfo = nullptr;
947 if (Record.readInt()) {
948 auto *FD = readDeclAs<FunctionDecl>();
949 auto TSK = (TemplateSpecializationKind)Record.readInt();
950 SourceLocation POI = readSourceLocation();
952 MSInfo = new (C) MemberSpecializationInfo(FD, TSK);
953 MSInfo->setPointOfInstantiation(POI);
956 FunctionTemplateSpecializationInfo *FTInfo =
957 FunctionTemplateSpecializationInfo::Create(
958 C, FD, Template, TSK, TemplArgList,
959 HasTemplateArgumentsAsWritten ? &TemplArgsInfo : nullptr, POI,
961 FD->TemplateOrSpecialization = FTInfo;
963 if (FD->isCanonicalDecl()) { // if canonical add to template's set.
964 // The template that contains the specializations set. It's not safe to
965 // use getCanonicalDecl on Template since it may still be initializing.
966 auto *CanonTemplate = readDeclAs<FunctionTemplateDecl>();
967 // Get the InsertPos by FindNodeOrInsertPos() instead of calling
968 // InsertNode(FTInfo) directly to avoid the getASTContext() call in
969 // FunctionTemplateSpecializationInfo's Profile().
970 // We avoid getASTContext because a decl in the parent hierarchy may
972 llvm::FoldingSetNodeID ID;
973 FunctionTemplateSpecializationInfo::Profile(ID, TemplArgs, C);
974 void *InsertPos = nullptr;
975 FunctionTemplateDecl::Common *CommonPtr = CanonTemplate->getCommonPtr();
976 FunctionTemplateSpecializationInfo *ExistingInfo =
977 CommonPtr->Specializations.FindNodeOrInsertPos(ID, InsertPos);
979 CommonPtr->Specializations.InsertNode(FTInfo, InsertPos);
981 assert(Reader.getContext().getLangOpts().Modules &&
982 "already deserialized this template specialization");
983 mergeRedeclarable(FD, ExistingInfo->getFunction(), Redecl);
988 case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
990 UnresolvedSet<8> TemplDecls;
991 unsigned NumTemplates = Record.readInt();
992 while (NumTemplates--)
993 TemplDecls.addDecl(readDeclAs<NamedDecl>());
996 TemplateArgumentListInfo TemplArgs;
997 unsigned NumArgs = Record.readInt();
999 TemplArgs.addArgument(Record.readTemplateArgumentLoc());
1000 TemplArgs.setLAngleLoc(readSourceLocation());
1001 TemplArgs.setRAngleLoc(readSourceLocation());
1003 FD->setDependentTemplateSpecialization(Reader.getContext(),
1004 TemplDecls, TemplArgs);
1005 // These are not merged; we don't need to merge redeclarations of dependent
1006 // template friends.
1011 // Read in the parameters.
1012 unsigned NumParams = Record.readInt();
1013 SmallVector<ParmVarDecl *, 16> Params;
1014 Params.reserve(NumParams);
1015 for (unsigned I = 0; I != NumParams; ++I)
1016 Params.push_back(readDeclAs<ParmVarDecl>());
1017 FD->setParams(Reader.getContext(), Params);
1020 void ASTDeclReader::VisitObjCMethodDecl(ObjCMethodDecl *MD) {
1022 if (Record.readInt()) {
1023 // Load the body on-demand. Most clients won't care, because method
1024 // definitions rarely show up in headers.
1025 Reader.PendingBodies[MD] = GetCurrentCursorOffset();
1026 HasPendingBody = true;
1028 MD->setSelfDecl(readDeclAs<ImplicitParamDecl>());
1029 MD->setCmdDecl(readDeclAs<ImplicitParamDecl>());
1030 MD->setInstanceMethod(Record.readInt());
1031 MD->setVariadic(Record.readInt());
1032 MD->setPropertyAccessor(Record.readInt());
1033 MD->setSynthesizedAccessorStub(Record.readInt());
1034 MD->setDefined(Record.readInt());
1035 MD->setOverriding(Record.readInt());
1036 MD->setHasSkippedBody(Record.readInt());
1038 MD->setIsRedeclaration(Record.readInt());
1039 MD->setHasRedeclaration(Record.readInt());
1040 if (MD->hasRedeclaration())
1041 Reader.getContext().setObjCMethodRedeclaration(MD,
1042 readDeclAs<ObjCMethodDecl>());
1044 MD->setDeclImplementation((ObjCMethodDecl::ImplementationControl)Record.readInt());
1045 MD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record.readInt());
1046 MD->setRelatedResultType(Record.readInt());
1047 MD->setReturnType(Record.readType());
1048 MD->setReturnTypeSourceInfo(readTypeSourceInfo());
1049 MD->DeclEndLoc = readSourceLocation();
1050 unsigned NumParams = Record.readInt();
1051 SmallVector<ParmVarDecl *, 16> Params;
1052 Params.reserve(NumParams);
1053 for (unsigned I = 0; I != NumParams; ++I)
1054 Params.push_back(readDeclAs<ParmVarDecl>());
1056 MD->setSelLocsKind((SelectorLocationsKind)Record.readInt());
1057 unsigned NumStoredSelLocs = Record.readInt();
1058 SmallVector<SourceLocation, 16> SelLocs;
1059 SelLocs.reserve(NumStoredSelLocs);
1060 for (unsigned i = 0; i != NumStoredSelLocs; ++i)
1061 SelLocs.push_back(readSourceLocation());
1063 MD->setParamsAndSelLocs(Reader.getContext(), Params, SelLocs);
1066 void ASTDeclReader::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
1067 VisitTypedefNameDecl(D);
1069 D->Variance = Record.readInt();
1070 D->Index = Record.readInt();
1071 D->VarianceLoc = readSourceLocation();
1072 D->ColonLoc = readSourceLocation();
1075 void ASTDeclReader::VisitObjCContainerDecl(ObjCContainerDecl *CD) {
1077 CD->setAtStartLoc(readSourceLocation());
1078 CD->setAtEndRange(readSourceRange());
1081 ObjCTypeParamList *ASTDeclReader::ReadObjCTypeParamList() {
1082 unsigned numParams = Record.readInt();
1086 SmallVector<ObjCTypeParamDecl *, 4> typeParams;
1087 typeParams.reserve(numParams);
1088 for (unsigned i = 0; i != numParams; ++i) {
1089 auto *typeParam = readDeclAs<ObjCTypeParamDecl>();
1093 typeParams.push_back(typeParam);
1096 SourceLocation lAngleLoc = readSourceLocation();
1097 SourceLocation rAngleLoc = readSourceLocation();
1099 return ObjCTypeParamList::create(Reader.getContext(), lAngleLoc,
1100 typeParams, rAngleLoc);
1103 void ASTDeclReader::ReadObjCDefinitionData(
1104 struct ObjCInterfaceDecl::DefinitionData &Data) {
1105 // Read the superclass.
1106 Data.SuperClassTInfo = readTypeSourceInfo();
1108 Data.EndLoc = readSourceLocation();
1109 Data.HasDesignatedInitializers = Record.readInt();
1111 // Read the directly referenced protocols and their SourceLocations.
1112 unsigned NumProtocols = Record.readInt();
1113 SmallVector<ObjCProtocolDecl *, 16> Protocols;
1114 Protocols.reserve(NumProtocols);
1115 for (unsigned I = 0; I != NumProtocols; ++I)
1116 Protocols.push_back(readDeclAs<ObjCProtocolDecl>());
1117 SmallVector<SourceLocation, 16> ProtoLocs;
1118 ProtoLocs.reserve(NumProtocols);
1119 for (unsigned I = 0; I != NumProtocols; ++I)
1120 ProtoLocs.push_back(readSourceLocation());
1121 Data.ReferencedProtocols.set(Protocols.data(), NumProtocols, ProtoLocs.data(),
1122 Reader.getContext());
1124 // Read the transitive closure of protocols referenced by this class.
1125 NumProtocols = Record.readInt();
1127 Protocols.reserve(NumProtocols);
1128 for (unsigned I = 0; I != NumProtocols; ++I)
1129 Protocols.push_back(readDeclAs<ObjCProtocolDecl>());
1130 Data.AllReferencedProtocols.set(Protocols.data(), NumProtocols,
1131 Reader.getContext());
1134 void ASTDeclReader::MergeDefinitionData(ObjCInterfaceDecl *D,
1135 struct ObjCInterfaceDecl::DefinitionData &&NewDD) {
1136 // FIXME: odr checking?
1139 void ASTDeclReader::VisitObjCInterfaceDecl(ObjCInterfaceDecl *ID) {
1140 RedeclarableResult Redecl = VisitRedeclarable(ID);
1141 VisitObjCContainerDecl(ID);
1142 DeferredTypeID = Record.getGlobalTypeID(Record.readInt());
1143 mergeRedeclarable(ID, Redecl);
1145 ID->TypeParamList = ReadObjCTypeParamList();
1146 if (Record.readInt()) {
1147 // Read the definition.
1148 ID->allocateDefinitionData();
1150 ReadObjCDefinitionData(ID->data());
1151 ObjCInterfaceDecl *Canon = ID->getCanonicalDecl();
1152 if (Canon->Data.getPointer()) {
1153 // If we already have a definition, keep the definition invariant and
1155 MergeDefinitionData(Canon, std::move(ID->data()));
1156 ID->Data = Canon->Data;
1158 // Set the definition data of the canonical declaration, so other
1159 // redeclarations will see it.
1160 ID->getCanonicalDecl()->Data = ID->Data;
1162 // We will rebuild this list lazily.
1163 ID->setIvarList(nullptr);
1166 // Note that we have deserialized a definition.
1167 Reader.PendingDefinitions.insert(ID);
1169 // Note that we've loaded this Objective-C class.
1170 Reader.ObjCClassesLoaded.push_back(ID);
1172 ID->Data = ID->getCanonicalDecl()->Data;
1176 void ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) {
1177 VisitFieldDecl(IVD);
1178 IVD->setAccessControl((ObjCIvarDecl::AccessControl)Record.readInt());
1179 // This field will be built lazily.
1180 IVD->setNextIvar(nullptr);
1181 bool synth = Record.readInt();
1182 IVD->setSynthesize(synth);
1185 void ASTDeclReader::ReadObjCDefinitionData(
1186 struct ObjCProtocolDecl::DefinitionData &Data) {
1187 unsigned NumProtoRefs = Record.readInt();
1188 SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
1189 ProtoRefs.reserve(NumProtoRefs);
1190 for (unsigned I = 0; I != NumProtoRefs; ++I)
1191 ProtoRefs.push_back(readDeclAs<ObjCProtocolDecl>());
1192 SmallVector<SourceLocation, 16> ProtoLocs;
1193 ProtoLocs.reserve(NumProtoRefs);
1194 for (unsigned I = 0; I != NumProtoRefs; ++I)
1195 ProtoLocs.push_back(readSourceLocation());
1196 Data.ReferencedProtocols.set(ProtoRefs.data(), NumProtoRefs,
1197 ProtoLocs.data(), Reader.getContext());
1200 void ASTDeclReader::MergeDefinitionData(ObjCProtocolDecl *D,
1201 struct ObjCProtocolDecl::DefinitionData &&NewDD) {
1202 // FIXME: odr checking?
1205 void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {
1206 RedeclarableResult Redecl = VisitRedeclarable(PD);
1207 VisitObjCContainerDecl(PD);
1208 mergeRedeclarable(PD, Redecl);
1210 if (Record.readInt()) {
1211 // Read the definition.
1212 PD->allocateDefinitionData();
1214 ReadObjCDefinitionData(PD->data());
1216 ObjCProtocolDecl *Canon = PD->getCanonicalDecl();
1217 if (Canon->Data.getPointer()) {
1218 // If we already have a definition, keep the definition invariant and
1220 MergeDefinitionData(Canon, std::move(PD->data()));
1221 PD->Data = Canon->Data;
1223 // Set the definition data of the canonical declaration, so other
1224 // redeclarations will see it.
1225 PD->getCanonicalDecl()->Data = PD->Data;
1227 // Note that we have deserialized a definition.
1228 Reader.PendingDefinitions.insert(PD);
1230 PD->Data = PD->getCanonicalDecl()->Data;
1234 void ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {
1238 void ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {
1239 VisitObjCContainerDecl(CD);
1240 CD->setCategoryNameLoc(readSourceLocation());
1241 CD->setIvarLBraceLoc(readSourceLocation());
1242 CD->setIvarRBraceLoc(readSourceLocation());
1244 // Note that this category has been deserialized. We do this before
1245 // deserializing the interface declaration, so that it will consider this
1247 Reader.CategoriesDeserialized.insert(CD);
1249 CD->ClassInterface = readDeclAs<ObjCInterfaceDecl>();
1250 CD->TypeParamList = ReadObjCTypeParamList();
1251 unsigned NumProtoRefs = Record.readInt();
1252 SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
1253 ProtoRefs.reserve(NumProtoRefs);
1254 for (unsigned I = 0; I != NumProtoRefs; ++I)
1255 ProtoRefs.push_back(readDeclAs<ObjCProtocolDecl>());
1256 SmallVector<SourceLocation, 16> ProtoLocs;
1257 ProtoLocs.reserve(NumProtoRefs);
1258 for (unsigned I = 0; I != NumProtoRefs; ++I)
1259 ProtoLocs.push_back(readSourceLocation());
1260 CD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
1261 Reader.getContext());
1263 // Protocols in the class extension belong to the class.
1264 if (NumProtoRefs > 0 && CD->ClassInterface && CD->IsClassExtension())
1265 CD->ClassInterface->mergeClassExtensionProtocolList(
1266 (ObjCProtocolDecl *const *)ProtoRefs.data(), NumProtoRefs,
1267 Reader.getContext());
1270 void ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
1271 VisitNamedDecl(CAD);
1272 CAD->setClassInterface(readDeclAs<ObjCInterfaceDecl>());
1275 void ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
1277 D->setAtLoc(readSourceLocation());
1278 D->setLParenLoc(readSourceLocation());
1279 QualType T = Record.readType();
1280 TypeSourceInfo *TSI = readTypeSourceInfo();
1282 D->setPropertyAttributes(
1283 (ObjCPropertyDecl::PropertyAttributeKind)Record.readInt());
1284 D->setPropertyAttributesAsWritten(
1285 (ObjCPropertyDecl::PropertyAttributeKind)Record.readInt());
1286 D->setPropertyImplementation(
1287 (ObjCPropertyDecl::PropertyControl)Record.readInt());
1288 DeclarationName GetterName = Record.readDeclarationName();
1289 SourceLocation GetterLoc = readSourceLocation();
1290 D->setGetterName(GetterName.getObjCSelector(), GetterLoc);
1291 DeclarationName SetterName = Record.readDeclarationName();
1292 SourceLocation SetterLoc = readSourceLocation();
1293 D->setSetterName(SetterName.getObjCSelector(), SetterLoc);
1294 D->setGetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1295 D->setSetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1296 D->setPropertyIvarDecl(readDeclAs<ObjCIvarDecl>());
1299 void ASTDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) {
1300 VisitObjCContainerDecl(D);
1301 D->setClassInterface(readDeclAs<ObjCInterfaceDecl>());
1304 void ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1305 VisitObjCImplDecl(D);
1306 D->CategoryNameLoc = readSourceLocation();
1309 void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1310 VisitObjCImplDecl(D);
1311 D->setSuperClass(readDeclAs<ObjCInterfaceDecl>());
1312 D->SuperLoc = readSourceLocation();
1313 D->setIvarLBraceLoc(readSourceLocation());
1314 D->setIvarRBraceLoc(readSourceLocation());
1315 D->setHasNonZeroConstructors(Record.readInt());
1316 D->setHasDestructors(Record.readInt());
1317 D->NumIvarInitializers = Record.readInt();
1318 if (D->NumIvarInitializers)
1319 D->IvarInitializers = ReadGlobalOffset();
1322 void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
1324 D->setAtLoc(readSourceLocation());
1325 D->setPropertyDecl(readDeclAs<ObjCPropertyDecl>());
1326 D->PropertyIvarDecl = readDeclAs<ObjCIvarDecl>();
1327 D->IvarLoc = readSourceLocation();
1328 D->setGetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1329 D->setSetterMethodDecl(readDeclAs<ObjCMethodDecl>());
1330 D->setGetterCXXConstructor(Record.readExpr());
1331 D->setSetterCXXAssignment(Record.readExpr());
1334 void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {
1335 VisitDeclaratorDecl(FD);
1336 FD->Mutable = Record.readInt();
1338 if (auto ISK = static_cast<FieldDecl::InitStorageKind>(Record.readInt())) {
1339 FD->InitStorage.setInt(ISK);
1340 FD->InitStorage.setPointer(ISK == FieldDecl::ISK_CapturedVLAType
1341 ? Record.readType().getAsOpaquePtr()
1342 : Record.readExpr());
1345 if (auto *BW = Record.readExpr())
1346 FD->setBitWidth(BW);
1348 if (!FD->getDeclName()) {
1349 if (auto *Tmpl = readDeclAs<FieldDecl>())
1350 Reader.getContext().setInstantiatedFromUnnamedFieldDecl(FD, Tmpl);
1355 void ASTDeclReader::VisitMSPropertyDecl(MSPropertyDecl *PD) {
1356 VisitDeclaratorDecl(PD);
1357 PD->GetterId = Record.readIdentifier();
1358 PD->SetterId = Record.readIdentifier();
1361 void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
1364 FD->ChainingSize = Record.readInt();
1365 assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2");
1366 FD->Chaining = new (Reader.getContext())NamedDecl*[FD->ChainingSize];
1368 for (unsigned I = 0; I != FD->ChainingSize; ++I)
1369 FD->Chaining[I] = readDeclAs<NamedDecl>();
1374 ASTDeclReader::RedeclarableResult ASTDeclReader::VisitVarDeclImpl(VarDecl *VD) {
1375 RedeclarableResult Redecl = VisitRedeclarable(VD);
1376 VisitDeclaratorDecl(VD);
1378 VD->VarDeclBits.SClass = (StorageClass)Record.readInt();
1379 VD->VarDeclBits.TSCSpec = Record.readInt();
1380 VD->VarDeclBits.InitStyle = Record.readInt();
1381 VD->VarDeclBits.ARCPseudoStrong = Record.readInt();
1382 if (!isa<ParmVarDecl>(VD)) {
1383 VD->NonParmVarDeclBits.IsThisDeclarationADemotedDefinition =
1385 VD->NonParmVarDeclBits.ExceptionVar = Record.readInt();
1386 VD->NonParmVarDeclBits.NRVOVariable = Record.readInt();
1387 VD->NonParmVarDeclBits.CXXForRangeDecl = Record.readInt();
1388 VD->NonParmVarDeclBits.ObjCForDecl = Record.readInt();
1389 VD->NonParmVarDeclBits.IsInline = Record.readInt();
1390 VD->NonParmVarDeclBits.IsInlineSpecified = Record.readInt();
1391 VD->NonParmVarDeclBits.IsConstexpr = Record.readInt();
1392 VD->NonParmVarDeclBits.IsInitCapture = Record.readInt();
1393 VD->NonParmVarDeclBits.PreviousDeclInSameBlockScope = Record.readInt();
1394 VD->NonParmVarDeclBits.ImplicitParamKind = Record.readInt();
1395 VD->NonParmVarDeclBits.EscapingByref = Record.readInt();
1397 auto VarLinkage = Linkage(Record.readInt());
1398 VD->setCachedLinkage(VarLinkage);
1400 // Reconstruct the one piece of the IdentifierNamespace that we need.
1401 if (VD->getStorageClass() == SC_Extern && VarLinkage != NoLinkage &&
1402 VD->getLexicalDeclContext()->isFunctionOrMethod())
1403 VD->setLocalExternDecl();
1405 if (uint64_t Val = Record.readInt()) {
1406 VD->setInit(Record.readExpr());
1408 EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
1409 Eval->CheckedICE = true;
1410 Eval->IsICE = (Val & 1) != 0;
1411 Eval->HasConstantDestruction = (Val & 4) != 0;
1415 if (VD->hasAttr<BlocksAttr>() && VD->getType()->getAsCXXRecordDecl()) {
1416 Expr *CopyExpr = Record.readExpr();
1418 Reader.getContext().setBlockVarCopyInit(VD, CopyExpr, Record.readInt());
1421 if (VD->getStorageDuration() == SD_Static && Record.readInt())
1422 Reader.DefinitionSource[VD] = Loc.F->Kind == ModuleKind::MK_MainFile;
1425 VarNotTemplate = 0, VarTemplate, StaticDataMemberSpecialization
1427 switch ((VarKind)Record.readInt()) {
1428 case VarNotTemplate:
1429 // Only true variables (not parameters or implicit parameters) can be
1430 // merged; the other kinds are not really redeclarable at all.
1431 if (!isa<ParmVarDecl>(VD) && !isa<ImplicitParamDecl>(VD) &&
1432 !isa<VarTemplateSpecializationDecl>(VD))
1433 mergeRedeclarable(VD, Redecl);
1436 // Merged when we merge the template.
1437 VD->setDescribedVarTemplate(readDeclAs<VarTemplateDecl>());
1439 case StaticDataMemberSpecialization: { // HasMemberSpecializationInfo.
1440 auto *Tmpl = readDeclAs<VarDecl>();
1441 auto TSK = (TemplateSpecializationKind)Record.readInt();
1442 SourceLocation POI = readSourceLocation();
1443 Reader.getContext().setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);
1444 mergeRedeclarable(VD, Redecl);
1452 void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
1456 void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
1458 unsigned isObjCMethodParam = Record.readInt();
1459 unsigned scopeDepth = Record.readInt();
1460 unsigned scopeIndex = Record.readInt();
1461 unsigned declQualifier = Record.readInt();
1462 if (isObjCMethodParam) {
1463 assert(scopeDepth == 0);
1464 PD->setObjCMethodScopeInfo(scopeIndex);
1465 PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier;
1467 PD->setScopeInfo(scopeDepth, scopeIndex);
1469 PD->ParmVarDeclBits.IsKNRPromoted = Record.readInt();
1470 PD->ParmVarDeclBits.HasInheritedDefaultArg = Record.readInt();
1471 if (Record.readInt()) // hasUninstantiatedDefaultArg.
1472 PD->setUninstantiatedDefaultArg(Record.readExpr());
1474 // FIXME: If this is a redeclaration of a function from another module, handle
1475 // inheritance of default arguments.
1478 void ASTDeclReader::VisitDecompositionDecl(DecompositionDecl *DD) {
1480 auto **BDs = DD->getTrailingObjects<BindingDecl *>();
1481 for (unsigned I = 0; I != DD->NumBindings; ++I) {
1482 BDs[I] = readDeclAs<BindingDecl>();
1483 BDs[I]->setDecomposedDecl(DD);
1487 void ASTDeclReader::VisitBindingDecl(BindingDecl *BD) {
1489 BD->Binding = Record.readExpr();
1492 void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
1494 AD->setAsmString(cast<StringLiteral>(Record.readExpr()));
1495 AD->setRParenLoc(readSourceLocation());
1498 void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
1500 BD->setBody(cast_or_null<CompoundStmt>(Record.readStmt()));
1501 BD->setSignatureAsWritten(readTypeSourceInfo());
1502 unsigned NumParams = Record.readInt();
1503 SmallVector<ParmVarDecl *, 16> Params;
1504 Params.reserve(NumParams);
1505 for (unsigned I = 0; I != NumParams; ++I)
1506 Params.push_back(readDeclAs<ParmVarDecl>());
1507 BD->setParams(Params);
1509 BD->setIsVariadic(Record.readInt());
1510 BD->setBlockMissingReturnType(Record.readInt());
1511 BD->setIsConversionFromLambda(Record.readInt());
1512 BD->setDoesNotEscape(Record.readInt());
1513 BD->setCanAvoidCopyToHeap(Record.readInt());
1515 bool capturesCXXThis = Record.readInt();
1516 unsigned numCaptures = Record.readInt();
1517 SmallVector<BlockDecl::Capture, 16> captures;
1518 captures.reserve(numCaptures);
1519 for (unsigned i = 0; i != numCaptures; ++i) {
1520 auto *decl = readDeclAs<VarDecl>();
1521 unsigned flags = Record.readInt();
1522 bool byRef = (flags & 1);
1523 bool nested = (flags & 2);
1524 Expr *copyExpr = ((flags & 4) ? Record.readExpr() : nullptr);
1526 captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr));
1528 BD->setCaptures(Reader.getContext(), captures, capturesCXXThis);
1531 void ASTDeclReader::VisitCapturedDecl(CapturedDecl *CD) {
1533 unsigned ContextParamPos = Record.readInt();
1534 CD->setNothrow(Record.readInt() != 0);
1535 // Body is set by VisitCapturedStmt.
1536 for (unsigned I = 0; I < CD->NumParams; ++I) {
1537 if (I != ContextParamPos)
1538 CD->setParam(I, readDeclAs<ImplicitParamDecl>());
1540 CD->setContextParam(I, readDeclAs<ImplicitParamDecl>());
1544 void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1546 D->setLanguage((LinkageSpecDecl::LanguageIDs)Record.readInt());
1547 D->setExternLoc(readSourceLocation());
1548 D->setRBraceLoc(readSourceLocation());
1551 void ASTDeclReader::VisitExportDecl(ExportDecl *D) {
1553 D->RBraceLoc = readSourceLocation();
1556 void ASTDeclReader::VisitLabelDecl(LabelDecl *D) {
1558 D->setLocStart(readSourceLocation());
1561 void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
1562 RedeclarableResult Redecl = VisitRedeclarable(D);
1564 D->setInline(Record.readInt());
1565 D->LocStart = readSourceLocation();
1566 D->RBraceLoc = readSourceLocation();
1568 // Defer loading the anonymous namespace until we've finished merging
1569 // this namespace; loading it might load a later declaration of the
1570 // same namespace, and we have an invariant that older declarations
1571 // get merged before newer ones try to merge.
1572 GlobalDeclID AnonNamespace = 0;
1573 if (Redecl.getFirstID() == ThisDeclID) {
1574 AnonNamespace = readDeclID();
1576 // Link this namespace back to the first declaration, which has already
1577 // been deserialized.
1578 D->AnonOrFirstNamespaceAndInline.setPointer(D->getFirstDecl());
1581 mergeRedeclarable(D, Redecl);
1583 if (AnonNamespace) {
1584 // Each module has its own anonymous namespace, which is disjoint from
1585 // any other module's anonymous namespaces, so don't attach the anonymous
1586 // namespace at all.
1587 auto *Anon = cast<NamespaceDecl>(Reader.GetDecl(AnonNamespace));
1588 if (!Record.isModule())
1589 D->setAnonymousNamespace(Anon);
1593 void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1594 RedeclarableResult Redecl = VisitRedeclarable(D);
1596 D->NamespaceLoc = readSourceLocation();
1597 D->IdentLoc = readSourceLocation();
1598 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1599 D->Namespace = readDeclAs<NamedDecl>();
1600 mergeRedeclarable(D, Redecl);
1603 void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
1605 D->setUsingLoc(readSourceLocation());
1606 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1607 D->DNLoc = Record.readDeclarationNameLoc(D->getDeclName());
1608 D->FirstUsingShadow.setPointer(readDeclAs<UsingShadowDecl>());
1609 D->setTypename(Record.readInt());
1610 if (auto *Pattern = readDeclAs<NamedDecl>())
1611 Reader.getContext().setInstantiatedFromUsingDecl(D, Pattern);
1615 void ASTDeclReader::VisitUsingPackDecl(UsingPackDecl *D) {
1617 D->InstantiatedFrom = readDeclAs<NamedDecl>();
1618 auto **Expansions = D->getTrailingObjects<NamedDecl *>();
1619 for (unsigned I = 0; I != D->NumExpansions; ++I)
1620 Expansions[I] = readDeclAs<NamedDecl>();
1624 void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
1625 RedeclarableResult Redecl = VisitRedeclarable(D);
1627 D->Underlying = readDeclAs<NamedDecl>();
1628 D->IdentifierNamespace = Record.readInt();
1629 D->UsingOrNextShadow = readDeclAs<NamedDecl>();
1630 auto *Pattern = readDeclAs<UsingShadowDecl>();
1632 Reader.getContext().setInstantiatedFromUsingShadowDecl(D, Pattern);
1633 mergeRedeclarable(D, Redecl);
1636 void ASTDeclReader::VisitConstructorUsingShadowDecl(
1637 ConstructorUsingShadowDecl *D) {
1638 VisitUsingShadowDecl(D);
1639 D->NominatedBaseClassShadowDecl = readDeclAs<ConstructorUsingShadowDecl>();
1640 D->ConstructedBaseClassShadowDecl = readDeclAs<ConstructorUsingShadowDecl>();
1641 D->IsVirtual = Record.readInt();
1644 void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1646 D->UsingLoc = readSourceLocation();
1647 D->NamespaceLoc = readSourceLocation();
1648 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1649 D->NominatedNamespace = readDeclAs<NamedDecl>();
1650 D->CommonAncestor = readDeclAs<DeclContext>();
1653 void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1655 D->setUsingLoc(readSourceLocation());
1656 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1657 D->DNLoc = Record.readDeclarationNameLoc(D->getDeclName());
1658 D->EllipsisLoc = readSourceLocation();
1662 void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
1663 UnresolvedUsingTypenameDecl *D) {
1665 D->TypenameLocation = readSourceLocation();
1666 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1667 D->EllipsisLoc = readSourceLocation();
1671 void ASTDeclReader::ReadCXXDefinitionData(
1672 struct CXXRecordDecl::DefinitionData &Data, const CXXRecordDecl *D) {
1673 #define FIELD(Name, Width, Merge) \
1674 Data.Name = Record.readInt();
1675 #include "clang/AST/CXXRecordDeclDefinitionBits.def"
1677 // Note: the caller has deserialized the IsLambda bit already.
1678 Data.ODRHash = Record.readInt();
1679 Data.HasODRHash = true;
1681 if (Record.readInt())
1682 Reader.DefinitionSource[D] = Loc.F->Kind == ModuleKind::MK_MainFile;
1684 Data.NumBases = Record.readInt();
1686 Data.Bases = ReadGlobalOffset();
1687 Data.NumVBases = Record.readInt();
1689 Data.VBases = ReadGlobalOffset();
1691 Record.readUnresolvedSet(Data.Conversions);
1692 Data.ComputedVisibleConversions = Record.readInt();
1693 if (Data.ComputedVisibleConversions)
1694 Record.readUnresolvedSet(Data.VisibleConversions);
1695 assert(Data.Definition && "Data.Definition should be already set!");
1696 Data.FirstFriend = readDeclID();
1698 if (Data.IsLambda) {
1699 using Capture = LambdaCapture;
1701 auto &Lambda = static_cast<CXXRecordDecl::LambdaDefinitionData &>(Data);
1702 Lambda.Dependent = Record.readInt();
1703 Lambda.IsGenericLambda = Record.readInt();
1704 Lambda.CaptureDefault = Record.readInt();
1705 Lambda.NumCaptures = Record.readInt();
1706 Lambda.NumExplicitCaptures = Record.readInt();
1707 Lambda.HasKnownInternalLinkage = Record.readInt();
1708 Lambda.ManglingNumber = Record.readInt();
1709 Lambda.ContextDecl = readDeclID();
1710 Lambda.Captures = (Capture *)Reader.getContext().Allocate(
1711 sizeof(Capture) * Lambda.NumCaptures);
1712 Capture *ToCapture = Lambda.Captures;
1713 Lambda.MethodTyInfo = readTypeSourceInfo();
1714 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
1715 SourceLocation Loc = readSourceLocation();
1716 bool IsImplicit = Record.readInt();
1717 auto Kind = static_cast<LambdaCaptureKind>(Record.readInt());
1722 *ToCapture++ = Capture(Loc, IsImplicit, Kind, nullptr,SourceLocation());
1726 auto *Var = readDeclAs<VarDecl>();
1727 SourceLocation EllipsisLoc = readSourceLocation();
1728 *ToCapture++ = Capture(Loc, IsImplicit, Kind, Var, EllipsisLoc);
1735 void ASTDeclReader::MergeDefinitionData(
1736 CXXRecordDecl *D, struct CXXRecordDecl::DefinitionData &&MergeDD) {
1737 assert(D->DefinitionData &&
1738 "merging class definition into non-definition");
1739 auto &DD = *D->DefinitionData;
1741 if (DD.Definition != MergeDD.Definition) {
1742 // Track that we merged the definitions.
1743 Reader.MergedDeclContexts.insert(std::make_pair(MergeDD.Definition,
1745 Reader.PendingDefinitions.erase(MergeDD.Definition);
1746 MergeDD.Definition->setCompleteDefinition(false);
1747 Reader.mergeDefinitionVisibility(DD.Definition, MergeDD.Definition);
1748 assert(Reader.Lookups.find(MergeDD.Definition) == Reader.Lookups.end() &&
1749 "already loaded pending lookups for merged definition");
1752 auto PFDI = Reader.PendingFakeDefinitionData.find(&DD);
1753 if (PFDI != Reader.PendingFakeDefinitionData.end() &&
1754 PFDI->second == ASTReader::PendingFakeDefinitionKind::Fake) {
1755 // We faked up this definition data because we found a class for which we'd
1756 // not yet loaded the definition. Replace it with the real thing now.
1757 assert(!DD.IsLambda && !MergeDD.IsLambda && "faked up lambda definition?");
1758 PFDI->second = ASTReader::PendingFakeDefinitionKind::FakeLoaded;
1760 // Don't change which declaration is the definition; that is required
1761 // to be invariant once we select it.
1762 auto *Def = DD.Definition;
1763 DD = std::move(MergeDD);
1764 DD.Definition = Def;
1768 bool DetectedOdrViolation = false;
1770 #define FIELD(Name, Width, Merge) Merge(Name)
1771 #define MERGE_OR(Field) DD.Field |= MergeDD.Field;
1772 #define NO_MERGE(Field) \
1773 DetectedOdrViolation |= DD.Field != MergeDD.Field; \
1775 #include "clang/AST/CXXRecordDeclDefinitionBits.def"
1780 if (DD.NumBases != MergeDD.NumBases || DD.NumVBases != MergeDD.NumVBases)
1781 DetectedOdrViolation = true;
1782 // FIXME: Issue a diagnostic if the base classes don't match when we come
1783 // to lazily load them.
1785 // FIXME: Issue a diagnostic if the list of conversion functions doesn't
1786 // match when we come to lazily load them.
1787 if (MergeDD.ComputedVisibleConversions && !DD.ComputedVisibleConversions) {
1788 DD.VisibleConversions = std::move(MergeDD.VisibleConversions);
1789 DD.ComputedVisibleConversions = true;
1792 // FIXME: Issue a diagnostic if FirstFriend doesn't match when we come to
1796 // FIXME: ODR-checking for merging lambdas (this happens, for instance,
1797 // when they occur within the body of a function template specialization).
1800 if (D->getODRHash() != MergeDD.ODRHash) {
1801 DetectedOdrViolation = true;
1804 if (DetectedOdrViolation)
1805 Reader.PendingOdrMergeFailures[DD.Definition].push_back(
1806 {MergeDD.Definition, &MergeDD});
1809 void ASTDeclReader::ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update) {
1810 struct CXXRecordDecl::DefinitionData *DD;
1811 ASTContext &C = Reader.getContext();
1813 // Determine whether this is a lambda closure type, so that we can
1814 // allocate the appropriate DefinitionData structure.
1815 bool IsLambda = Record.readInt();
1817 DD = new (C) CXXRecordDecl::LambdaDefinitionData(D, nullptr, false, false,
1820 DD = new (C) struct CXXRecordDecl::DefinitionData(D);
1822 CXXRecordDecl *Canon = D->getCanonicalDecl();
1823 // Set decl definition data before reading it, so that during deserialization
1824 // when we read CXXRecordDecl, it already has definition data and we don't
1826 if (!Canon->DefinitionData)
1827 Canon->DefinitionData = DD;
1828 D->DefinitionData = Canon->DefinitionData;
1829 ReadCXXDefinitionData(*DD, D);
1831 // We might already have a different definition for this record. This can
1832 // happen either because we're reading an update record, or because we've
1833 // already done some merging. Either way, just merge into it.
1834 if (Canon->DefinitionData != DD) {
1835 MergeDefinitionData(Canon, std::move(*DD));
1839 // Mark this declaration as being a definition.
1840 D->setCompleteDefinition(true);
1842 // If this is not the first declaration or is an update record, we can have
1843 // other redeclarations already. Make a note that we need to propagate the
1844 // DefinitionData pointer onto them.
1845 if (Update || Canon != D)
1846 Reader.PendingDefinitions.insert(D);
1849 ASTDeclReader::RedeclarableResult
1850 ASTDeclReader::VisitCXXRecordDeclImpl(CXXRecordDecl *D) {
1851 RedeclarableResult Redecl = VisitRecordDeclImpl(D);
1853 ASTContext &C = Reader.getContext();
1856 CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
1858 switch ((CXXRecKind)Record.readInt()) {
1859 case CXXRecNotTemplate:
1860 // Merged when we merge the folding set entry in the primary template.
1861 if (!isa<ClassTemplateSpecializationDecl>(D))
1862 mergeRedeclarable(D, Redecl);
1864 case CXXRecTemplate: {
1865 // Merged when we merge the template.
1866 auto *Template = readDeclAs<ClassTemplateDecl>();
1867 D->TemplateOrInstantiation = Template;
1868 if (!Template->getTemplatedDecl()) {
1869 // We've not actually loaded the ClassTemplateDecl yet, because we're
1870 // currently being loaded as its pattern. Rely on it to set up our
1871 // TypeForDecl (see VisitClassTemplateDecl).
1873 // Beware: we do not yet know our canonical declaration, and may still
1874 // get merged once the surrounding class template has got off the ground.
1879 case CXXRecMemberSpecialization: {
1880 auto *RD = readDeclAs<CXXRecordDecl>();
1881 auto TSK = (TemplateSpecializationKind)Record.readInt();
1882 SourceLocation POI = readSourceLocation();
1883 MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
1884 MSI->setPointOfInstantiation(POI);
1885 D->TemplateOrInstantiation = MSI;
1886 mergeRedeclarable(D, Redecl);
1891 bool WasDefinition = Record.readInt();
1893 ReadCXXRecordDefinition(D, /*Update*/false);
1895 // Propagate DefinitionData pointer from the canonical declaration.
1896 D->DefinitionData = D->getCanonicalDecl()->DefinitionData;
1898 // Lazily load the key function to avoid deserializing every method so we can
1900 if (WasDefinition) {
1901 DeclID KeyFn = readDeclID();
1902 if (KeyFn && D->isCompleteDefinition())
1903 // FIXME: This is wrong for the ARM ABI, where some other module may have
1904 // made this function no longer be a key function. We need an update
1905 // record or similar for that case.
1906 C.KeyFunctions[D] = KeyFn;
1912 void ASTDeclReader::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
1913 D->setExplicitSpecifier(Record.readExplicitSpec());
1914 VisitFunctionDecl(D);
1915 D->setIsCopyDeductionCandidate(Record.readInt());
1918 void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
1919 VisitFunctionDecl(D);
1921 unsigned NumOverridenMethods = Record.readInt();
1922 if (D->isCanonicalDecl()) {
1923 while (NumOverridenMethods--) {
1924 // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
1925 // MD may be initializing.
1926 if (auto *MD = readDeclAs<CXXMethodDecl>())
1927 Reader.getContext().addOverriddenMethod(D, MD->getCanonicalDecl());
1930 // We don't care about which declarations this used to override; we get
1931 // the relevant information from the canonical declaration.
1932 Record.skipInts(NumOverridenMethods);
1936 void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1937 // We need the inherited constructor information to merge the declaration,
1938 // so we have to read it before we call VisitCXXMethodDecl.
1939 D->setExplicitSpecifier(Record.readExplicitSpec());
1940 if (D->isInheritingConstructor()) {
1941 auto *Shadow = readDeclAs<ConstructorUsingShadowDecl>();
1942 auto *Ctor = readDeclAs<CXXConstructorDecl>();
1943 *D->getTrailingObjects<InheritedConstructor>() =
1944 InheritedConstructor(Shadow, Ctor);
1947 VisitCXXMethodDecl(D);
1950 void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1951 VisitCXXMethodDecl(D);
1953 if (auto *OperatorDelete = readDeclAs<FunctionDecl>()) {
1954 CXXDestructorDecl *Canon = D->getCanonicalDecl();
1955 auto *ThisArg = Record.readExpr();
1956 // FIXME: Check consistency if we have an old and new operator delete.
1957 if (!Canon->OperatorDelete) {
1958 Canon->OperatorDelete = OperatorDelete;
1959 Canon->OperatorDeleteThisArg = ThisArg;
1964 void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
1965 D->setExplicitSpecifier(Record.readExplicitSpec());
1966 VisitCXXMethodDecl(D);
1969 void ASTDeclReader::VisitImportDecl(ImportDecl *D) {
1971 D->ImportedAndComplete.setPointer(readModule());
1972 D->ImportedAndComplete.setInt(Record.readInt());
1973 auto *StoredLocs = D->getTrailingObjects<SourceLocation>();
1974 for (unsigned I = 0, N = Record.back(); I != N; ++I)
1975 StoredLocs[I] = readSourceLocation();
1976 Record.skipInts(1); // The number of stored source locations.
1979 void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
1981 D->setColonLoc(readSourceLocation());
1984 void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
1986 if (Record.readInt()) // hasFriendDecl
1987 D->Friend = readDeclAs<NamedDecl>();
1989 D->Friend = readTypeSourceInfo();
1990 for (unsigned i = 0; i != D->NumTPLists; ++i)
1991 D->getTrailingObjects<TemplateParameterList *>()[i] =
1992 Record.readTemplateParameterList();
1993 D->NextFriend = readDeclID();
1994 D->UnsupportedFriend = (Record.readInt() != 0);
1995 D->FriendLoc = readSourceLocation();
1998 void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
2000 unsigned NumParams = Record.readInt();
2001 D->NumParams = NumParams;
2002 D->Params = new TemplateParameterList*[NumParams];
2003 for (unsigned i = 0; i != NumParams; ++i)
2004 D->Params[i] = Record.readTemplateParameterList();
2005 if (Record.readInt()) // HasFriendDecl
2006 D->Friend = readDeclAs<NamedDecl>();
2008 D->Friend = readTypeSourceInfo();
2009 D->FriendLoc = readSourceLocation();
2012 DeclID ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
2015 DeclID PatternID = readDeclID();
2016 auto *TemplatedDecl = cast_or_null<NamedDecl>(Reader.GetDecl(PatternID));
2017 TemplateParameterList *TemplateParams = Record.readTemplateParameterList();
2018 D->init(TemplatedDecl, TemplateParams);
2023 void ASTDeclReader::VisitConceptDecl(ConceptDecl *D) {
2024 VisitTemplateDecl(D);
2025 D->ConstraintExpr = Record.readExpr();
2029 void ASTDeclReader::VisitRequiresExprBodyDecl(RequiresExprBodyDecl *D) {
2032 ASTDeclReader::RedeclarableResult
2033 ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
2034 RedeclarableResult Redecl = VisitRedeclarable(D);
2036 // Make sure we've allocated the Common pointer first. We do this before
2037 // VisitTemplateDecl so that getCommonPtr() can be used during initialization.
2038 RedeclarableTemplateDecl *CanonD = D->getCanonicalDecl();
2039 if (!CanonD->Common) {
2040 CanonD->Common = CanonD->newCommon(Reader.getContext());
2041 Reader.PendingDefinitions.insert(CanonD);
2043 D->Common = CanonD->Common;
2045 // If this is the first declaration of the template, fill in the information
2046 // for the 'common' pointer.
2047 if (ThisDeclID == Redecl.getFirstID()) {
2048 if (auto *RTD = readDeclAs<RedeclarableTemplateDecl>()) {
2049 assert(RTD->getKind() == D->getKind() &&
2050 "InstantiatedFromMemberTemplate kind mismatch");
2051 D->setInstantiatedFromMemberTemplate(RTD);
2052 if (Record.readInt())
2053 D->setMemberSpecialization();
2057 DeclID PatternID = VisitTemplateDecl(D);
2058 D->IdentifierNamespace = Record.readInt();
2060 mergeRedeclarable(D, Redecl, PatternID);
2062 // If we merged the template with a prior declaration chain, merge the common
2064 // FIXME: Actually merge here, don't just overwrite.
2065 D->Common = D->getCanonicalDecl()->Common;
2070 void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
2071 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2073 if (ThisDeclID == Redecl.getFirstID()) {
2074 // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
2075 // the specializations.
2076 SmallVector<serialization::DeclID, 32> SpecIDs;
2077 readDeclIDList(SpecIDs);
2078 ASTDeclReader::AddLazySpecializations(D, SpecIDs);
2081 if (D->getTemplatedDecl()->TemplateOrInstantiation) {
2082 // We were loaded before our templated declaration was. We've not set up
2083 // its corresponding type yet (see VisitCXXRecordDeclImpl), so reconstruct
2085 Reader.getContext().getInjectedClassNameType(
2086 D->getTemplatedDecl(), D->getInjectedClassNameSpecialization());
2090 void ASTDeclReader::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
2091 llvm_unreachable("BuiltinTemplates are not serialized");
2094 /// TODO: Unify with ClassTemplateDecl version?
2095 /// May require unifying ClassTemplateDecl and
2096 /// VarTemplateDecl beyond TemplateDecl...
2097 void ASTDeclReader::VisitVarTemplateDecl(VarTemplateDecl *D) {
2098 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2100 if (ThisDeclID == Redecl.getFirstID()) {
2101 // This VarTemplateDecl owns a CommonPtr; read it to keep track of all of
2102 // the specializations.
2103 SmallVector<serialization::DeclID, 32> SpecIDs;
2104 readDeclIDList(SpecIDs);
2105 ASTDeclReader::AddLazySpecializations(D, SpecIDs);
2109 ASTDeclReader::RedeclarableResult
2110 ASTDeclReader::VisitClassTemplateSpecializationDeclImpl(
2111 ClassTemplateSpecializationDecl *D) {
2112 RedeclarableResult Redecl = VisitCXXRecordDeclImpl(D);
2114 ASTContext &C = Reader.getContext();
2115 if (Decl *InstD = readDecl()) {
2116 if (auto *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
2117 D->SpecializedTemplate = CTD;
2119 SmallVector<TemplateArgument, 8> TemplArgs;
2120 Record.readTemplateArgumentList(TemplArgs);
2121 TemplateArgumentList *ArgList
2122 = TemplateArgumentList::CreateCopy(C, TemplArgs);
2124 new (C) ClassTemplateSpecializationDecl::
2125 SpecializedPartialSpecialization();
2126 PS->PartialSpecialization
2127 = cast<ClassTemplatePartialSpecializationDecl>(InstD);
2128 PS->TemplateArgs = ArgList;
2129 D->SpecializedTemplate = PS;
2133 SmallVector<TemplateArgument, 8> TemplArgs;
2134 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
2135 D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs);
2136 D->PointOfInstantiation = readSourceLocation();
2137 D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
2139 bool writtenAsCanonicalDecl = Record.readInt();
2140 if (writtenAsCanonicalDecl) {
2141 auto *CanonPattern = readDeclAs<ClassTemplateDecl>();
2142 if (D->isCanonicalDecl()) { // It's kept in the folding set.
2143 // Set this as, or find, the canonical declaration for this specialization
2144 ClassTemplateSpecializationDecl *CanonSpec;
2145 if (auto *Partial = dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
2146 CanonSpec = CanonPattern->getCommonPtr()->PartialSpecializations
2147 .GetOrInsertNode(Partial);
2150 CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
2152 // If there was already a canonical specialization, merge into it.
2153 if (CanonSpec != D) {
2154 mergeRedeclarable<TagDecl>(D, CanonSpec, Redecl);
2156 // This declaration might be a definition. Merge with any existing
2158 if (auto *DDD = D->DefinitionData) {
2159 if (CanonSpec->DefinitionData)
2160 MergeDefinitionData(CanonSpec, std::move(*DDD));
2162 CanonSpec->DefinitionData = D->DefinitionData;
2164 D->DefinitionData = CanonSpec->DefinitionData;
2170 if (TypeSourceInfo *TyInfo = readTypeSourceInfo()) {
2171 auto *ExplicitInfo =
2172 new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
2173 ExplicitInfo->TypeAsWritten = TyInfo;
2174 ExplicitInfo->ExternLoc = readSourceLocation();
2175 ExplicitInfo->TemplateKeywordLoc = readSourceLocation();
2176 D->ExplicitInfo = ExplicitInfo;
2182 void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
2183 ClassTemplatePartialSpecializationDecl *D) {
2184 // We need to read the template params first because redeclarable is going to
2185 // need them for profiling
2186 TemplateParameterList *Params = Record.readTemplateParameterList();
2187 D->TemplateParams = Params;
2188 D->ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2190 RedeclarableResult Redecl = VisitClassTemplateSpecializationDeclImpl(D);
2192 // These are read/set from/to the first declaration.
2193 if (ThisDeclID == Redecl.getFirstID()) {
2194 D->InstantiatedFromMember.setPointer(
2195 readDeclAs<ClassTemplatePartialSpecializationDecl>());
2196 D->InstantiatedFromMember.setInt(Record.readInt());
2200 void ASTDeclReader::VisitClassScopeFunctionSpecializationDecl(
2201 ClassScopeFunctionSpecializationDecl *D) {
2203 D->Specialization = readDeclAs<CXXMethodDecl>();
2204 if (Record.readInt())
2205 D->TemplateArgs = Record.readASTTemplateArgumentListInfo();
2208 void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
2209 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2211 if (ThisDeclID == Redecl.getFirstID()) {
2212 // This FunctionTemplateDecl owns a CommonPtr; read it.
2213 SmallVector<serialization::DeclID, 32> SpecIDs;
2214 readDeclIDList(SpecIDs);
2215 ASTDeclReader::AddLazySpecializations(D, SpecIDs);
2219 /// TODO: Unify with ClassTemplateSpecializationDecl version?
2220 /// May require unifying ClassTemplate(Partial)SpecializationDecl and
2221 /// VarTemplate(Partial)SpecializationDecl with a new data
2222 /// structure Template(Partial)SpecializationDecl, and
2223 /// using Template(Partial)SpecializationDecl as input type.
2224 ASTDeclReader::RedeclarableResult
2225 ASTDeclReader::VisitVarTemplateSpecializationDeclImpl(
2226 VarTemplateSpecializationDecl *D) {
2227 RedeclarableResult Redecl = VisitVarDeclImpl(D);
2229 ASTContext &C = Reader.getContext();
2230 if (Decl *InstD = readDecl()) {
2231 if (auto *VTD = dyn_cast<VarTemplateDecl>(InstD)) {
2232 D->SpecializedTemplate = VTD;
2234 SmallVector<TemplateArgument, 8> TemplArgs;
2235 Record.readTemplateArgumentList(TemplArgs);
2236 TemplateArgumentList *ArgList = TemplateArgumentList::CreateCopy(
2240 VarTemplateSpecializationDecl::SpecializedPartialSpecialization();
2241 PS->PartialSpecialization =
2242 cast<VarTemplatePartialSpecializationDecl>(InstD);
2243 PS->TemplateArgs = ArgList;
2244 D->SpecializedTemplate = PS;
2249 if (TypeSourceInfo *TyInfo = readTypeSourceInfo()) {
2250 auto *ExplicitInfo =
2251 new (C) VarTemplateSpecializationDecl::ExplicitSpecializationInfo;
2252 ExplicitInfo->TypeAsWritten = TyInfo;
2253 ExplicitInfo->ExternLoc = readSourceLocation();
2254 ExplicitInfo->TemplateKeywordLoc = readSourceLocation();
2255 D->ExplicitInfo = ExplicitInfo;
2258 SmallVector<TemplateArgument, 8> TemplArgs;
2259 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
2260 D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs);
2261 D->PointOfInstantiation = readSourceLocation();
2262 D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
2263 D->IsCompleteDefinition = Record.readInt();
2265 bool writtenAsCanonicalDecl = Record.readInt();
2266 if (writtenAsCanonicalDecl) {
2267 auto *CanonPattern = readDeclAs<VarTemplateDecl>();
2268 if (D->isCanonicalDecl()) { // It's kept in the folding set.
2269 // FIXME: If it's already present, merge it.
2270 if (auto *Partial = dyn_cast<VarTemplatePartialSpecializationDecl>(D)) {
2271 CanonPattern->getCommonPtr()->PartialSpecializations
2272 .GetOrInsertNode(Partial);
2274 CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
2282 /// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2283 /// May require unifying ClassTemplate(Partial)SpecializationDecl and
2284 /// VarTemplate(Partial)SpecializationDecl with a new data
2285 /// structure Template(Partial)SpecializationDecl, and
2286 /// using Template(Partial)SpecializationDecl as input type.
2287 void ASTDeclReader::VisitVarTemplatePartialSpecializationDecl(
2288 VarTemplatePartialSpecializationDecl *D) {
2289 TemplateParameterList *Params = Record.readTemplateParameterList();
2290 D->TemplateParams = Params;
2291 D->ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2293 RedeclarableResult Redecl = VisitVarTemplateSpecializationDeclImpl(D);
2295 // These are read/set from/to the first declaration.
2296 if (ThisDeclID == Redecl.getFirstID()) {
2297 D->InstantiatedFromMember.setPointer(
2298 readDeclAs<VarTemplatePartialSpecializationDecl>());
2299 D->InstantiatedFromMember.setInt(Record.readInt());
2303 void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
2306 D->setDeclaredWithTypename(Record.readInt());
2308 if (Record.readBool()) {
2309 NestedNameSpecifierLoc NNS = Record.readNestedNameSpecifierLoc();
2310 DeclarationNameInfo DN = Record.readDeclarationNameInfo();
2311 ConceptDecl *NamedConcept = Record.readDeclAs<ConceptDecl>();
2312 const ASTTemplateArgumentListInfo *ArgsAsWritten = nullptr;
2313 if (Record.readBool())
2314 ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2315 Expr *ImmediatelyDeclaredConstraint = Record.readExpr();
2316 D->setTypeConstraint(NNS, DN, /*FoundDecl=*/nullptr, NamedConcept,
2317 ArgsAsWritten, ImmediatelyDeclaredConstraint);
2318 if ((D->ExpandedParameterPack = Record.readInt()))
2319 D->NumExpanded = Record.readInt();
2322 if (Record.readInt())
2323 D->setDefaultArgument(readTypeSourceInfo());
2326 void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
2327 VisitDeclaratorDecl(D);
2328 // TemplateParmPosition.
2329 D->setDepth(Record.readInt());
2330 D->setPosition(Record.readInt());
2331 if (D->hasPlaceholderTypeConstraint())
2332 D->setPlaceholderTypeConstraint(Record.readExpr());
2333 if (D->isExpandedParameterPack()) {
2334 auto TypesAndInfos =
2335 D->getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
2336 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2337 new (&TypesAndInfos[I].first) QualType(Record.readType());
2338 TypesAndInfos[I].second = readTypeSourceInfo();
2341 // Rest of NonTypeTemplateParmDecl.
2342 D->ParameterPack = Record.readInt();
2343 if (Record.readInt())
2344 D->setDefaultArgument(Record.readExpr());
2348 void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
2349 VisitTemplateDecl(D);
2350 // TemplateParmPosition.
2351 D->setDepth(Record.readInt());
2352 D->setPosition(Record.readInt());
2353 if (D->isExpandedParameterPack()) {
2354 auto **Data = D->getTrailingObjects<TemplateParameterList *>();
2355 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2357 Data[I] = Record.readTemplateParameterList();
2359 // Rest of TemplateTemplateParmDecl.
2360 D->ParameterPack = Record.readInt();
2361 if (Record.readInt())
2362 D->setDefaultArgument(Reader.getContext(),
2363 Record.readTemplateArgumentLoc());
2367 void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
2368 VisitRedeclarableTemplateDecl(D);
2371 void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
2373 D->AssertExprAndFailed.setPointer(Record.readExpr());
2374 D->AssertExprAndFailed.setInt(Record.readInt());
2375 D->Message = cast_or_null<StringLiteral>(Record.readExpr());
2376 D->RParenLoc = readSourceLocation();
2379 void ASTDeclReader::VisitEmptyDecl(EmptyDecl *D) {
2383 void ASTDeclReader::VisitLifetimeExtendedTemporaryDecl(
2384 LifetimeExtendedTemporaryDecl *D) {
2386 D->ExtendingDecl = readDeclAs<ValueDecl>();
2387 D->ExprWithTemporary = Record.readStmt();
2388 if (Record.readInt())
2389 D->Value = new (D->getASTContext()) APValue(Record.readAPValue());
2390 D->ManglingNumber = Record.readInt();
2394 std::pair<uint64_t, uint64_t>
2395 ASTDeclReader::VisitDeclContext(DeclContext *DC) {
2396 uint64_t LexicalOffset = ReadLocalOffset();
2397 uint64_t VisibleOffset = ReadLocalOffset();
2398 return std::make_pair(LexicalOffset, VisibleOffset);
2401 template <typename T>
2402 ASTDeclReader::RedeclarableResult
2403 ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
2404 DeclID FirstDeclID = readDeclID();
2405 Decl *MergeWith = nullptr;
2407 bool IsKeyDecl = ThisDeclID == FirstDeclID;
2408 bool IsFirstLocalDecl = false;
2410 uint64_t RedeclOffset = 0;
2412 // 0 indicates that this declaration was the only declaration of its entity,
2413 // and is used for space optimization.
2414 if (FirstDeclID == 0) {
2415 FirstDeclID = ThisDeclID;
2417 IsFirstLocalDecl = true;
2418 } else if (unsigned N = Record.readInt()) {
2419 // This declaration was the first local declaration, but may have imported
2420 // other declarations.
2422 IsFirstLocalDecl = true;
2424 // We have some declarations that must be before us in our redeclaration
2425 // chain. Read them now, and remember that we ought to merge with one of
2427 // FIXME: Provide a known merge target to the second and subsequent such
2429 for (unsigned I = 0; I != N - 1; ++I)
2430 MergeWith = readDecl();
2432 RedeclOffset = ReadLocalOffset();
2434 // This declaration was not the first local declaration. Read the first
2435 // local declaration now, to trigger the import of other redeclarations.
2439 auto *FirstDecl = cast_or_null<T>(Reader.GetDecl(FirstDeclID));
2440 if (FirstDecl != D) {
2441 // We delay loading of the redeclaration chain to avoid deeply nested calls.
2442 // We temporarily set the first (canonical) declaration as the previous one
2443 // which is the one that matters and mark the real previous DeclID to be
2444 // loaded & attached later on.
2445 D->RedeclLink = Redeclarable<T>::PreviousDeclLink(FirstDecl);
2446 D->First = FirstDecl->getCanonicalDecl();
2449 auto *DAsT = static_cast<T *>(D);
2451 // Note that we need to load local redeclarations of this decl and build a
2452 // decl chain for them. This must happen *after* we perform the preloading
2453 // above; this ensures that the redeclaration chain is built in the correct
2455 if (IsFirstLocalDecl)
2456 Reader.PendingDeclChains.push_back(std::make_pair(DAsT, RedeclOffset));
2458 return RedeclarableResult(MergeWith, FirstDeclID, IsKeyDecl);
2461 /// Attempts to merge the given declaration (D) with another declaration
2462 /// of the same entity.
2463 template<typename T>
2464 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase,
2465 RedeclarableResult &Redecl,
2466 DeclID TemplatePatternID) {
2467 // If modules are not available, there is no reason to perform this merge.
2468 if (!Reader.getContext().getLangOpts().Modules)
2471 // If we're not the canonical declaration, we don't need to merge.
2472 if (!DBase->isFirstDecl())
2475 auto *D = static_cast<T *>(DBase);
2477 if (auto *Existing = Redecl.getKnownMergeTarget())
2478 // We already know of an existing declaration we should merge with.
2479 mergeRedeclarable(D, cast<T>(Existing), Redecl, TemplatePatternID);
2480 else if (FindExistingResult ExistingRes = findExisting(D))
2481 if (T *Existing = ExistingRes)
2482 mergeRedeclarable(D, Existing, Redecl, TemplatePatternID);
2485 /// "Cast" to type T, asserting if we don't have an implicit conversion.
2486 /// We use this to put code in a template that will only be valid for certain
2488 template<typename T> static T assert_cast(T t) { return t; }
2489 template<typename T> static T assert_cast(...) {
2490 llvm_unreachable("bad assert_cast");
2493 /// Merge together the pattern declarations from two template
2495 void ASTDeclReader::mergeTemplatePattern(RedeclarableTemplateDecl *D,
2496 RedeclarableTemplateDecl *Existing,
2497 DeclID DsID, bool IsKeyDecl) {
2498 auto *DPattern = D->getTemplatedDecl();
2499 auto *ExistingPattern = Existing->getTemplatedDecl();
2500 RedeclarableResult Result(/*MergeWith*/ ExistingPattern,
2501 DPattern->getCanonicalDecl()->getGlobalID(),
2504 if (auto *DClass = dyn_cast<CXXRecordDecl>(DPattern)) {
2505 // Merge with any existing definition.
2506 // FIXME: This is duplicated in several places. Refactor.
2507 auto *ExistingClass =
2508 cast<CXXRecordDecl>(ExistingPattern)->getCanonicalDecl();
2509 if (auto *DDD = DClass->DefinitionData) {
2510 if (ExistingClass->DefinitionData) {
2511 MergeDefinitionData(ExistingClass, std::move(*DDD));
2513 ExistingClass->DefinitionData = DClass->DefinitionData;
2514 // We may have skipped this before because we thought that DClass
2515 // was the canonical declaration.
2516 Reader.PendingDefinitions.insert(DClass);
2519 DClass->DefinitionData = ExistingClass->DefinitionData;
2521 return mergeRedeclarable(DClass, cast<TagDecl>(ExistingPattern),
2524 if (auto *DFunction = dyn_cast<FunctionDecl>(DPattern))
2525 return mergeRedeclarable(DFunction, cast<FunctionDecl>(ExistingPattern),
2527 if (auto *DVar = dyn_cast<VarDecl>(DPattern))
2528 return mergeRedeclarable(DVar, cast<VarDecl>(ExistingPattern), Result);
2529 if (auto *DAlias = dyn_cast<TypeAliasDecl>(DPattern))
2530 return mergeRedeclarable(DAlias, cast<TypedefNameDecl>(ExistingPattern),
2532 llvm_unreachable("merged an unknown kind of redeclarable template");
2535 /// Attempts to merge the given declaration (D) with another declaration
2536 /// of the same entity.
2537 template<typename T>
2538 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase, T *Existing,
2539 RedeclarableResult &Redecl,
2540 DeclID TemplatePatternID) {
2541 auto *D = static_cast<T *>(DBase);
2542 T *ExistingCanon = Existing->getCanonicalDecl();
2543 T *DCanon = D->getCanonicalDecl();
2544 if (ExistingCanon != DCanon) {
2545 assert(DCanon->getGlobalID() == Redecl.getFirstID() &&
2546 "already merged this declaration");
2548 // Have our redeclaration link point back at the canonical declaration
2549 // of the existing declaration, so that this declaration has the
2550 // appropriate canonical declaration.
2551 D->RedeclLink = Redeclarable<T>::PreviousDeclLink(ExistingCanon);
2552 D->First = ExistingCanon;
2553 ExistingCanon->Used |= D->Used;
2556 // When we merge a namespace, update its pointer to the first namespace.
2557 // We cannot have loaded any redeclarations of this declaration yet, so
2558 // there's nothing else that needs to be updated.
2559 if (auto *Namespace = dyn_cast<NamespaceDecl>(D))
2560 Namespace->AnonOrFirstNamespaceAndInline.setPointer(
2561 assert_cast<NamespaceDecl*>(ExistingCanon));
2563 // When we merge a template, merge its pattern.
2564 if (auto *DTemplate = dyn_cast<RedeclarableTemplateDecl>(D))
2565 mergeTemplatePattern(
2566 DTemplate, assert_cast<RedeclarableTemplateDecl*>(ExistingCanon),
2567 TemplatePatternID, Redecl.isKeyDecl());
2569 // If this declaration is a key declaration, make a note of that.
2570 if (Redecl.isKeyDecl())
2571 Reader.KeyDecls[ExistingCanon].push_back(Redecl.getFirstID());
2575 /// ODR-like semantics for C/ObjC allow us to merge tag types and a structural
2576 /// check in Sema guarantees the types can be merged (see C11 6.2.7/1 or C89
2577 /// 6.1.2.6/1). Although most merging is done in Sema, we need to guarantee
2578 /// that some types are mergeable during deserialization, otherwise name
2579 /// lookup fails. This is the case for EnumConstantDecl.
2580 static bool allowODRLikeMergeInC(NamedDecl *ND) {
2583 // TODO: implement merge for other necessary decls.
2584 if (isa<EnumConstantDecl>(ND))
2589 /// Attempts to merge LifetimeExtendedTemporaryDecl with
2590 /// identical class definitions from two different modules.
2591 void ASTDeclReader::mergeMergeable(LifetimeExtendedTemporaryDecl *D) {
2592 // If modules are not available, there is no reason to perform this merge.
2593 if (!Reader.getContext().getLangOpts().Modules)
2596 LifetimeExtendedTemporaryDecl *LETDecl = D;
2598 LifetimeExtendedTemporaryDecl *&LookupResult =
2599 Reader.LETemporaryForMerging[std::make_pair(
2600 LETDecl->getExtendingDecl(), LETDecl->getManglingNumber())];
2602 Reader.getContext().setPrimaryMergedDecl(LETDecl,
2603 LookupResult->getCanonicalDecl());
2605 LookupResult = LETDecl;
2608 /// Attempts to merge the given declaration (D) with another declaration
2609 /// of the same entity, for the case where the entity is not actually
2610 /// redeclarable. This happens, for instance, when merging the fields of
2611 /// identical class definitions from two different modules.
2612 template<typename T>
2613 void ASTDeclReader::mergeMergeable(Mergeable<T> *D) {
2614 // If modules are not available, there is no reason to perform this merge.
2615 if (!Reader.getContext().getLangOpts().Modules)
2618 // ODR-based merging is performed in C++ and in some cases (tag types) in C.
2619 // Note that C identically-named things in different translation units are
2620 // not redeclarations, but may still have compatible types, where ODR-like
2621 // semantics may apply.
2622 if (!Reader.getContext().getLangOpts().CPlusPlus &&
2623 !allowODRLikeMergeInC(dyn_cast<NamedDecl>(static_cast<T*>(D))))
2626 if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D)))
2627 if (T *Existing = ExistingRes)
2628 Reader.getContext().setPrimaryMergedDecl(static_cast<T *>(D),
2629 Existing->getCanonicalDecl());
2632 void ASTDeclReader::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
2634 unsigned NumVars = D->varlist_size();
2635 SmallVector<Expr *, 16> Vars;
2636 Vars.reserve(NumVars);
2637 for (unsigned i = 0; i != NumVars; ++i) {
2638 Vars.push_back(Record.readExpr());
2643 void ASTDeclReader::VisitOMPAllocateDecl(OMPAllocateDecl *D) {
2645 unsigned NumVars = D->varlist_size();
2646 unsigned NumClauses = D->clauselist_size();
2647 SmallVector<Expr *, 16> Vars;
2648 Vars.reserve(NumVars);
2649 for (unsigned i = 0; i != NumVars; ++i) {
2650 Vars.push_back(Record.readExpr());
2653 SmallVector<OMPClause *, 8> Clauses;
2654 Clauses.reserve(NumClauses);
2655 for (unsigned I = 0; I != NumClauses; ++I)
2656 Clauses.push_back(Record.readOMPClause());
2657 D->setClauses(Clauses);
2660 void ASTDeclReader::VisitOMPRequiresDecl(OMPRequiresDecl * D) {
2662 unsigned NumClauses = D->clauselist_size();
2663 SmallVector<OMPClause *, 8> Clauses;
2664 Clauses.reserve(NumClauses);
2665 for (unsigned I = 0; I != NumClauses; ++I)
2666 Clauses.push_back(Record.readOMPClause());
2667 D->setClauses(Clauses);
2670 void ASTDeclReader::VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D) {
2672 D->setLocation(readSourceLocation());
2673 Expr *In = Record.readExpr();
2674 Expr *Out = Record.readExpr();
2675 D->setCombinerData(In, Out);
2676 Expr *Combiner = Record.readExpr();
2677 D->setCombiner(Combiner);
2678 Expr *Orig = Record.readExpr();
2679 Expr *Priv = Record.readExpr();
2680 D->setInitializerData(Orig, Priv);
2681 Expr *Init = Record.readExpr();
2682 auto IK = static_cast<OMPDeclareReductionDecl::InitKind>(Record.readInt());
2683 D->setInitializer(Init, IK);
2684 D->PrevDeclInScope = readDeclID();
2687 void ASTDeclReader::VisitOMPDeclareMapperDecl(OMPDeclareMapperDecl *D) {
2689 D->setLocation(readSourceLocation());
2690 Expr *MapperVarRefE = Record.readExpr();
2691 D->setMapperVarRef(MapperVarRefE);
2692 D->VarName = Record.readDeclarationName();
2693 D->PrevDeclInScope = readDeclID();
2694 unsigned NumClauses = D->clauselist_size();
2695 SmallVector<OMPClause *, 8> Clauses;
2696 Clauses.reserve(NumClauses);
2697 for (unsigned I = 0; I != NumClauses; ++I)
2698 Clauses.push_back(Record.readOMPClause());
2699 D->setClauses(Clauses);
2702 void ASTDeclReader::VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D) {
2706 //===----------------------------------------------------------------------===//
2707 // Attribute Reading
2708 //===----------------------------------------------------------------------===//
2712 ASTRecordReader &Reader;
2715 AttrReader(ASTRecordReader &Reader) : Reader(Reader) {}
2717 uint64_t readInt() {
2718 return Reader.readInt();
2721 SourceRange readSourceRange() {
2722 return Reader.readSourceRange();
2725 SourceLocation readSourceLocation() {
2726 return Reader.readSourceLocation();
2729 Expr *readExpr() { return Reader.readExpr(); }
2731 std::string readString() {
2732 return Reader.readString();
2735 TypeSourceInfo *readTypeSourceInfo() {
2736 return Reader.readTypeSourceInfo();
2739 IdentifierInfo *readIdentifier() {
2740 return Reader.readIdentifier();
2743 VersionTuple readVersionTuple() {
2744 return Reader.readVersionTuple();
2747 template <typename T> T *GetLocalDeclAs(uint32_t LocalID) {
2748 return Reader.GetLocalDeclAs<T>(LocalID);
2753 Attr *ASTRecordReader::readAttr() {
2754 AttrReader Record(*this);
2755 auto V = Record.readInt();
2759 Attr *New = nullptr;
2760 // Kind is stored as a 1-based integer because 0 is used to indicate a null
2762 auto Kind = static_cast<attr::Kind>(V - 1);
2763 ASTContext &Context = getContext();
2765 IdentifierInfo *AttrName = Record.readIdentifier();
2766 IdentifierInfo *ScopeName = Record.readIdentifier();
2767 SourceRange AttrRange = Record.readSourceRange();
2768 SourceLocation ScopeLoc = Record.readSourceLocation();
2769 unsigned ParsedKind = Record.readInt();
2770 unsigned Syntax = Record.readInt();
2771 unsigned SpellingIndex = Record.readInt();
2773 AttributeCommonInfo Info(AttrName, ScopeName, AttrRange, ScopeLoc,
2774 AttributeCommonInfo::Kind(ParsedKind),
2775 AttributeCommonInfo::Syntax(Syntax), SpellingIndex);
2777 #include "clang/Serialization/AttrPCHRead.inc"
2779 assert(New && "Unable to decode attribute?");
2783 /// Reads attributes from the current stream position.
2784 void ASTRecordReader::readAttributes(AttrVec &Attrs) {
2785 for (unsigned I = 0, E = readInt(); I != E; ++I)
2786 Attrs.push_back(readAttr());
2789 //===----------------------------------------------------------------------===//
2790 // ASTReader Implementation
2791 //===----------------------------------------------------------------------===//
2793 /// Note that we have loaded the declaration with the given
2796 /// This routine notes that this declaration has already been loaded,
2797 /// so that future GetDecl calls will return this declaration rather
2798 /// than trying to load a new declaration.
2799 inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
2800 assert(!DeclsLoaded[Index] && "Decl loaded twice?");
2801 DeclsLoaded[Index] = D;
2804 /// Determine whether the consumer will be interested in seeing
2805 /// this declaration (via HandleTopLevelDecl).
2807 /// This routine should return true for anything that might affect
2808 /// code generation, e.g., inline function definitions, Objective-C
2809 /// declarations with metadata, etc.
2810 static bool isConsumerInterestedIn(ASTContext &Ctx, Decl *D, bool HasBody) {
2811 // An ObjCMethodDecl is never considered as "interesting" because its
2812 // implementation container always is.
2814 // An ImportDecl or VarDecl imported from a module map module will get
2815 // emitted when we import the relevant module.
2816 if (isPartOfPerModuleInitializer(D)) {
2817 auto *M = D->getImportedOwningModule();
2818 if (M && M->Kind == Module::ModuleMapModule &&
2819 Ctx.DeclMustBeEmitted(D))
2823 if (isa<FileScopeAsmDecl>(D) ||
2824 isa<ObjCProtocolDecl>(D) ||
2825 isa<ObjCImplDecl>(D) ||
2826 isa<ImportDecl>(D) ||
2827 isa<PragmaCommentDecl>(D) ||
2828 isa<PragmaDetectMismatchDecl>(D))
2830 if (isa<OMPThreadPrivateDecl>(D) || isa<OMPDeclareReductionDecl>(D) ||
2831 isa<OMPDeclareMapperDecl>(D) || isa<OMPAllocateDecl>(D))
2832 return !D->getDeclContext()->isFunctionOrMethod();
2833 if (const auto *Var = dyn_cast<VarDecl>(D))
2834 return Var->isFileVarDecl() &&
2835 (Var->isThisDeclarationADefinition() == VarDecl::Definition ||
2836 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(Var));
2837 if (const auto *Func = dyn_cast<FunctionDecl>(D))
2838 return Func->doesThisDeclarationHaveABody() || HasBody;
2840 if (auto *ES = D->getASTContext().getExternalSource())
2841 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
2847 /// Get the correct cursor and offset for loading a declaration.
2848 ASTReader::RecordLocation
2849 ASTReader::DeclCursorForID(DeclID ID, SourceLocation &Loc) {
2850 GlobalDeclMapType::iterator I = GlobalDeclMap.find(ID);
2851 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
2852 ModuleFile *M = I->second;
2853 const DeclOffset &DOffs =
2854 M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS];
2855 Loc = TranslateSourceLocation(*M, DOffs.getLocation());
2856 return RecordLocation(M, DOffs.BitOffset);
2859 ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
2860 auto I = GlobalBitOffsetsMap.find(GlobalOffset);
2862 assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map");
2863 return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
2866 uint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset) {
2867 return LocalOffset + M.GlobalBitOffset;
2870 static bool isSameTemplateParameterList(const TemplateParameterList *X,
2871 const TemplateParameterList *Y);
2873 /// Determine whether two template parameters are similar enough
2874 /// that they may be used in declarations of the same template.
2875 static bool isSameTemplateParameter(const NamedDecl *X,
2876 const NamedDecl *Y) {
2877 if (X->getKind() != Y->getKind())
2880 if (const auto *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
2881 const auto *TY = cast<TemplateTypeParmDecl>(Y);
2882 return TX->isParameterPack() == TY->isParameterPack();
2885 if (const auto *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
2886 const auto *TY = cast<NonTypeTemplateParmDecl>(Y);
2887 return TX->isParameterPack() == TY->isParameterPack() &&
2888 TX->getASTContext().hasSameType(TX->getType(), TY->getType());
2891 const auto *TX = cast<TemplateTemplateParmDecl>(X);
2892 const auto *TY = cast<TemplateTemplateParmDecl>(Y);
2893 return TX->isParameterPack() == TY->isParameterPack() &&
2894 isSameTemplateParameterList(TX->getTemplateParameters(),
2895 TY->getTemplateParameters());
2898 static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) {
2899 if (auto *NS = X->getAsNamespace())
2901 if (auto *NAS = X->getAsNamespaceAlias())
2902 return NAS->getNamespace();
2906 static bool isSameQualifier(const NestedNameSpecifier *X,
2907 const NestedNameSpecifier *Y) {
2908 if (auto *NSX = getNamespace(X)) {
2909 auto *NSY = getNamespace(Y);
2910 if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
2912 } else if (X->getKind() != Y->getKind())
2915 // FIXME: For namespaces and types, we're permitted to check that the entity
2916 // is named via the same tokens. We should probably do so.
2917 switch (X->getKind()) {
2918 case NestedNameSpecifier::Identifier:
2919 if (X->getAsIdentifier() != Y->getAsIdentifier())
2922 case NestedNameSpecifier::Namespace:
2923 case NestedNameSpecifier::NamespaceAlias:
2924 // We've already checked that we named the same namespace.
2926 case NestedNameSpecifier::TypeSpec:
2927 case NestedNameSpecifier::TypeSpecWithTemplate:
2928 if (X->getAsType()->getCanonicalTypeInternal() !=
2929 Y->getAsType()->getCanonicalTypeInternal())
2932 case NestedNameSpecifier::Global:
2933 case NestedNameSpecifier::Super:
2937 // Recurse into earlier portion of NNS, if any.
2938 auto *PX = X->getPrefix();
2939 auto *PY = Y->getPrefix();
2941 return isSameQualifier(PX, PY);
2945 /// Determine whether two template parameter lists are similar enough
2946 /// that they may be used in declarations of the same template.
2947 static bool isSameTemplateParameterList(const TemplateParameterList *X,
2948 const TemplateParameterList *Y) {
2949 if (X->size() != Y->size())
2952 for (unsigned I = 0, N = X->size(); I != N; ++I)
2953 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
2959 /// Determine whether the attributes we can overload on are identical for A and
2960 /// B. Will ignore any overloadable attrs represented in the type of A and B.
2961 static bool hasSameOverloadableAttrs(const FunctionDecl *A,
2962 const FunctionDecl *B) {
2963 // Note that pass_object_size attributes are represented in the function's
2964 // ExtParameterInfo, so we don't need to check them here.
2966 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
2967 auto AEnableIfAttrs = A->specific_attrs<EnableIfAttr>();
2968 auto BEnableIfAttrs = B->specific_attrs<EnableIfAttr>();
2970 for (auto Pair : zip_longest(AEnableIfAttrs, BEnableIfAttrs)) {
2971 Optional<EnableIfAttr *> Cand1A = std::get<0>(Pair);
2972 Optional<EnableIfAttr *> Cand2A = std::get<1>(Pair);
2974 // Return false if the number of enable_if attributes is different.
2975 if (!Cand1A || !Cand2A)
2981 (*Cand1A)->getCond()->Profile(Cand1ID, A->getASTContext(), true);
2982 (*Cand2A)->getCond()->Profile(Cand2ID, B->getASTContext(), true);
2984 // Return false if any of the enable_if expressions of A and B are
2986 if (Cand1ID != Cand2ID)
2992 /// Determine whether the two declarations refer to the same entity.
2993 static bool isSameEntity(NamedDecl *X, NamedDecl *Y) {
2994 assert(X->getDeclName() == Y->getDeclName() && "Declaration name mismatch!");
2999 // Must be in the same context.
3001 // Note that we can't use DeclContext::Equals here, because the DeclContexts
3002 // could be two different declarations of the same function. (We will fix the
3003 // semantic DC to refer to the primary definition after merging.)
3004 if (!declaresSameEntity(cast<Decl>(X->getDeclContext()->getRedeclContext()),
3005 cast<Decl>(Y->getDeclContext()->getRedeclContext())))
3008 // Two typedefs refer to the same entity if they have the same underlying
3010 if (const auto *TypedefX = dyn_cast<TypedefNameDecl>(X))
3011 if (const auto *TypedefY = dyn_cast<TypedefNameDecl>(Y))
3012 return X->getASTContext().hasSameType(TypedefX->getUnderlyingType(),
3013 TypedefY->getUnderlyingType());
3015 // Must have the same kind.
3016 if (X->getKind() != Y->getKind())
3019 // Objective-C classes and protocols with the same name always match.
3020 if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
3023 if (isa<ClassTemplateSpecializationDecl>(X)) {
3024 // No need to handle these here: we merge them when adding them to the
3029 // Compatible tags match.
3030 if (const auto *TagX = dyn_cast<TagDecl>(X)) {
3031 const auto *TagY = cast<TagDecl>(Y);
3032 return (TagX->getTagKind() == TagY->getTagKind()) ||
3033 ((TagX->getTagKind() == TTK_Struct || TagX->getTagKind() == TTK_Class ||
3034 TagX->getTagKind() == TTK_Interface) &&
3035 (TagY->getTagKind() == TTK_Struct || TagY->getTagKind() == TTK_Class ||
3036 TagY->getTagKind() == TTK_Interface));
3039 // Functions with the same type and linkage match.
3040 // FIXME: This needs to cope with merging of prototyped/non-prototyped
3042 if (const auto *FuncX = dyn_cast<FunctionDecl>(X)) {
3043 const auto *FuncY = cast<FunctionDecl>(Y);
3044 if (const auto *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
3045 const auto *CtorY = cast<CXXConstructorDecl>(Y);
3046 if (CtorX->getInheritedConstructor() &&
3047 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
3048 CtorY->getInheritedConstructor().getConstructor()))
3052 if (FuncX->isMultiVersion() != FuncY->isMultiVersion())
3055 // Multiversioned functions with different feature strings are represented
3056 // as separate declarations.
3057 if (FuncX->isMultiVersion()) {
3058 const auto *TAX = FuncX->getAttr<TargetAttr>();
3059 const auto *TAY = FuncY->getAttr<TargetAttr>();
3060 assert(TAX && TAY && "Multiversion Function without target attribute");
3062 if (TAX->getFeaturesStr() != TAY->getFeaturesStr())
3066 ASTContext &C = FuncX->getASTContext();
3067 auto GetTypeAsWritten = [](const FunctionDecl *FD) {
3068 // Map to the first declaration that we've already merged into this one.
3069 // The TSI of redeclarations might not match (due to calling conventions
3070 // being inherited onto the type but not the TSI), but the TSI type of
3071 // the first declaration of the function should match across modules.
3072 FD = FD->getCanonicalDecl();
3073 return FD->getTypeSourceInfo() ? FD->getTypeSourceInfo()->getType()
3076 QualType XT = GetTypeAsWritten(FuncX), YT = GetTypeAsWritten(FuncY);
3077 if (!C.hasSameType(XT, YT)) {
3078 // We can get functions with different types on the redecl chain in C++17
3079 // if they have differing exception specifications and at least one of
3080 // the excpetion specs is unresolved.
3081 auto *XFPT = XT->getAs<FunctionProtoType>();
3082 auto *YFPT = YT->getAs<FunctionProtoType>();
3083 if (C.getLangOpts().CPlusPlus17 && XFPT && YFPT &&
3084 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
3085 isUnresolvedExceptionSpec(YFPT->getExceptionSpecType())) &&
3086 C.hasSameFunctionTypeIgnoringExceptionSpec(XT, YT))
3090 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
3091 hasSameOverloadableAttrs(FuncX, FuncY);
3094 // Variables with the same type and linkage match.
3095 if (const auto *VarX = dyn_cast<VarDecl>(X)) {
3096 const auto *VarY = cast<VarDecl>(Y);
3097 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
3098 ASTContext &C = VarX->getASTContext();
3099 if (C.hasSameType(VarX->getType(), VarY->getType()))
3102 // We can get decls with different types on the redecl chain. Eg.
3103 // template <typename T> struct S { static T Var[]; }; // #1
3104 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
3105 // Only? happens when completing an incomplete array type. In this case
3106 // when comparing #1 and #2 we should go through their element type.
3107 const ArrayType *VarXTy = C.getAsArrayType(VarX->getType());
3108 const ArrayType *VarYTy = C.getAsArrayType(VarY->getType());
3109 if (!VarXTy || !VarYTy)
3111 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
3112 return C.hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
3117 // Namespaces with the same name and inlinedness match.
3118 if (const auto *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
3119 const auto *NamespaceY = cast<NamespaceDecl>(Y);
3120 return NamespaceX->isInline() == NamespaceY->isInline();
3123 // Identical template names and kinds match if their template parameter lists
3124 // and patterns match.
3125 if (const auto *TemplateX = dyn_cast<TemplateDecl>(X)) {
3126 const auto *TemplateY = cast<TemplateDecl>(Y);
3127 return isSameEntity(TemplateX->getTemplatedDecl(),
3128 TemplateY->getTemplatedDecl()) &&
3129 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
3130 TemplateY->getTemplateParameters());
3133 // Fields with the same name and the same type match.
3134 if (const auto *FDX = dyn_cast<FieldDecl>(X)) {
3135 const auto *FDY = cast<FieldDecl>(Y);
3136 // FIXME: Also check the bitwidth is odr-equivalent, if any.
3137 return X->getASTContext().hasSameType(FDX->getType(), FDY->getType());
3140 // Indirect fields with the same target field match.
3141 if (const auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
3142 const auto *IFDY = cast<IndirectFieldDecl>(Y);
3143 return IFDX->getAnonField()->getCanonicalDecl() ==
3144 IFDY->getAnonField()->getCanonicalDecl();
3147 // Enumerators with the same name match.
3148 if (isa<EnumConstantDecl>(X))
3149 // FIXME: Also check the value is odr-equivalent.
3152 // Using shadow declarations with the same target match.
3153 if (const auto *USX = dyn_cast<UsingShadowDecl>(X)) {
3154 const auto *USY = cast<UsingShadowDecl>(Y);
3155 return USX->getTargetDecl() == USY->getTargetDecl();
3158 // Using declarations with the same qualifier match. (We already know that
3159 // the name matches.)
3160 if (const auto *UX = dyn_cast<UsingDecl>(X)) {
3161 const auto *UY = cast<UsingDecl>(Y);
3162 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
3163 UX->hasTypename() == UY->hasTypename() &&
3164 UX->isAccessDeclaration() == UY->isAccessDeclaration();
3166 if (const auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
3167 const auto *UY = cast<UnresolvedUsingValueDecl>(Y);
3168 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
3169 UX->isAccessDeclaration() == UY->isAccessDeclaration();
3171 if (const auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X))
3172 return isSameQualifier(
3174 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
3176 // Namespace alias definitions with the same target match.
3177 if (const auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
3178 const auto *NAY = cast<NamespaceAliasDecl>(Y);
3179 return NAX->getNamespace()->Equals(NAY->getNamespace());
3185 /// Find the context in which we should search for previous declarations when
3186 /// looking for declarations to merge.
3187 DeclContext *ASTDeclReader::getPrimaryContextForMerging(ASTReader &Reader,
3189 if (auto *ND = dyn_cast<NamespaceDecl>(DC))
3190 return ND->getOriginalNamespace();
3192 if (auto *RD = dyn_cast<CXXRecordDecl>(DC)) {
3193 // Try to dig out the definition.
3194 auto *DD = RD->DefinitionData;
3196 DD = RD->getCanonicalDecl()->DefinitionData;
3198 // If there's no definition yet, then DC's definition is added by an update
3199 // record, but we've not yet loaded that update record. In this case, we
3200 // commit to DC being the canonical definition now, and will fix this when
3201 // we load the update record.
3203 DD = new (Reader.getContext()) struct CXXRecordDecl::DefinitionData(RD);
3204 RD->setCompleteDefinition(true);
3205 RD->DefinitionData = DD;
3206 RD->getCanonicalDecl()->DefinitionData = DD;
3208 // Track that we did this horrible thing so that we can fix it later.
3209 Reader.PendingFakeDefinitionData.insert(
3210 std::make_pair(DD, ASTReader::PendingFakeDefinitionKind::Fake));
3213 return DD->Definition;
3216 if (auto *ED = dyn_cast<EnumDecl>(DC))
3217 return ED->getASTContext().getLangOpts().CPlusPlus? ED->getDefinition()
3220 // We can see the TU here only if we have no Sema object. In that case,
3221 // there's no TU scope to look in, so using the DC alone is sufficient.
3222 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
3228 ASTDeclReader::FindExistingResult::~FindExistingResult() {
3229 // Record that we had a typedef name for linkage whether or not we merge
3230 // with that declaration.
3231 if (TypedefNameForLinkage) {
3232 DeclContext *DC = New->getDeclContext()->getRedeclContext();
3233 Reader.ImportedTypedefNamesForLinkage.insert(
3234 std::make_pair(std::make_pair(DC, TypedefNameForLinkage), New));
3238 if (!AddResult || Existing)
3241 DeclarationName Name = New->getDeclName();
3242 DeclContext *DC = New->getDeclContext()->getRedeclContext();
3243 if (needsAnonymousDeclarationNumber(New)) {
3244 setAnonymousDeclForMerging(Reader, New->getLexicalDeclContext(),
3245 AnonymousDeclNumber, New);
3246 } else if (DC->isTranslationUnit() &&
3247 !Reader.getContext().getLangOpts().CPlusPlus) {
3248 if (Reader.getIdResolver().tryAddTopLevelDecl(New, Name))
3249 Reader.PendingFakeLookupResults[Name.getAsIdentifierInfo()]
3251 } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
3252 // Add the declaration to its redeclaration context so later merging
3253 // lookups will find it.
3254 MergeDC->makeDeclVisibleInContextImpl(New, /*Internal*/true);
3258 /// Find the declaration that should be merged into, given the declaration found
3259 /// by name lookup. If we're merging an anonymous declaration within a typedef,
3260 /// we need a matching typedef, and we merge with the type inside it.
3261 static NamedDecl *getDeclForMerging(NamedDecl *Found,
3262 bool IsTypedefNameForLinkage) {
3263 if (!IsTypedefNameForLinkage)
3266 // If we found a typedef declaration that gives a name to some other
3267 // declaration, then we want that inner declaration. Declarations from
3268 // AST files are handled via ImportedTypedefNamesForLinkage.
3269 if (Found->isFromASTFile())
3272 if (auto *TND = dyn_cast<TypedefNameDecl>(Found))
3273 return TND->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
3278 /// Find the declaration to use to populate the anonymous declaration table
3279 /// for the given lexical DeclContext. We only care about finding local
3280 /// definitions of the context; we'll merge imported ones as we go.
3282 ASTDeclReader::getPrimaryDCForAnonymousDecl(DeclContext *LexicalDC) {
3283 // For classes, we track the definition as we merge.
3284 if (auto *RD = dyn_cast<CXXRecordDecl>(LexicalDC)) {
3285 auto *DD = RD->getCanonicalDecl()->DefinitionData;
3286 return DD ? DD->Definition : nullptr;
3289 // For anything else, walk its merged redeclarations looking for a definition.
3290 // Note that we can't just call getDefinition here because the redeclaration
3291 // chain isn't wired up.
3292 for (auto *D : merged_redecls(cast<Decl>(LexicalDC))) {
3293 if (auto *FD = dyn_cast<FunctionDecl>(D))
3294 if (FD->isThisDeclarationADefinition())
3296 if (auto *MD = dyn_cast<ObjCMethodDecl>(D))
3297 if (MD->isThisDeclarationADefinition())
3301 // No merged definition yet.
3305 NamedDecl *ASTDeclReader::getAnonymousDeclForMerging(ASTReader &Reader,
3308 // If the lexical context has been merged, look into the now-canonical
3310 auto *CanonDC = cast<Decl>(DC)->getCanonicalDecl();
3312 // If we've seen this before, return the canonical declaration.
3313 auto &Previous = Reader.AnonymousDeclarationsForMerging[CanonDC];
3314 if (Index < Previous.size() && Previous[Index])
3315 return Previous[Index];
3317 // If this is the first time, but we have parsed a declaration of the context,
3318 // build the anonymous declaration list from the parsed declaration.
3319 auto *PrimaryDC = getPrimaryDCForAnonymousDecl(DC);
3320 if (PrimaryDC && !cast<Decl>(PrimaryDC)->isFromASTFile()) {
3321 numberAnonymousDeclsWithin(PrimaryDC, [&](NamedDecl *ND, unsigned Number) {
3322 if (Previous.size() == Number)
3323 Previous.push_back(cast<NamedDecl>(ND->getCanonicalDecl()));
3325 Previous[Number] = cast<NamedDecl>(ND->getCanonicalDecl());
3329 return Index < Previous.size() ? Previous[Index] : nullptr;
3332 void ASTDeclReader::setAnonymousDeclForMerging(ASTReader &Reader,
3333 DeclContext *DC, unsigned Index,
3335 auto *CanonDC = cast<Decl>(DC)->getCanonicalDecl();
3337 auto &Previous = Reader.AnonymousDeclarationsForMerging[CanonDC];
3338 if (Index >= Previous.size())
3339 Previous.resize(Index + 1);
3340 if (!Previous[Index])
3341 Previous[Index] = D;
3344 ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) {
3345 DeclarationName Name = TypedefNameForLinkage ? TypedefNameForLinkage
3348 if (!Name && !needsAnonymousDeclarationNumber(D)) {
3349 // Don't bother trying to find unnamed declarations that are in
3350 // unmergeable contexts.
3351 FindExistingResult Result(Reader, D, /*Existing=*/nullptr,
3352 AnonymousDeclNumber, TypedefNameForLinkage);
3357 DeclContext *DC = D->getDeclContext()->getRedeclContext();
3358 if (TypedefNameForLinkage) {
3359 auto It = Reader.ImportedTypedefNamesForLinkage.find(
3360 std::make_pair(DC, TypedefNameForLinkage));
3361 if (It != Reader.ImportedTypedefNamesForLinkage.end())
3362 if (isSameEntity(It->second, D))
3363 return FindExistingResult(Reader, D, It->second, AnonymousDeclNumber,
3364 TypedefNameForLinkage);
3365 // Go on to check in other places in case an existing typedef name
3366 // was not imported.
3369 if (needsAnonymousDeclarationNumber(D)) {
3370 // This is an anonymous declaration that we may need to merge. Look it up
3371 // in its context by number.
3372 if (auto *Existing = getAnonymousDeclForMerging(
3373 Reader, D->getLexicalDeclContext(), AnonymousDeclNumber))
3374 if (isSameEntity(Existing, D))
3375 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3376 TypedefNameForLinkage);
3377 } else if (DC->isTranslationUnit() &&
3378 !Reader.getContext().getLangOpts().CPlusPlus) {
3379 IdentifierResolver &IdResolver = Reader.getIdResolver();
3381 // Temporarily consider the identifier to be up-to-date. We don't want to
3382 // cause additional lookups here.
3383 class UpToDateIdentifierRAII {
3385 bool WasOutToDate = false;
3388 explicit UpToDateIdentifierRAII(IdentifierInfo *II) : II(II) {
3390 WasOutToDate = II->isOutOfDate();
3392 II->setOutOfDate(false);
3396 ~UpToDateIdentifierRAII() {
3398 II->setOutOfDate(true);
3400 } UpToDate(Name.getAsIdentifierInfo());
3402 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
3403 IEnd = IdResolver.end();
3405 if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
3406 if (isSameEntity(Existing, D))
3407 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3408 TypedefNameForLinkage);
3410 } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
3411 DeclContext::lookup_result R = MergeDC->noload_lookup(Name);
3412 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
3413 if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
3414 if (isSameEntity(Existing, D))
3415 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3416 TypedefNameForLinkage);
3419 // Not in a mergeable context.
3420 return FindExistingResult(Reader);
3423 // If this declaration is from a merged context, make a note that we need to
3424 // check that the canonical definition of that context contains the decl.
3426 // FIXME: We should do something similar if we merge two definitions of the
3427 // same template specialization into the same CXXRecordDecl.
3428 auto MergedDCIt = Reader.MergedDeclContexts.find(D->getLexicalDeclContext());
3429 if (MergedDCIt != Reader.MergedDeclContexts.end() &&
3430 MergedDCIt->second == D->getDeclContext())
3431 Reader.PendingOdrMergeChecks.push_back(D);
3433 return FindExistingResult(Reader, D, /*Existing=*/nullptr,
3434 AnonymousDeclNumber, TypedefNameForLinkage);
3437 template<typename DeclT>
3438 Decl *ASTDeclReader::getMostRecentDeclImpl(Redeclarable<DeclT> *D) {
3439 return D->RedeclLink.getLatestNotUpdated();
3442 Decl *ASTDeclReader::getMostRecentDeclImpl(...) {
3443 llvm_unreachable("getMostRecentDecl on non-redeclarable declaration");
3446 Decl *ASTDeclReader::getMostRecentDecl(Decl *D) {
3449 switch (D->getKind()) {
3450 #define ABSTRACT_DECL(TYPE)
3451 #define DECL(TYPE, BASE) \
3453 return getMostRecentDeclImpl(cast<TYPE##Decl>(D));
3454 #include "clang/AST/DeclNodes.inc"
3456 llvm_unreachable("unknown decl kind");
3459 Decl *ASTReader::getMostRecentExistingDecl(Decl *D) {
3460 return ASTDeclReader::getMostRecentDecl(D->getCanonicalDecl());
3463 template<typename DeclT>
3464 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3465 Redeclarable<DeclT> *D,
3466 Decl *Previous, Decl *Canon) {
3467 D->RedeclLink.setPrevious(cast<DeclT>(Previous));
3468 D->First = cast<DeclT>(Previous)->First;
3474 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3475 Redeclarable<VarDecl> *D,
3476 Decl *Previous, Decl *Canon) {
3477 auto *VD = static_cast<VarDecl *>(D);
3478 auto *PrevVD = cast<VarDecl>(Previous);
3479 D->RedeclLink.setPrevious(PrevVD);
3480 D->First = PrevVD->First;
3482 // We should keep at most one definition on the chain.
3483 // FIXME: Cache the definition once we've found it. Building a chain with
3484 // N definitions currently takes O(N^2) time here.
3485 if (VD->isThisDeclarationADefinition() == VarDecl::Definition) {
3486 for (VarDecl *CurD = PrevVD; CurD; CurD = CurD->getPreviousDecl()) {
3487 if (CurD->isThisDeclarationADefinition() == VarDecl::Definition) {
3488 Reader.mergeDefinitionVisibility(CurD, VD);
3489 VD->demoteThisDefinitionToDeclaration();
3496 static bool isUndeducedReturnType(QualType T) {
3497 auto *DT = T->getContainedDeducedType();
3498 return DT && !DT->isDeduced();
3502 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3503 Redeclarable<FunctionDecl> *D,
3504 Decl *Previous, Decl *Canon) {
3505 auto *FD = static_cast<FunctionDecl *>(D);
3506 auto *PrevFD = cast<FunctionDecl>(Previous);
3508 FD->RedeclLink.setPrevious(PrevFD);
3509 FD->First = PrevFD->First;
3511 // If the previous declaration is an inline function declaration, then this
3512 // declaration is too.
3513 if (PrevFD->isInlined() != FD->isInlined()) {
3514 // FIXME: [dcl.fct.spec]p4:
3515 // If a function with external linkage is declared inline in one
3516 // translation unit, it shall be declared inline in all translation
3517 // units in which it appears.
3519 // Be careful of this case:
3522 // template<typename T> struct X { void f(); };
3523 // template<typename T> inline void X<T>::f() {}
3525 // module B instantiates the declaration of X<int>::f
3526 // module C instantiates the definition of X<int>::f
3528 // If module B and C are merged, we do not have a violation of this rule.
3529 FD->setImplicitlyInline(true);
3532 auto *FPT = FD->getType()->getAs<FunctionProtoType>();
3533 auto *PrevFPT = PrevFD->getType()->getAs<FunctionProtoType>();
3534 if (FPT && PrevFPT) {
3535 // If we need to propagate an exception specification along the redecl
3536 // chain, make a note of that so that we can do so later.
3537 bool IsUnresolved = isUnresolvedExceptionSpec(FPT->getExceptionSpecType());
3538 bool WasUnresolved =
3539 isUnresolvedExceptionSpec(PrevFPT->getExceptionSpecType());
3540 if (IsUnresolved != WasUnresolved)
3541 Reader.PendingExceptionSpecUpdates.insert(
3542 {Canon, IsUnresolved ? PrevFD : FD});
3544 // If we need to propagate a deduced return type along the redecl chain,
3545 // make a note of that so that we can do it later.
3546 bool IsUndeduced = isUndeducedReturnType(FPT->getReturnType());
3547 bool WasUndeduced = isUndeducedReturnType(PrevFPT->getReturnType());
3548 if (IsUndeduced != WasUndeduced)
3549 Reader.PendingDeducedTypeUpdates.insert(
3550 {cast<FunctionDecl>(Canon),
3551 (IsUndeduced ? PrevFPT : FPT)->getReturnType()});
3555 } // namespace clang
3557 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader, ...) {
3558 llvm_unreachable("attachPreviousDecl on non-redeclarable declaration");
3561 /// Inherit the default template argument from \p From to \p To. Returns
3562 /// \c false if there is no default template for \p From.
3563 template <typename ParmDecl>
3564 static bool inheritDefaultTemplateArgument(ASTContext &Context, ParmDecl *From,
3566 auto *To = cast<ParmDecl>(ToD);
3567 if (!From->hasDefaultArgument())
3569 To->setInheritedDefaultArgument(Context, From);
3573 static void inheritDefaultTemplateArguments(ASTContext &Context,
3576 auto *FromTP = From->getTemplateParameters();
3577 auto *ToTP = To->getTemplateParameters();
3578 assert(FromTP->size() == ToTP->size() && "merged mismatched templates?");
3580 for (unsigned I = 0, N = FromTP->size(); I != N; ++I) {
3581 NamedDecl *FromParam = FromTP->getParam(I);
3582 NamedDecl *ToParam = ToTP->getParam(I);
3584 if (auto *FTTP = dyn_cast<TemplateTypeParmDecl>(FromParam))
3585 inheritDefaultTemplateArgument(Context, FTTP, ToParam);
3586 else if (auto *FNTTP = dyn_cast<NonTypeTemplateParmDecl>(FromParam))
3587 inheritDefaultTemplateArgument(Context, FNTTP, ToParam);
3589 inheritDefaultTemplateArgument(
3590 Context, cast<TemplateTemplateParmDecl>(FromParam), ToParam);
3594 void ASTDeclReader::attachPreviousDecl(ASTReader &Reader, Decl *D,
3595 Decl *Previous, Decl *Canon) {
3596 assert(D && Previous);
3598 switch (D->getKind()) {
3599 #define ABSTRACT_DECL(TYPE)
3600 #define DECL(TYPE, BASE) \
3602 attachPreviousDeclImpl(Reader, cast<TYPE##Decl>(D), Previous, Canon); \
3604 #include "clang/AST/DeclNodes.inc"
3607 // If the declaration was visible in one module, a redeclaration of it in
3608 // another module remains visible even if it wouldn't be visible by itself.
3610 // FIXME: In this case, the declaration should only be visible if a module
3611 // that makes it visible has been imported.
3612 D->IdentifierNamespace |=
3613 Previous->IdentifierNamespace &
3614 (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
3616 // If the declaration declares a template, it may inherit default arguments
3617 // from the previous declaration.
3618 if (auto *TD = dyn_cast<TemplateDecl>(D))
3619 inheritDefaultTemplateArguments(Reader.getContext(),
3620 cast<TemplateDecl>(Previous), TD);
3623 template<typename DeclT>
3624 void ASTDeclReader::attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest) {
3625 D->RedeclLink.setLatest(cast<DeclT>(Latest));
3628 void ASTDeclReader::attachLatestDeclImpl(...) {
3629 llvm_unreachable("attachLatestDecl on non-redeclarable declaration");
3632 void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {
3633 assert(D && Latest);
3635 switch (D->getKind()) {
3636 #define ABSTRACT_DECL(TYPE)
3637 #define DECL(TYPE, BASE) \
3639 attachLatestDeclImpl(cast<TYPE##Decl>(D), Latest); \
3641 #include "clang/AST/DeclNodes.inc"
3645 template<typename DeclT>
3646 void ASTDeclReader::markIncompleteDeclChainImpl(Redeclarable<DeclT> *D) {
3647 D->RedeclLink.markIncomplete();
3650 void ASTDeclReader::markIncompleteDeclChainImpl(...) {
3651 llvm_unreachable("markIncompleteDeclChain on non-redeclarable declaration");
3654 void ASTReader::markIncompleteDeclChain(Decl *D) {
3655 switch (D->getKind()) {
3656 #define ABSTRACT_DECL(TYPE)
3657 #define DECL(TYPE, BASE) \
3659 ASTDeclReader::markIncompleteDeclChainImpl(cast<TYPE##Decl>(D)); \
3661 #include "clang/AST/DeclNodes.inc"
3665 /// Read the declaration at the given offset from the AST file.
3666 Decl *ASTReader::ReadDeclRecord(DeclID ID) {
3667 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
3668 SourceLocation DeclLoc;
3669 RecordLocation Loc = DeclCursorForID(ID, DeclLoc);
3670 llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
3671 // Keep track of where we are in the stream, then jump back there
3672 // after reading this declaration.
3673 SavedStreamPosition SavedPosition(DeclsCursor);
3675 ReadingKindTracker ReadingKind(Read_Decl, *this);
3677 // Note that we are loading a declaration record.
3678 Deserializing ADecl(this);
3680 auto Fail = [](const char *what, llvm::Error &&Err) {
3681 llvm::report_fatal_error(Twine("ASTReader::readDeclRecord failed ") + what +
3682 ": " + toString(std::move(Err)));
3685 if (llvm::Error JumpFailed = DeclsCursor.JumpToBit(Loc.Offset))
3686 Fail("jumping", std::move(JumpFailed));
3687 ASTRecordReader Record(*this, *Loc.F);
3688 ASTDeclReader Reader(*this, Record, Loc, ID, DeclLoc);
3689 Expected<unsigned> MaybeCode = DeclsCursor.ReadCode();
3691 Fail("reading code", MaybeCode.takeError());
3692 unsigned Code = MaybeCode.get();
3694 ASTContext &Context = getContext();
3696 Expected<unsigned> MaybeDeclCode = Record.readRecord(DeclsCursor, Code);
3698 llvm::report_fatal_error(
3699 "ASTReader::readDeclRecord failed reading decl code: " +
3700 toString(MaybeDeclCode.takeError()));
3701 switch ((DeclCode)MaybeDeclCode.get()) {
3702 case DECL_CONTEXT_LEXICAL:
3703 case DECL_CONTEXT_VISIBLE:
3704 llvm_unreachable("Record cannot be de-serialized with readDeclRecord");
3706 D = TypedefDecl::CreateDeserialized(Context, ID);
3708 case DECL_TYPEALIAS:
3709 D = TypeAliasDecl::CreateDeserialized(Context, ID);
3712 D = EnumDecl::CreateDeserialized(Context, ID);
3715 D = RecordDecl::CreateDeserialized(Context, ID);
3717 case DECL_ENUM_CONSTANT:
3718 D = EnumConstantDecl::CreateDeserialized(Context, ID);
3721 D = FunctionDecl::CreateDeserialized(Context, ID);
3723 case DECL_LINKAGE_SPEC:
3724 D = LinkageSpecDecl::CreateDeserialized(Context, ID);
3727 D = ExportDecl::CreateDeserialized(Context, ID);
3730 D = LabelDecl::CreateDeserialized(Context, ID);
3732 case DECL_NAMESPACE:
3733 D = NamespaceDecl::CreateDeserialized(Context, ID);
3735 case DECL_NAMESPACE_ALIAS:
3736 D = NamespaceAliasDecl::CreateDeserialized(Context, ID);
3739 D = UsingDecl::CreateDeserialized(Context, ID);
3741 case DECL_USING_PACK:
3742 D = UsingPackDecl::CreateDeserialized(Context, ID, Record.readInt());
3744 case DECL_USING_SHADOW:
3745 D = UsingShadowDecl::CreateDeserialized(Context, ID);
3747 case DECL_CONSTRUCTOR_USING_SHADOW:
3748 D = ConstructorUsingShadowDecl::CreateDeserialized(Context, ID);
3750 case DECL_USING_DIRECTIVE:
3751 D = UsingDirectiveDecl::CreateDeserialized(Context, ID);
3753 case DECL_UNRESOLVED_USING_VALUE:
3754 D = UnresolvedUsingValueDecl::CreateDeserialized(Context, ID);
3756 case DECL_UNRESOLVED_USING_TYPENAME:
3757 D = UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID);
3759 case DECL_CXX_RECORD:
3760 D = CXXRecordDecl::CreateDeserialized(Context, ID);
3762 case DECL_CXX_DEDUCTION_GUIDE:
3763 D = CXXDeductionGuideDecl::CreateDeserialized(Context, ID);
3765 case DECL_CXX_METHOD:
3766 D = CXXMethodDecl::CreateDeserialized(Context, ID);
3768 case DECL_CXX_CONSTRUCTOR:
3769 D = CXXConstructorDecl::CreateDeserialized(Context, ID, Record.readInt());
3771 case DECL_CXX_DESTRUCTOR:
3772 D = CXXDestructorDecl::CreateDeserialized(Context, ID);
3774 case DECL_CXX_CONVERSION:
3775 D = CXXConversionDecl::CreateDeserialized(Context, ID);
3777 case DECL_ACCESS_SPEC:
3778 D = AccessSpecDecl::CreateDeserialized(Context, ID);
3781 D = FriendDecl::CreateDeserialized(Context, ID, Record.readInt());
3783 case DECL_FRIEND_TEMPLATE:
3784 D = FriendTemplateDecl::CreateDeserialized(Context, ID);
3786 case DECL_CLASS_TEMPLATE:
3787 D = ClassTemplateDecl::CreateDeserialized(Context, ID);
3789 case DECL_CLASS_TEMPLATE_SPECIALIZATION:
3790 D = ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3792 case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
3793 D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3795 case DECL_VAR_TEMPLATE:
3796 D = VarTemplateDecl::CreateDeserialized(Context, ID);
3798 case DECL_VAR_TEMPLATE_SPECIALIZATION:
3799 D = VarTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3801 case DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION:
3802 D = VarTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3804 case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
3805 D = ClassScopeFunctionSpecializationDecl::CreateDeserialized(Context, ID);
3807 case DECL_FUNCTION_TEMPLATE:
3808 D = FunctionTemplateDecl::CreateDeserialized(Context, ID);
3810 case DECL_TEMPLATE_TYPE_PARM: {
3811 bool HasTypeConstraint = Record.readInt();
3812 D = TemplateTypeParmDecl::CreateDeserialized(Context, ID,
3816 case DECL_NON_TYPE_TEMPLATE_PARM: {
3817 bool HasTypeConstraint = Record.readInt();
3818 D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID,
3822 case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK: {
3823 bool HasTypeConstraint = Record.readInt();
3824 D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID,
3829 case DECL_TEMPLATE_TEMPLATE_PARM:
3830 D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID);
3832 case DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK:
3833 D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID,
3836 case DECL_TYPE_ALIAS_TEMPLATE:
3837 D = TypeAliasTemplateDecl::CreateDeserialized(Context, ID);
3840 D = ConceptDecl::CreateDeserialized(Context, ID);
3842 case DECL_REQUIRES_EXPR_BODY:
3843 D = RequiresExprBodyDecl::CreateDeserialized(Context, ID);
3845 case DECL_STATIC_ASSERT:
3846 D = StaticAssertDecl::CreateDeserialized(Context, ID);
3848 case DECL_OBJC_METHOD:
3849 D = ObjCMethodDecl::CreateDeserialized(Context, ID);
3851 case DECL_OBJC_INTERFACE:
3852 D = ObjCInterfaceDecl::CreateDeserialized(Context, ID);
3854 case DECL_OBJC_IVAR:
3855 D = ObjCIvarDecl::CreateDeserialized(Context, ID);
3857 case DECL_OBJC_PROTOCOL:
3858 D = ObjCProtocolDecl::CreateDeserialized(Context, ID);
3860 case DECL_OBJC_AT_DEFS_FIELD:
3861 D = ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID);
3863 case DECL_OBJC_CATEGORY:
3864 D = ObjCCategoryDecl::CreateDeserialized(Context, ID);
3866 case DECL_OBJC_CATEGORY_IMPL:
3867 D = ObjCCategoryImplDecl::CreateDeserialized(Context, ID);
3869 case DECL_OBJC_IMPLEMENTATION:
3870 D = ObjCImplementationDecl::CreateDeserialized(Context, ID);
3872 case DECL_OBJC_COMPATIBLE_ALIAS:
3873 D = ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID);
3875 case DECL_OBJC_PROPERTY:
3876 D = ObjCPropertyDecl::CreateDeserialized(Context, ID);
3878 case DECL_OBJC_PROPERTY_IMPL:
3879 D = ObjCPropertyImplDecl::CreateDeserialized(Context, ID);
3882 D = FieldDecl::CreateDeserialized(Context, ID);
3884 case DECL_INDIRECTFIELD:
3885 D = IndirectFieldDecl::CreateDeserialized(Context, ID);
3888 D = VarDecl::CreateDeserialized(Context, ID);
3890 case DECL_IMPLICIT_PARAM:
3891 D = ImplicitParamDecl::CreateDeserialized(Context, ID);
3894 D = ParmVarDecl::CreateDeserialized(Context, ID);
3896 case DECL_DECOMPOSITION:
3897 D = DecompositionDecl::CreateDeserialized(Context, ID, Record.readInt());
3900 D = BindingDecl::CreateDeserialized(Context, ID);
3902 case DECL_FILE_SCOPE_ASM:
3903 D = FileScopeAsmDecl::CreateDeserialized(Context, ID);
3906 D = BlockDecl::CreateDeserialized(Context, ID);
3908 case DECL_MS_PROPERTY:
3909 D = MSPropertyDecl::CreateDeserialized(Context, ID);
3912 D = CapturedDecl::CreateDeserialized(Context, ID, Record.readInt());
3914 case DECL_CXX_BASE_SPECIFIERS:
3915 Error("attempt to read a C++ base-specifier record as a declaration");
3917 case DECL_CXX_CTOR_INITIALIZERS:
3918 Error("attempt to read a C++ ctor initializer record as a declaration");
3921 // Note: last entry of the ImportDecl record is the number of stored source
3923 D = ImportDecl::CreateDeserialized(Context, ID, Record.back());
3925 case DECL_OMP_THREADPRIVATE:
3926 D = OMPThreadPrivateDecl::CreateDeserialized(Context, ID, Record.readInt());
3928 case DECL_OMP_ALLOCATE: {
3929 unsigned NumVars = Record.readInt();
3930 unsigned NumClauses = Record.readInt();
3931 D = OMPAllocateDecl::CreateDeserialized(Context, ID, NumVars, NumClauses);
3934 case DECL_OMP_REQUIRES:
3935 D = OMPRequiresDecl::CreateDeserialized(Context, ID, Record.readInt());
3937 case DECL_OMP_DECLARE_REDUCTION:
3938 D = OMPDeclareReductionDecl::CreateDeserialized(Context, ID);
3940 case DECL_OMP_DECLARE_MAPPER:
3941 D = OMPDeclareMapperDecl::CreateDeserialized(Context, ID, Record.readInt());
3943 case DECL_OMP_CAPTUREDEXPR:
3944 D = OMPCapturedExprDecl::CreateDeserialized(Context, ID);
3946 case DECL_PRAGMA_COMMENT:
3947 D = PragmaCommentDecl::CreateDeserialized(Context, ID, Record.readInt());
3949 case DECL_PRAGMA_DETECT_MISMATCH:
3950 D = PragmaDetectMismatchDecl::CreateDeserialized(Context, ID,
3954 D = EmptyDecl::CreateDeserialized(Context, ID);
3956 case DECL_LIFETIME_EXTENDED_TEMPORARY:
3957 D = LifetimeExtendedTemporaryDecl::CreateDeserialized(Context, ID);
3959 case DECL_OBJC_TYPE_PARAM:
3960 D = ObjCTypeParamDecl::CreateDeserialized(Context, ID);
3964 assert(D && "Unknown declaration reading AST file");
3965 LoadedDecl(Index, D);
3966 // Set the DeclContext before doing any deserialization, to make sure internal
3967 // calls to Decl::getASTContext() by Decl's methods will find the
3968 // TranslationUnitDecl without crashing.
3969 D->setDeclContext(Context.getTranslationUnitDecl());
3972 // If this declaration is also a declaration context, get the
3973 // offsets for its tables of lexical and visible declarations.
3974 if (auto *DC = dyn_cast<DeclContext>(D)) {
3975 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
3976 if (Offsets.first &&
3977 ReadLexicalDeclContextStorage(*Loc.F, DeclsCursor, Offsets.first, DC))
3979 if (Offsets.second &&
3980 ReadVisibleDeclContextStorage(*Loc.F, DeclsCursor, Offsets.second, ID))
3983 assert(Record.getIdx() == Record.size());
3985 // Load any relevant update records.
3986 PendingUpdateRecords.push_back(
3987 PendingUpdateRecord(ID, D, /*JustLoaded=*/true));
3989 // Load the categories after recursive loading is finished.
3990 if (auto *Class = dyn_cast<ObjCInterfaceDecl>(D))
3991 // If we already have a definition when deserializing the ObjCInterfaceDecl,
3992 // we put the Decl in PendingDefinitions so we can pull the categories here.
3993 if (Class->isThisDeclarationADefinition() ||
3994 PendingDefinitions.count(Class))
3995 loadObjCCategories(ID, Class);
3997 // If we have deserialized a declaration that has a definition the
3998 // AST consumer might need to know about, queue it.
3999 // We don't pass it to the consumer immediately because we may be in recursive
4000 // loading, and some declarations may still be initializing.
4001 PotentiallyInterestingDecls.push_back(
4002 InterestingDecl(D, Reader.hasPendingBody()));
4007 void ASTReader::PassInterestingDeclsToConsumer() {
4010 if (PassingDeclsToConsumer)
4013 // Guard variable to avoid recursively redoing the process of passing
4014 // decls to consumer.
4015 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
4018 // Ensure that we've loaded all potentially-interesting declarations
4019 // that need to be eagerly loaded.
4020 for (auto ID : EagerlyDeserializedDecls)
4022 EagerlyDeserializedDecls.clear();
4024 while (!PotentiallyInterestingDecls.empty()) {
4025 InterestingDecl D = PotentiallyInterestingDecls.front();
4026 PotentiallyInterestingDecls.pop_front();
4027 if (isConsumerInterestedIn(getContext(), D.getDecl(), D.hasPendingBody()))
4028 PassInterestingDeclToConsumer(D.getDecl());
4032 void ASTReader::loadDeclUpdateRecords(PendingUpdateRecord &Record) {
4033 // The declaration may have been modified by files later in the chain.
4034 // If this is the case, read the record containing the updates from each file
4035 // and pass it to ASTDeclReader to make the modifications.
4036 serialization::GlobalDeclID ID = Record.ID;
4038 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
4039 DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
4041 SmallVector<serialization::DeclID, 8> PendingLazySpecializationIDs;
4043 if (UpdI != DeclUpdateOffsets.end()) {
4044 auto UpdateOffsets = std::move(UpdI->second);
4045 DeclUpdateOffsets.erase(UpdI);
4047 // Check if this decl was interesting to the consumer. If we just loaded
4048 // the declaration, then we know it was interesting and we skip the call
4049 // to isConsumerInterestedIn because it is unsafe to call in the
4050 // current ASTReader state.
4051 bool WasInteresting =
4052 Record.JustLoaded || isConsumerInterestedIn(getContext(), D, false);
4053 for (auto &FileAndOffset : UpdateOffsets) {
4054 ModuleFile *F = FileAndOffset.first;
4055 uint64_t Offset = FileAndOffset.second;
4056 llvm::BitstreamCursor &Cursor = F->DeclsCursor;
4057 SavedStreamPosition SavedPosition(Cursor);
4058 if (llvm::Error JumpFailed = Cursor.JumpToBit(Offset))
4059 // FIXME don't do a fatal error.
4060 llvm::report_fatal_error(
4061 "ASTReader::loadDeclUpdateRecords failed jumping: " +
4062 toString(std::move(JumpFailed)));
4063 Expected<unsigned> MaybeCode = Cursor.ReadCode();
4065 llvm::report_fatal_error(
4066 "ASTReader::loadDeclUpdateRecords failed reading code: " +
4067 toString(MaybeCode.takeError()));
4068 unsigned Code = MaybeCode.get();
4069 ASTRecordReader Record(*this, *F);
4070 if (Expected<unsigned> MaybeRecCode = Record.readRecord(Cursor, Code))
4071 assert(MaybeRecCode.get() == DECL_UPDATES &&
4072 "Expected DECL_UPDATES record!");
4074 llvm::report_fatal_error(
4075 "ASTReader::loadDeclUpdateRecords failed reading rec code: " +
4076 toString(MaybeCode.takeError()));
4078 ASTDeclReader Reader(*this, Record, RecordLocation(F, Offset), ID,
4080 Reader.UpdateDecl(D, PendingLazySpecializationIDs);
4082 // We might have made this declaration interesting. If so, remember that
4083 // we need to hand it off to the consumer.
4084 if (!WasInteresting &&
4085 isConsumerInterestedIn(getContext(), D, Reader.hasPendingBody())) {
4086 PotentiallyInterestingDecls.push_back(
4087 InterestingDecl(D, Reader.hasPendingBody()));
4088 WasInteresting = true;
4092 // Add the lazy specializations to the template.
4093 assert((PendingLazySpecializationIDs.empty() || isa<ClassTemplateDecl>(D) ||
4094 isa<FunctionTemplateDecl>(D) || isa<VarTemplateDecl>(D)) &&
4095 "Must not have pending specializations");
4096 if (auto *CTD = dyn_cast<ClassTemplateDecl>(D))
4097 ASTDeclReader::AddLazySpecializations(CTD, PendingLazySpecializationIDs);
4098 else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(D))
4099 ASTDeclReader::AddLazySpecializations(FTD, PendingLazySpecializationIDs);
4100 else if (auto *VTD = dyn_cast<VarTemplateDecl>(D))
4101 ASTDeclReader::AddLazySpecializations(VTD, PendingLazySpecializationIDs);
4102 PendingLazySpecializationIDs.clear();
4104 // Load the pending visible updates for this decl context, if it has any.
4105 auto I = PendingVisibleUpdates.find(ID);
4106 if (I != PendingVisibleUpdates.end()) {
4107 auto VisibleUpdates = std::move(I->second);
4108 PendingVisibleUpdates.erase(I);
4110 auto *DC = cast<DeclContext>(D)->getPrimaryContext();
4111 for (const auto &Update : VisibleUpdates)
4112 Lookups[DC].Table.add(
4113 Update.Mod, Update.Data,
4114 reader::ASTDeclContextNameLookupTrait(*this, *Update.Mod));
4115 DC->setHasExternalVisibleStorage(true);
4119 void ASTReader::loadPendingDeclChain(Decl *FirstLocal, uint64_t LocalOffset) {
4120 // Attach FirstLocal to the end of the decl chain.
4121 Decl *CanonDecl = FirstLocal->getCanonicalDecl();
4122 if (FirstLocal != CanonDecl) {
4123 Decl *PrevMostRecent = ASTDeclReader::getMostRecentDecl(CanonDecl);
4124 ASTDeclReader::attachPreviousDecl(
4125 *this, FirstLocal, PrevMostRecent ? PrevMostRecent : CanonDecl,
4130 ASTDeclReader::attachLatestDecl(CanonDecl, FirstLocal);
4134 // Load the list of other redeclarations from this module file.
4135 ModuleFile *M = getOwningModuleFile(FirstLocal);
4136 assert(M && "imported decl from no module file");
4138 llvm::BitstreamCursor &Cursor = M->DeclsCursor;
4139 SavedStreamPosition SavedPosition(Cursor);
4140 if (llvm::Error JumpFailed = Cursor.JumpToBit(LocalOffset))
4141 llvm::report_fatal_error(
4142 "ASTReader::loadPendingDeclChain failed jumping: " +
4143 toString(std::move(JumpFailed)));
4146 Expected<unsigned> MaybeCode = Cursor.ReadCode();
4148 llvm::report_fatal_error(
4149 "ASTReader::loadPendingDeclChain failed reading code: " +
4150 toString(MaybeCode.takeError()));
4151 unsigned Code = MaybeCode.get();
4152 if (Expected<unsigned> MaybeRecCode = Cursor.readRecord(Code, Record))
4153 assert(MaybeRecCode.get() == LOCAL_REDECLARATIONS &&
4154 "expected LOCAL_REDECLARATIONS record!");
4156 llvm::report_fatal_error(
4157 "ASTReader::loadPendingDeclChain failed reading rec code: " +
4158 toString(MaybeCode.takeError()));
4160 // FIXME: We have several different dispatches on decl kind here; maybe
4161 // we should instead generate one loop per kind and dispatch up-front?
4162 Decl *MostRecent = FirstLocal;
4163 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
4164 auto *D = GetLocalDecl(*M, Record[N - I - 1]);
4165 ASTDeclReader::attachPreviousDecl(*this, D, MostRecent, CanonDecl);
4168 ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent);
4173 /// Given an ObjC interface, goes through the modules and links to the
4174 /// interface all the categories for it.
4175 class ObjCCategoriesVisitor {
4177 ObjCInterfaceDecl *Interface;
4178 llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized;
4179 ObjCCategoryDecl *Tail = nullptr;
4180 llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
4181 serialization::GlobalDeclID InterfaceID;
4182 unsigned PreviousGeneration;
4184 void add(ObjCCategoryDecl *Cat) {
4185 // Only process each category once.
4186 if (!Deserialized.erase(Cat))
4189 // Check for duplicate categories.
4190 if (Cat->getDeclName()) {
4191 ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
4193 Reader.getOwningModuleFile(Existing)
4194 != Reader.getOwningModuleFile(Cat)) {
4195 // FIXME: We should not warn for duplicates in diamond:
4203 // If there are duplicates in ML/MR, there will be warning when
4204 // creating MB *and* when importing MB. We should not warn when
4206 Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
4207 << Interface->getDeclName() << Cat->getDeclName();
4208 Reader.Diag(Existing->getLocation(), diag::note_previous_definition);
4209 } else if (!Existing) {
4210 // Record this category.
4215 // Add this category to the end of the chain.
4217 ASTDeclReader::setNextObjCCategory(Tail, Cat);
4219 Interface->setCategoryListRaw(Cat);
4224 ObjCCategoriesVisitor(ASTReader &Reader,
4225 ObjCInterfaceDecl *Interface,
4226 llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized,
4227 serialization::GlobalDeclID InterfaceID,
4228 unsigned PreviousGeneration)
4229 : Reader(Reader), Interface(Interface), Deserialized(Deserialized),
4230 InterfaceID(InterfaceID), PreviousGeneration(PreviousGeneration) {
4231 // Populate the name -> category map with the set of known categories.
4232 for (auto *Cat : Interface->known_categories()) {
4233 if (Cat->getDeclName())
4234 NameCategoryMap[Cat->getDeclName()] = Cat;
4236 // Keep track of the tail of the category list.
4241 bool operator()(ModuleFile &M) {
4242 // If we've loaded all of the category information we care about from
4243 // this module file, we're done.
4244 if (M.Generation <= PreviousGeneration)
4247 // Map global ID of the definition down to the local ID used in this
4248 // module file. If there is no such mapping, we'll find nothing here
4249 // (or in any module it imports).
4250 DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID);
4254 // Perform a binary search to find the local redeclarations for this
4255 // declaration (if any).
4256 const ObjCCategoriesInfo Compare = { LocalID, 0 };
4257 const ObjCCategoriesInfo *Result
4258 = std::lower_bound(M.ObjCCategoriesMap,
4259 M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap,
4261 if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap ||
4262 Result->DefinitionID != LocalID) {
4263 // We didn't find anything. If the class definition is in this module
4264 // file, then the module files it depends on cannot have any categories,
4265 // so suppress further lookup.
4266 return Reader.isDeclIDFromModule(InterfaceID, M);
4269 // We found something. Dig out all of the categories.
4270 unsigned Offset = Result->Offset;
4271 unsigned N = M.ObjCCategories[Offset];
4272 M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again
4273 for (unsigned I = 0; I != N; ++I)
4274 add(cast_or_null<ObjCCategoryDecl>(
4275 Reader.GetLocalDecl(M, M.ObjCCategories[Offset++])));
4282 void ASTReader::loadObjCCategories(serialization::GlobalDeclID ID,
4283 ObjCInterfaceDecl *D,
4284 unsigned PreviousGeneration) {
4285 ObjCCategoriesVisitor Visitor(*this, D, CategoriesDeserialized, ID,
4286 PreviousGeneration);
4287 ModuleMgr.visit(Visitor);
4290 template<typename DeclT, typename Fn>
4291 static void forAllLaterRedecls(DeclT *D, Fn F) {
4294 // Check whether we've already merged D into its redeclaration chain.
4295 // MostRecent may or may not be nullptr if D has not been merged. If
4296 // not, walk the merged redecl chain and see if it's there.
4297 auto *MostRecent = D->getMostRecentDecl();
4299 for (auto *Redecl = MostRecent; Redecl && !Found;
4300 Redecl = Redecl->getPreviousDecl())
4301 Found = (Redecl == D);
4303 // If this declaration is merged, apply the functor to all later decls.
4305 for (auto *Redecl = MostRecent; Redecl != D;
4306 Redecl = Redecl->getPreviousDecl())
4311 void ASTDeclReader::UpdateDecl(Decl *D,
4312 llvm::SmallVectorImpl<serialization::DeclID> &PendingLazySpecializationIDs) {
4313 while (Record.getIdx() < Record.size()) {
4314 switch ((DeclUpdateKind)Record.readInt()) {
4315 case UPD_CXX_ADDED_IMPLICIT_MEMBER: {
4316 auto *RD = cast<CXXRecordDecl>(D);
4317 // FIXME: If we also have an update record for instantiating the
4318 // definition of D, we need that to happen before we get here.
4319 Decl *MD = Record.readDecl();
4320 assert(MD && "couldn't read decl from update record");
4321 // FIXME: We should call addHiddenDecl instead, to add the member
4322 // to its DeclContext.
4323 RD->addedMember(MD);
4327 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
4328 // It will be added to the template's lazy specialization set.
4329 PendingLazySpecializationIDs.push_back(readDeclID());
4332 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
4333 auto *Anon = readDeclAs<NamespaceDecl>();
4335 // Each module has its own anonymous namespace, which is disjoint from
4336 // any other module's anonymous namespaces, so don't attach the anonymous
4337 // namespace at all.
4338 if (!Record.isModule()) {
4339 if (auto *TU = dyn_cast<TranslationUnitDecl>(D))
4340 TU->setAnonymousNamespace(Anon);
4342 cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon);
4347 case UPD_CXX_ADDED_VAR_DEFINITION: {
4348 auto *VD = cast<VarDecl>(D);
4349 VD->NonParmVarDeclBits.IsInline = Record.readInt();
4350 VD->NonParmVarDeclBits.IsInlineSpecified = Record.readInt();
4351 uint64_t Val = Record.readInt();
4352 if (Val && !VD->getInit()) {
4353 VD->setInit(Record.readExpr());
4354 if (Val > 1) { // IsInitKnownICE = 1, IsInitNotICE = 2, IsInitICE = 3
4355 EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
4356 Eval->CheckedICE = true;
4357 Eval->IsICE = Val == 3;
4363 case UPD_CXX_POINT_OF_INSTANTIATION: {
4364 SourceLocation POI = Record.readSourceLocation();
4365 if (auto *VTSD = dyn_cast<VarTemplateSpecializationDecl>(D)) {
4366 VTSD->setPointOfInstantiation(POI);
4367 } else if (auto *VD = dyn_cast<VarDecl>(D)) {
4368 VD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
4370 auto *FD = cast<FunctionDecl>(D);
4371 if (auto *FTSInfo = FD->TemplateOrSpecialization
4372 .dyn_cast<FunctionTemplateSpecializationInfo *>())
4373 FTSInfo->setPointOfInstantiation(POI);
4375 FD->TemplateOrSpecialization.get<MemberSpecializationInfo *>()
4376 ->setPointOfInstantiation(POI);
4381 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT: {
4382 auto *Param = cast<ParmVarDecl>(D);
4384 // We have to read the default argument regardless of whether we use it
4385 // so that hypothetical further update records aren't messed up.
4386 // TODO: Add a function to skip over the next expr record.
4387 auto *DefaultArg = Record.readExpr();
4389 // Only apply the update if the parameter still has an uninstantiated
4390 // default argument.
4391 if (Param->hasUninstantiatedDefaultArg())
4392 Param->setDefaultArg(DefaultArg);
4396 case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER: {
4397 auto *FD = cast<FieldDecl>(D);
4398 auto *DefaultInit = Record.readExpr();
4400 // Only apply the update if the field still has an uninstantiated
4401 // default member initializer.
4402 if (FD->hasInClassInitializer() && !FD->getInClassInitializer()) {
4404 FD->setInClassInitializer(DefaultInit);
4406 // Instantiation failed. We can get here if we serialized an AST for
4407 // an invalid program.
4408 FD->removeInClassInitializer();
4413 case UPD_CXX_ADDED_FUNCTION_DEFINITION: {
4414 auto *FD = cast<FunctionDecl>(D);
4415 if (Reader.PendingBodies[FD]) {
4416 // FIXME: Maybe check for ODR violations.
4417 // It's safe to stop now because this update record is always last.
4421 if (Record.readInt()) {
4422 // Maintain AST consistency: any later redeclarations of this function
4423 // are inline if this one is. (We might have merged another declaration
4425 forAllLaterRedecls(FD, [](FunctionDecl *FD) {
4426 FD->setImplicitlyInline();
4429 FD->setInnerLocStart(readSourceLocation());
4430 ReadFunctionDefinition(FD);
4431 assert(Record.getIdx() == Record.size() && "lazy body must be last");
4435 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4436 auto *RD = cast<CXXRecordDecl>(D);
4437 auto *OldDD = RD->getCanonicalDecl()->DefinitionData;
4438 bool HadRealDefinition =
4439 OldDD && (OldDD->Definition != RD ||
4440 !Reader.PendingFakeDefinitionData.count(OldDD));
4441 RD->setParamDestroyedInCallee(Record.readInt());
4442 RD->setArgPassingRestrictions(
4443 (RecordDecl::ArgPassingKind)Record.readInt());
4444 ReadCXXRecordDefinition(RD, /*Update*/true);
4446 // Visible update is handled separately.
4447 uint64_t LexicalOffset = ReadLocalOffset();
4448 if (!HadRealDefinition && LexicalOffset) {
4449 Record.readLexicalDeclContextStorage(LexicalOffset, RD);
4450 Reader.PendingFakeDefinitionData.erase(OldDD);
4453 auto TSK = (TemplateSpecializationKind)Record.readInt();
4454 SourceLocation POI = readSourceLocation();
4455 if (MemberSpecializationInfo *MSInfo =
4456 RD->getMemberSpecializationInfo()) {
4457 MSInfo->setTemplateSpecializationKind(TSK);
4458 MSInfo->setPointOfInstantiation(POI);
4460 auto *Spec = cast<ClassTemplateSpecializationDecl>(RD);
4461 Spec->setTemplateSpecializationKind(TSK);
4462 Spec->setPointOfInstantiation(POI);
4464 if (Record.readInt()) {
4466 readDeclAs<ClassTemplatePartialSpecializationDecl>();
4467 SmallVector<TemplateArgument, 8> TemplArgs;
4468 Record.readTemplateArgumentList(TemplArgs);
4469 auto *TemplArgList = TemplateArgumentList::CreateCopy(
4470 Reader.getContext(), TemplArgs);
4472 // FIXME: If we already have a partial specialization set,
4473 // check that it matches.
4474 if (!Spec->getSpecializedTemplateOrPartial()
4475 .is<ClassTemplatePartialSpecializationDecl *>())
4476 Spec->setInstantiationOf(PartialSpec, TemplArgList);
4480 RD->setTagKind((TagTypeKind)Record.readInt());
4481 RD->setLocation(readSourceLocation());
4482 RD->setLocStart(readSourceLocation());
4483 RD->setBraceRange(readSourceRange());
4485 if (Record.readInt()) {
4487 Record.readAttributes(Attrs);
4488 // If the declaration already has attributes, we assume that some other
4489 // AST file already loaded them.
4491 D->setAttrsImpl(Attrs, Reader.getContext());
4496 case UPD_CXX_RESOLVED_DTOR_DELETE: {
4497 // Set the 'operator delete' directly to avoid emitting another update
4499 auto *Del = readDeclAs<FunctionDecl>();
4500 auto *First = cast<CXXDestructorDecl>(D->getCanonicalDecl());
4501 auto *ThisArg = Record.readExpr();
4502 // FIXME: Check consistency if we have an old and new operator delete.
4503 if (!First->OperatorDelete) {
4504 First->OperatorDelete = Del;
4505 First->OperatorDeleteThisArg = ThisArg;
4510 case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {
4511 SmallVector<QualType, 8> ExceptionStorage;
4512 auto ESI = Record.readExceptionSpecInfo(ExceptionStorage);
4514 // Update this declaration's exception specification, if needed.
4515 auto *FD = cast<FunctionDecl>(D);
4516 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
4517 // FIXME: If the exception specification is already present, check that it
4519 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
4520 FD->setType(Reader.getContext().getFunctionType(
4521 FPT->getReturnType(), FPT->getParamTypes(),
4522 FPT->getExtProtoInfo().withExceptionSpec(ESI)));
4524 // When we get to the end of deserializing, see if there are other decls
4525 // that we need to propagate this exception specification onto.
4526 Reader.PendingExceptionSpecUpdates.insert(
4527 std::make_pair(FD->getCanonicalDecl(), FD));
4532 case UPD_CXX_DEDUCED_RETURN_TYPE: {
4533 auto *FD = cast<FunctionDecl>(D);
4534 QualType DeducedResultType = Record.readType();
4535 Reader.PendingDeducedTypeUpdates.insert(
4536 {FD->getCanonicalDecl(), DeducedResultType});
4540 case UPD_DECL_MARKED_USED:
4541 // Maintain AST consistency: any later redeclarations are used too.
4542 D->markUsed(Reader.getContext());
4545 case UPD_MANGLING_NUMBER:
4546 Reader.getContext().setManglingNumber(cast<NamedDecl>(D),
4550 case UPD_STATIC_LOCAL_NUMBER:
4551 Reader.getContext().setStaticLocalNumber(cast<VarDecl>(D),
4555 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
4556 D->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
4557 Reader.getContext(), readSourceRange(),
4558 AttributeCommonInfo::AS_Pragma));
4561 case UPD_DECL_MARKED_OPENMP_ALLOCATE: {
4562 auto AllocatorKind =
4563 static_cast<OMPAllocateDeclAttr::AllocatorTypeTy>(Record.readInt());
4564 Expr *Allocator = Record.readExpr();
4565 SourceRange SR = readSourceRange();
4566 D->addAttr(OMPAllocateDeclAttr::CreateImplicit(
4567 Reader.getContext(), AllocatorKind, Allocator, SR,
4568 AttributeCommonInfo::AS_Pragma));
4572 case UPD_DECL_EXPORTED: {
4573 unsigned SubmoduleID = readSubmoduleID();
4574 auto *Exported = cast<NamedDecl>(D);
4575 Module *Owner = SubmoduleID ? Reader.getSubmodule(SubmoduleID) : nullptr;
4576 Reader.getContext().mergeDefinitionIntoModule(Exported, Owner);
4577 Reader.PendingMergedDefinitionsToDeduplicate.insert(Exported);
4581 case UPD_DECL_MARKED_OPENMP_DECLARETARGET: {
4582 OMPDeclareTargetDeclAttr::MapTypeTy MapType =
4583 static_cast<OMPDeclareTargetDeclAttr::MapTypeTy>(Record.readInt());
4584 OMPDeclareTargetDeclAttr::DevTypeTy DevType =
4585 static_cast<OMPDeclareTargetDeclAttr::DevTypeTy>(Record.readInt());
4586 D->addAttr(OMPDeclareTargetDeclAttr::CreateImplicit(
4587 Reader.getContext(), MapType, DevType, readSourceRange(),
4588 AttributeCommonInfo::AS_Pragma));
4592 case UPD_ADDED_ATTR_TO_RECORD:
4594 Record.readAttributes(Attrs);
4595 assert(Attrs.size() == 1);
4596 D->addAttr(Attrs[0]);