1 //===--- ASTReaderDecl.cpp - Decl Deserialization ---------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the ASTReader::ReadDeclRecord method, which is the
11 // entrypoint for loading a decl.
13 //===----------------------------------------------------------------------===//
15 #include "ASTCommon.h"
16 #include "ASTReaderInternals.h"
17 #include "clang/AST/ASTContext.h"
18 #include "clang/AST/DeclCXX.h"
19 #include "clang/AST/DeclGroup.h"
20 #include "clang/AST/DeclTemplate.h"
21 #include "clang/AST/DeclVisitor.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/Sema/IdentifierResolver.h"
24 #include "clang/Sema/SemaDiagnostic.h"
25 #include "clang/Serialization/ASTReader.h"
26 #include "llvm/Support/SaveAndRestore.h"
28 using namespace clang;
29 using namespace clang::serialization;
31 //===----------------------------------------------------------------------===//
32 // Declaration deserialization
33 //===----------------------------------------------------------------------===//
36 class ASTDeclReader : public DeclVisitor<ASTDeclReader, void> {
38 ASTRecordReader &Record;
39 ASTReader::RecordLocation Loc;
40 const DeclID ThisDeclID;
41 const SourceLocation ThisDeclLoc;
42 typedef ASTReader::RecordData RecordData;
43 TypeID TypeIDForTypeDecl;
44 unsigned AnonymousDeclNumber;
45 GlobalDeclID NamedDeclForTagDecl;
46 IdentifierInfo *TypedefNameForLinkage;
50 ///\brief A flag to carry the information for a decl from the entity is
51 /// used. We use it to delay the marking of the canonical decl as used until
52 /// the entire declaration is deserialized and merged.
53 bool IsDeclMarkedUsed;
55 uint64_t GetCurrentCursorOffset();
57 uint64_t ReadLocalOffset() {
58 uint64_t LocalOffset = Record.readInt();
59 assert(LocalOffset < Loc.Offset && "offset point after current record");
60 return LocalOffset ? Loc.Offset - LocalOffset : 0;
63 uint64_t ReadGlobalOffset() {
64 uint64_t Local = ReadLocalOffset();
65 return Local ? Record.getGlobalBitOffset(Local) : 0;
68 SourceLocation ReadSourceLocation() {
69 return Record.readSourceLocation();
72 SourceRange ReadSourceRange() {
73 return Record.readSourceRange();
76 TypeSourceInfo *GetTypeSourceInfo() {
77 return Record.getTypeSourceInfo();
80 serialization::DeclID ReadDeclID() {
81 return Record.readDeclID();
84 std::string ReadString() {
85 return Record.readString();
88 void ReadDeclIDList(SmallVectorImpl<DeclID> &IDs) {
89 for (unsigned I = 0, Size = Record.readInt(); I != Size; ++I)
90 IDs.push_back(ReadDeclID());
94 return Record.readDecl();
99 return Record.readDeclAs<T>();
102 void ReadQualifierInfo(QualifierInfo &Info) {
103 Record.readQualifierInfo(Info);
106 void ReadDeclarationNameLoc(DeclarationNameLoc &DNLoc, DeclarationName Name) {
107 Record.readDeclarationNameLoc(DNLoc, Name);
110 serialization::SubmoduleID readSubmoduleID() {
111 if (Record.getIdx() == Record.size())
114 return Record.getGlobalSubmoduleID(Record.readInt());
117 Module *readModule() {
118 return Record.getSubmodule(readSubmoduleID());
121 void ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update);
122 void ReadCXXDefinitionData(struct CXXRecordDecl::DefinitionData &Data,
123 const CXXRecordDecl *D);
124 void MergeDefinitionData(CXXRecordDecl *D,
125 struct CXXRecordDecl::DefinitionData &&NewDD);
126 void ReadObjCDefinitionData(struct ObjCInterfaceDecl::DefinitionData &Data);
127 void MergeDefinitionData(ObjCInterfaceDecl *D,
128 struct ObjCInterfaceDecl::DefinitionData &&NewDD);
130 static NamedDecl *getAnonymousDeclForMerging(ASTReader &Reader,
133 static void setAnonymousDeclForMerging(ASTReader &Reader, DeclContext *DC,
134 unsigned Index, NamedDecl *D);
136 /// Results from loading a RedeclarableDecl.
137 class RedeclarableResult {
139 GlobalDeclID FirstID;
143 RedeclarableResult(Decl *MergeWith, GlobalDeclID FirstID, bool IsKeyDecl)
144 : MergeWith(MergeWith), FirstID(FirstID), IsKeyDecl(IsKeyDecl) {}
146 /// \brief Retrieve the first ID.
147 GlobalDeclID getFirstID() const { return FirstID; }
149 /// \brief Is this declaration a key declaration?
150 bool isKeyDecl() const { return IsKeyDecl; }
152 /// \brief Get a known declaration that this should be merged with, if
154 Decl *getKnownMergeTarget() const { return MergeWith; }
157 /// \brief Class used to capture the result of searching for an existing
158 /// declaration of a specific kind and name, along with the ability
159 /// to update the place where this result was found (the declaration
160 /// chain hanging off an identifier or the DeclContext we searched in)
162 class FindExistingResult {
168 unsigned AnonymousDeclNumber;
169 IdentifierInfo *TypedefNameForLinkage;
171 void operator=(FindExistingResult &&) = delete;
174 FindExistingResult(ASTReader &Reader)
175 : Reader(Reader), New(nullptr), Existing(nullptr), AddResult(false),
176 AnonymousDeclNumber(0), TypedefNameForLinkage(nullptr) {}
178 FindExistingResult(ASTReader &Reader, NamedDecl *New, NamedDecl *Existing,
179 unsigned AnonymousDeclNumber,
180 IdentifierInfo *TypedefNameForLinkage)
181 : Reader(Reader), New(New), Existing(Existing), AddResult(true),
182 AnonymousDeclNumber(AnonymousDeclNumber),
183 TypedefNameForLinkage(TypedefNameForLinkage) {}
185 FindExistingResult(FindExistingResult &&Other)
186 : Reader(Other.Reader), New(Other.New), Existing(Other.Existing),
187 AddResult(Other.AddResult),
188 AnonymousDeclNumber(Other.AnonymousDeclNumber),
189 TypedefNameForLinkage(Other.TypedefNameForLinkage) {
190 Other.AddResult = false;
193 ~FindExistingResult();
195 /// \brief Suppress the addition of this result into the known set of
197 void suppress() { AddResult = false; }
199 operator NamedDecl*() const { return Existing; }
202 operator T*() const { return dyn_cast_or_null<T>(Existing); }
205 static DeclContext *getPrimaryContextForMerging(ASTReader &Reader,
207 FindExistingResult findExisting(NamedDecl *D);
210 ASTDeclReader(ASTReader &Reader, ASTRecordReader &Record,
211 ASTReader::RecordLocation Loc,
212 DeclID thisDeclID, SourceLocation ThisDeclLoc)
213 : Reader(Reader), Record(Record), Loc(Loc),
214 ThisDeclID(thisDeclID), ThisDeclLoc(ThisDeclLoc),
215 TypeIDForTypeDecl(0), NamedDeclForTagDecl(0),
216 TypedefNameForLinkage(nullptr), HasPendingBody(false),
217 IsDeclMarkedUsed(false) {}
219 template <typename DeclT>
220 static Decl *getMostRecentDeclImpl(Redeclarable<DeclT> *D);
221 static Decl *getMostRecentDeclImpl(...);
222 static Decl *getMostRecentDecl(Decl *D);
224 template <typename DeclT>
225 static void attachPreviousDeclImpl(ASTReader &Reader,
226 Redeclarable<DeclT> *D, Decl *Previous,
228 static void attachPreviousDeclImpl(ASTReader &Reader, ...);
229 static void attachPreviousDecl(ASTReader &Reader, Decl *D, Decl *Previous,
232 template <typename DeclT>
233 static void attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest);
234 static void attachLatestDeclImpl(...);
235 static void attachLatestDecl(Decl *D, Decl *latest);
237 template <typename DeclT>
238 static void markIncompleteDeclChainImpl(Redeclarable<DeclT> *D);
239 static void markIncompleteDeclChainImpl(...);
241 /// \brief Determine whether this declaration has a pending body.
242 bool hasPendingBody() const { return HasPendingBody; }
244 void ReadFunctionDefinition(FunctionDecl *FD);
247 void UpdateDecl(Decl *D);
249 static void setNextObjCCategory(ObjCCategoryDecl *Cat,
250 ObjCCategoryDecl *Next) {
251 Cat->NextClassCategory = Next;
254 void VisitDecl(Decl *D);
255 void VisitPragmaCommentDecl(PragmaCommentDecl *D);
256 void VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D);
257 void VisitTranslationUnitDecl(TranslationUnitDecl *TU);
258 void VisitNamedDecl(NamedDecl *ND);
259 void VisitLabelDecl(LabelDecl *LD);
260 void VisitNamespaceDecl(NamespaceDecl *D);
261 void VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
262 void VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
263 void VisitTypeDecl(TypeDecl *TD);
264 RedeclarableResult VisitTypedefNameDecl(TypedefNameDecl *TD);
265 void VisitTypedefDecl(TypedefDecl *TD);
266 void VisitTypeAliasDecl(TypeAliasDecl *TD);
267 void VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
268 RedeclarableResult VisitTagDecl(TagDecl *TD);
269 void VisitEnumDecl(EnumDecl *ED);
270 RedeclarableResult VisitRecordDeclImpl(RecordDecl *RD);
271 void VisitRecordDecl(RecordDecl *RD) { VisitRecordDeclImpl(RD); }
272 RedeclarableResult VisitCXXRecordDeclImpl(CXXRecordDecl *D);
273 void VisitCXXRecordDecl(CXXRecordDecl *D) { VisitCXXRecordDeclImpl(D); }
274 RedeclarableResult VisitClassTemplateSpecializationDeclImpl(
275 ClassTemplateSpecializationDecl *D);
276 void VisitClassTemplateSpecializationDecl(
277 ClassTemplateSpecializationDecl *D) {
278 VisitClassTemplateSpecializationDeclImpl(D);
280 void VisitClassTemplatePartialSpecializationDecl(
281 ClassTemplatePartialSpecializationDecl *D);
282 void VisitClassScopeFunctionSpecializationDecl(
283 ClassScopeFunctionSpecializationDecl *D);
285 VisitVarTemplateSpecializationDeclImpl(VarTemplateSpecializationDecl *D);
286 void VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D) {
287 VisitVarTemplateSpecializationDeclImpl(D);
289 void VisitVarTemplatePartialSpecializationDecl(
290 VarTemplatePartialSpecializationDecl *D);
291 void VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
292 void VisitValueDecl(ValueDecl *VD);
293 void VisitEnumConstantDecl(EnumConstantDecl *ECD);
294 void VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
295 void VisitDeclaratorDecl(DeclaratorDecl *DD);
296 void VisitFunctionDecl(FunctionDecl *FD);
297 void VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *GD);
298 void VisitCXXMethodDecl(CXXMethodDecl *D);
299 void VisitCXXConstructorDecl(CXXConstructorDecl *D);
300 void VisitCXXDestructorDecl(CXXDestructorDecl *D);
301 void VisitCXXConversionDecl(CXXConversionDecl *D);
302 void VisitFieldDecl(FieldDecl *FD);
303 void VisitMSPropertyDecl(MSPropertyDecl *FD);
304 void VisitIndirectFieldDecl(IndirectFieldDecl *FD);
305 RedeclarableResult VisitVarDeclImpl(VarDecl *D);
306 void VisitVarDecl(VarDecl *VD) { VisitVarDeclImpl(VD); }
307 void VisitImplicitParamDecl(ImplicitParamDecl *PD);
308 void VisitParmVarDecl(ParmVarDecl *PD);
309 void VisitDecompositionDecl(DecompositionDecl *DD);
310 void VisitBindingDecl(BindingDecl *BD);
311 void VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
312 DeclID VisitTemplateDecl(TemplateDecl *D);
313 RedeclarableResult VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D);
314 void VisitClassTemplateDecl(ClassTemplateDecl *D);
315 void VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D);
316 void VisitVarTemplateDecl(VarTemplateDecl *D);
317 void VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
318 void VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
319 void VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
320 void VisitUsingDecl(UsingDecl *D);
321 void VisitUsingPackDecl(UsingPackDecl *D);
322 void VisitUsingShadowDecl(UsingShadowDecl *D);
323 void VisitConstructorUsingShadowDecl(ConstructorUsingShadowDecl *D);
324 void VisitLinkageSpecDecl(LinkageSpecDecl *D);
325 void VisitExportDecl(ExportDecl *D);
326 void VisitFileScopeAsmDecl(FileScopeAsmDecl *AD);
327 void VisitImportDecl(ImportDecl *D);
328 void VisitAccessSpecDecl(AccessSpecDecl *D);
329 void VisitFriendDecl(FriendDecl *D);
330 void VisitFriendTemplateDecl(FriendTemplateDecl *D);
331 void VisitStaticAssertDecl(StaticAssertDecl *D);
332 void VisitBlockDecl(BlockDecl *BD);
333 void VisitCapturedDecl(CapturedDecl *CD);
334 void VisitEmptyDecl(EmptyDecl *D);
336 std::pair<uint64_t, uint64_t> VisitDeclContext(DeclContext *DC);
339 RedeclarableResult VisitRedeclarable(Redeclarable<T> *D);
342 void mergeRedeclarable(Redeclarable<T> *D, RedeclarableResult &Redecl,
343 DeclID TemplatePatternID = 0);
346 void mergeRedeclarable(Redeclarable<T> *D, T *Existing,
347 RedeclarableResult &Redecl,
348 DeclID TemplatePatternID = 0);
351 void mergeMergeable(Mergeable<T> *D);
353 void mergeTemplatePattern(RedeclarableTemplateDecl *D,
354 RedeclarableTemplateDecl *Existing,
355 DeclID DsID, bool IsKeyDecl);
357 ObjCTypeParamList *ReadObjCTypeParamList();
359 // FIXME: Reorder according to DeclNodes.td?
360 void VisitObjCMethodDecl(ObjCMethodDecl *D);
361 void VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
362 void VisitObjCContainerDecl(ObjCContainerDecl *D);
363 void VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
364 void VisitObjCIvarDecl(ObjCIvarDecl *D);
365 void VisitObjCProtocolDecl(ObjCProtocolDecl *D);
366 void VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *D);
367 void VisitObjCCategoryDecl(ObjCCategoryDecl *D);
368 void VisitObjCImplDecl(ObjCImplDecl *D);
369 void VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
370 void VisitObjCImplementationDecl(ObjCImplementationDecl *D);
371 void VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *D);
372 void VisitObjCPropertyDecl(ObjCPropertyDecl *D);
373 void VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
374 void VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D);
375 void VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D);
376 void VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D);
378 } // end namespace clang
381 /// Iterator over the redeclarations of a declaration that have already
382 /// been merged into the same redeclaration chain.
383 template<typename DeclT>
384 class MergedRedeclIterator {
385 DeclT *Start, *Canonical, *Current;
387 MergedRedeclIterator() : Current(nullptr) {}
388 MergedRedeclIterator(DeclT *Start)
389 : Start(Start), Canonical(nullptr), Current(Start) {}
391 DeclT *operator*() { return Current; }
393 MergedRedeclIterator &operator++() {
394 if (Current->isFirstDecl()) {
396 Current = Current->getMostRecentDecl();
398 Current = Current->getPreviousDecl();
400 // If we started in the merged portion, we'll reach our start position
401 // eventually. Otherwise, we'll never reach it, but the second declaration
402 // we reached was the canonical declaration, so stop when we see that one
404 if (Current == Start || Current == Canonical)
409 friend bool operator!=(const MergedRedeclIterator &A,
410 const MergedRedeclIterator &B) {
411 return A.Current != B.Current;
414 } // end anonymous namespace
416 template <typename DeclT>
417 static llvm::iterator_range<MergedRedeclIterator<DeclT>>
418 merged_redecls(DeclT *D) {
419 return llvm::make_range(MergedRedeclIterator<DeclT>(D),
420 MergedRedeclIterator<DeclT>());
423 uint64_t ASTDeclReader::GetCurrentCursorOffset() {
424 return Loc.F->DeclsCursor.GetCurrentBitNo() + Loc.F->GlobalBitOffset;
427 void ASTDeclReader::ReadFunctionDefinition(FunctionDecl *FD) {
428 if (Record.readInt())
429 Reader.BodySource[FD] = Loc.F->Kind == ModuleKind::MK_MainFile;
430 if (auto *CD = dyn_cast<CXXConstructorDecl>(FD)) {
431 CD->NumCtorInitializers = Record.readInt();
432 if (CD->NumCtorInitializers)
433 CD->CtorInitializers = ReadGlobalOffset();
435 // Store the offset of the body so we can lazily load it later.
436 Reader.PendingBodies[FD] = GetCurrentCursorOffset();
437 HasPendingBody = true;
440 void ASTDeclReader::Visit(Decl *D) {
441 DeclVisitor<ASTDeclReader, void>::Visit(D);
443 // At this point we have deserialized and merged the decl and it is safe to
444 // update its canonical decl to signal that the entire entity is used.
445 D->getCanonicalDecl()->Used |= IsDeclMarkedUsed;
446 IsDeclMarkedUsed = false;
448 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
450 DeclaratorDecl::ExtInfo *Info =
451 DD->DeclInfo.get<DeclaratorDecl::ExtInfo *>();
452 Info->TInfo = GetTypeSourceInfo();
455 DD->DeclInfo = GetTypeSourceInfo();
459 if (TypeDecl *TD = dyn_cast<TypeDecl>(D)) {
460 // We have a fully initialized TypeDecl. Read its type now.
461 TD->setTypeForDecl(Reader.GetType(TypeIDForTypeDecl).getTypePtrOrNull());
463 // If this is a tag declaration with a typedef name for linkage, it's safe
464 // to load that typedef now.
465 if (NamedDeclForTagDecl)
466 cast<TagDecl>(D)->TypedefNameDeclOrQualifier =
467 cast<TypedefNameDecl>(Reader.GetDecl(NamedDeclForTagDecl));
468 } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
469 // if we have a fully initialized TypeDecl, we can safely read its type now.
470 ID->TypeForDecl = Reader.GetType(TypeIDForTypeDecl).getTypePtrOrNull();
471 } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
472 // FunctionDecl's body was written last after all other Stmts/Exprs.
473 // We only read it if FD doesn't already have a body (e.g., from another
475 // FIXME: Can we diagnose ODR violations somehow?
476 if (Record.readInt())
477 ReadFunctionDefinition(FD);
481 void ASTDeclReader::VisitDecl(Decl *D) {
482 if (D->isTemplateParameter() || D->isTemplateParameterPack() ||
483 isa<ParmVarDecl>(D)) {
484 // We don't want to deserialize the DeclContext of a template
485 // parameter or of a parameter of a function template immediately. These
486 // entities might be used in the formulation of its DeclContext (for
487 // example, a function parameter can be used in decltype() in trailing
488 // return type of the function). Use the translation unit DeclContext as a
490 GlobalDeclID SemaDCIDForTemplateParmDecl = ReadDeclID();
491 GlobalDeclID LexicalDCIDForTemplateParmDecl = ReadDeclID();
492 if (!LexicalDCIDForTemplateParmDecl)
493 LexicalDCIDForTemplateParmDecl = SemaDCIDForTemplateParmDecl;
494 Reader.addPendingDeclContextInfo(D,
495 SemaDCIDForTemplateParmDecl,
496 LexicalDCIDForTemplateParmDecl);
497 D->setDeclContext(Reader.getContext().getTranslationUnitDecl());
499 DeclContext *SemaDC = ReadDeclAs<DeclContext>();
500 DeclContext *LexicalDC = ReadDeclAs<DeclContext>();
503 DeclContext *MergedSemaDC = Reader.MergedDeclContexts.lookup(SemaDC);
504 // Avoid calling setLexicalDeclContext() directly because it uses
505 // Decl::getASTContext() internally which is unsafe during derialization.
506 D->setDeclContextsImpl(MergedSemaDC ? MergedSemaDC : SemaDC, LexicalDC,
507 Reader.getContext());
509 D->setLocation(ThisDeclLoc);
510 D->setInvalidDecl(Record.readInt());
511 if (Record.readInt()) { // hasAttrs
513 Record.readAttributes(Attrs);
514 // Avoid calling setAttrs() directly because it uses Decl::getASTContext()
515 // internally which is unsafe during derialization.
516 D->setAttrsImpl(Attrs, Reader.getContext());
518 D->setImplicit(Record.readInt());
519 D->Used = Record.readInt();
520 IsDeclMarkedUsed |= D->Used;
521 D->setReferenced(Record.readInt());
522 D->setTopLevelDeclInObjCContainer(Record.readInt());
523 D->setAccess((AccessSpecifier)Record.readInt());
524 D->FromASTFile = true;
525 bool ModulePrivate = Record.readInt();
527 // Determine whether this declaration is part of a (sub)module. If so, it
528 // may not yet be visible.
529 if (unsigned SubmoduleID = readSubmoduleID()) {
530 // Store the owning submodule ID in the declaration.
531 D->setModuleOwnershipKind(
532 ModulePrivate ? Decl::ModuleOwnershipKind::ModulePrivate
533 : Decl::ModuleOwnershipKind::VisibleWhenImported);
534 D->setOwningModuleID(SubmoduleID);
537 // Module-private declarations are never visible, so there is no work to
539 } else if (Reader.getContext().getLangOpts().ModulesLocalVisibility) {
540 // If local visibility is being tracked, this declaration will become
541 // hidden and visible as the owning module does.
542 } else if (Module *Owner = Reader.getSubmodule(SubmoduleID)) {
543 // Mark the declaration as visible when its owning module becomes visible.
544 if (Owner->NameVisibility == Module::AllVisible)
545 D->setVisibleDespiteOwningModule();
547 Reader.HiddenNamesMap[Owner].push_back(D);
552 void ASTDeclReader::VisitPragmaCommentDecl(PragmaCommentDecl *D) {
554 D->setLocation(ReadSourceLocation());
555 D->CommentKind = (PragmaMSCommentKind)Record.readInt();
556 std::string Arg = ReadString();
557 memcpy(D->getTrailingObjects<char>(), Arg.data(), Arg.size());
558 D->getTrailingObjects<char>()[Arg.size()] = '\0';
561 void ASTDeclReader::VisitPragmaDetectMismatchDecl(PragmaDetectMismatchDecl *D) {
563 D->setLocation(ReadSourceLocation());
564 std::string Name = ReadString();
565 memcpy(D->getTrailingObjects<char>(), Name.data(), Name.size());
566 D->getTrailingObjects<char>()[Name.size()] = '\0';
568 D->ValueStart = Name.size() + 1;
569 std::string Value = ReadString();
570 memcpy(D->getTrailingObjects<char>() + D->ValueStart, Value.data(),
572 D->getTrailingObjects<char>()[D->ValueStart + Value.size()] = '\0';
575 void ASTDeclReader::VisitTranslationUnitDecl(TranslationUnitDecl *TU) {
576 llvm_unreachable("Translation units are not serialized");
579 void ASTDeclReader::VisitNamedDecl(NamedDecl *ND) {
581 ND->setDeclName(Record.readDeclarationName());
582 AnonymousDeclNumber = Record.readInt();
585 void ASTDeclReader::VisitTypeDecl(TypeDecl *TD) {
587 TD->setLocStart(ReadSourceLocation());
588 // Delay type reading until after we have fully initialized the decl.
589 TypeIDForTypeDecl = Record.getGlobalTypeID(Record.readInt());
592 ASTDeclReader::RedeclarableResult
593 ASTDeclReader::VisitTypedefNameDecl(TypedefNameDecl *TD) {
594 RedeclarableResult Redecl = VisitRedeclarable(TD);
596 TypeSourceInfo *TInfo = GetTypeSourceInfo();
597 if (Record.readInt()) { // isModed
598 QualType modedT = Record.readType();
599 TD->setModedTypeSourceInfo(TInfo, modedT);
601 TD->setTypeSourceInfo(TInfo);
602 // Read and discard the declaration for which this is a typedef name for
603 // linkage, if it exists. We cannot rely on our type to pull in this decl,
604 // because it might have been merged with a type from another module and
605 // thus might not refer to our version of the declaration.
610 void ASTDeclReader::VisitTypedefDecl(TypedefDecl *TD) {
611 RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
612 mergeRedeclarable(TD, Redecl);
615 void ASTDeclReader::VisitTypeAliasDecl(TypeAliasDecl *TD) {
616 RedeclarableResult Redecl = VisitTypedefNameDecl(TD);
617 if (auto *Template = ReadDeclAs<TypeAliasTemplateDecl>())
618 // Merged when we merge the template.
619 TD->setDescribedAliasTemplate(Template);
621 mergeRedeclarable(TD, Redecl);
624 ASTDeclReader::RedeclarableResult ASTDeclReader::VisitTagDecl(TagDecl *TD) {
625 RedeclarableResult Redecl = VisitRedeclarable(TD);
628 TD->IdentifierNamespace = Record.readInt();
629 TD->setTagKind((TagDecl::TagKind)Record.readInt());
630 if (!isa<CXXRecordDecl>(TD))
631 TD->setCompleteDefinition(Record.readInt());
632 TD->setEmbeddedInDeclarator(Record.readInt());
633 TD->setFreeStanding(Record.readInt());
634 TD->setCompleteDefinitionRequired(Record.readInt());
635 TD->setBraceRange(ReadSourceRange());
637 switch (Record.readInt()) {
641 TagDecl::ExtInfo *Info = new (Reader.getContext()) TagDecl::ExtInfo();
642 ReadQualifierInfo(*Info);
643 TD->TypedefNameDeclOrQualifier = Info;
646 case 2: // TypedefNameForAnonDecl
647 NamedDeclForTagDecl = ReadDeclID();
648 TypedefNameForLinkage = Record.getIdentifierInfo();
651 llvm_unreachable("unexpected tag info kind");
654 if (!isa<CXXRecordDecl>(TD))
655 mergeRedeclarable(TD, Redecl);
659 void ASTDeclReader::VisitEnumDecl(EnumDecl *ED) {
661 if (TypeSourceInfo *TI = GetTypeSourceInfo())
662 ED->setIntegerTypeSourceInfo(TI);
664 ED->setIntegerType(Record.readType());
665 ED->setPromotionType(Record.readType());
666 ED->setNumPositiveBits(Record.readInt());
667 ED->setNumNegativeBits(Record.readInt());
668 ED->IsScoped = Record.readInt();
669 ED->IsScopedUsingClassTag = Record.readInt();
670 ED->IsFixed = Record.readInt();
672 // If this is a definition subject to the ODR, and we already have a
673 // definition, merge this one into it.
674 if (ED->IsCompleteDefinition &&
675 Reader.getContext().getLangOpts().Modules &&
676 Reader.getContext().getLangOpts().CPlusPlus) {
677 EnumDecl *&OldDef = Reader.EnumDefinitions[ED->getCanonicalDecl()];
679 // This is the first time we've seen an imported definition. Look for a
680 // local definition before deciding that we are the first definition.
681 for (auto *D : merged_redecls(ED->getCanonicalDecl())) {
682 if (!D->isFromASTFile() && D->isCompleteDefinition()) {
689 Reader.MergedDeclContexts.insert(std::make_pair(ED, OldDef));
690 ED->IsCompleteDefinition = false;
691 Reader.mergeDefinitionVisibility(OldDef, ED);
697 if (EnumDecl *InstED = ReadDeclAs<EnumDecl>()) {
698 TemplateSpecializationKind TSK =
699 (TemplateSpecializationKind)Record.readInt();
700 SourceLocation POI = ReadSourceLocation();
701 ED->setInstantiationOfMemberEnum(Reader.getContext(), InstED, TSK);
702 ED->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
706 ASTDeclReader::RedeclarableResult
707 ASTDeclReader::VisitRecordDeclImpl(RecordDecl *RD) {
708 RedeclarableResult Redecl = VisitTagDecl(RD);
709 RD->setHasFlexibleArrayMember(Record.readInt());
710 RD->setAnonymousStructOrUnion(Record.readInt());
711 RD->setHasObjectMember(Record.readInt());
712 RD->setHasVolatileMember(Record.readInt());
716 void ASTDeclReader::VisitValueDecl(ValueDecl *VD) {
718 VD->setType(Record.readType());
721 void ASTDeclReader::VisitEnumConstantDecl(EnumConstantDecl *ECD) {
723 if (Record.readInt())
724 ECD->setInitExpr(Record.readExpr());
725 ECD->setInitVal(Record.readAPSInt());
729 void ASTDeclReader::VisitDeclaratorDecl(DeclaratorDecl *DD) {
731 DD->setInnerLocStart(ReadSourceLocation());
732 if (Record.readInt()) { // hasExtInfo
733 DeclaratorDecl::ExtInfo *Info
734 = new (Reader.getContext()) DeclaratorDecl::ExtInfo();
735 ReadQualifierInfo(*Info);
740 void ASTDeclReader::VisitFunctionDecl(FunctionDecl *FD) {
741 RedeclarableResult Redecl = VisitRedeclarable(FD);
742 VisitDeclaratorDecl(FD);
744 ReadDeclarationNameLoc(FD->DNLoc, FD->getDeclName());
745 FD->IdentifierNamespace = Record.readInt();
747 // FunctionDecl's body is handled last at ASTDeclReader::Visit,
748 // after everything else is read.
750 FD->SClass = (StorageClass)Record.readInt();
751 FD->IsInline = Record.readInt();
752 FD->IsInlineSpecified = Record.readInt();
753 FD->IsExplicitSpecified = Record.readInt();
754 FD->IsVirtualAsWritten = Record.readInt();
755 FD->IsPure = Record.readInt();
756 FD->HasInheritedPrototype = Record.readInt();
757 FD->HasWrittenPrototype = Record.readInt();
758 FD->IsDeleted = Record.readInt();
759 FD->IsTrivial = Record.readInt();
760 FD->IsDefaulted = Record.readInt();
761 FD->IsExplicitlyDefaulted = Record.readInt();
762 FD->HasImplicitReturnZero = Record.readInt();
763 FD->IsConstexpr = Record.readInt();
764 FD->UsesSEHTry = Record.readInt();
765 FD->HasSkippedBody = Record.readInt();
766 FD->IsLateTemplateParsed = Record.readInt();
767 FD->setCachedLinkage(Linkage(Record.readInt()));
768 FD->EndRangeLoc = ReadSourceLocation();
770 switch ((FunctionDecl::TemplatedKind)Record.readInt()) {
771 case FunctionDecl::TK_NonTemplate:
772 mergeRedeclarable(FD, Redecl);
774 case FunctionDecl::TK_FunctionTemplate:
775 // Merged when we merge the template.
776 FD->setDescribedFunctionTemplate(ReadDeclAs<FunctionTemplateDecl>());
778 case FunctionDecl::TK_MemberSpecialization: {
779 FunctionDecl *InstFD = ReadDeclAs<FunctionDecl>();
780 TemplateSpecializationKind TSK =
781 (TemplateSpecializationKind)Record.readInt();
782 SourceLocation POI = ReadSourceLocation();
783 FD->setInstantiationOfMemberFunction(Reader.getContext(), InstFD, TSK);
784 FD->getMemberSpecializationInfo()->setPointOfInstantiation(POI);
785 mergeRedeclarable(FD, Redecl);
788 case FunctionDecl::TK_FunctionTemplateSpecialization: {
789 FunctionTemplateDecl *Template = ReadDeclAs<FunctionTemplateDecl>();
790 TemplateSpecializationKind TSK =
791 (TemplateSpecializationKind)Record.readInt();
793 // Template arguments.
794 SmallVector<TemplateArgument, 8> TemplArgs;
795 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
797 // Template args as written.
798 SmallVector<TemplateArgumentLoc, 8> TemplArgLocs;
799 SourceLocation LAngleLoc, RAngleLoc;
800 bool HasTemplateArgumentsAsWritten = Record.readInt();
801 if (HasTemplateArgumentsAsWritten) {
802 unsigned NumTemplateArgLocs = Record.readInt();
803 TemplArgLocs.reserve(NumTemplateArgLocs);
804 for (unsigned i=0; i != NumTemplateArgLocs; ++i)
805 TemplArgLocs.push_back(Record.readTemplateArgumentLoc());
807 LAngleLoc = ReadSourceLocation();
808 RAngleLoc = ReadSourceLocation();
811 SourceLocation POI = ReadSourceLocation();
813 ASTContext &C = Reader.getContext();
814 TemplateArgumentList *TemplArgList
815 = TemplateArgumentList::CreateCopy(C, TemplArgs);
816 TemplateArgumentListInfo TemplArgsInfo(LAngleLoc, RAngleLoc);
817 for (unsigned i=0, e = TemplArgLocs.size(); i != e; ++i)
818 TemplArgsInfo.addArgument(TemplArgLocs[i]);
819 FunctionTemplateSpecializationInfo *FTInfo
820 = FunctionTemplateSpecializationInfo::Create(C, FD, Template, TSK,
822 HasTemplateArgumentsAsWritten ? &TemplArgsInfo
825 FD->TemplateOrSpecialization = FTInfo;
827 if (FD->isCanonicalDecl()) { // if canonical add to template's set.
828 // The template that contains the specializations set. It's not safe to
829 // use getCanonicalDecl on Template since it may still be initializing.
830 FunctionTemplateDecl *CanonTemplate = ReadDeclAs<FunctionTemplateDecl>();
831 // Get the InsertPos by FindNodeOrInsertPos() instead of calling
832 // InsertNode(FTInfo) directly to avoid the getASTContext() call in
833 // FunctionTemplateSpecializationInfo's Profile().
834 // We avoid getASTContext because a decl in the parent hierarchy may
836 llvm::FoldingSetNodeID ID;
837 FunctionTemplateSpecializationInfo::Profile(ID, TemplArgs, C);
838 void *InsertPos = nullptr;
839 FunctionTemplateDecl::Common *CommonPtr = CanonTemplate->getCommonPtr();
840 FunctionTemplateSpecializationInfo *ExistingInfo =
841 CommonPtr->Specializations.FindNodeOrInsertPos(ID, InsertPos);
843 CommonPtr->Specializations.InsertNode(FTInfo, InsertPos);
845 assert(Reader.getContext().getLangOpts().Modules &&
846 "already deserialized this template specialization");
847 mergeRedeclarable(FD, ExistingInfo->Function, Redecl);
852 case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
854 UnresolvedSet<8> TemplDecls;
855 unsigned NumTemplates = Record.readInt();
856 while (NumTemplates--)
857 TemplDecls.addDecl(ReadDeclAs<NamedDecl>());
860 TemplateArgumentListInfo TemplArgs;
861 unsigned NumArgs = Record.readInt();
863 TemplArgs.addArgument(Record.readTemplateArgumentLoc());
864 TemplArgs.setLAngleLoc(ReadSourceLocation());
865 TemplArgs.setRAngleLoc(ReadSourceLocation());
867 FD->setDependentTemplateSpecialization(Reader.getContext(),
868 TemplDecls, TemplArgs);
869 // These are not merged; we don't need to merge redeclarations of dependent
875 // Read in the parameters.
876 unsigned NumParams = Record.readInt();
877 SmallVector<ParmVarDecl *, 16> Params;
878 Params.reserve(NumParams);
879 for (unsigned I = 0; I != NumParams; ++I)
880 Params.push_back(ReadDeclAs<ParmVarDecl>());
881 FD->setParams(Reader.getContext(), Params);
884 void ASTDeclReader::VisitObjCMethodDecl(ObjCMethodDecl *MD) {
886 if (Record.readInt()) {
887 // Load the body on-demand. Most clients won't care, because method
888 // definitions rarely show up in headers.
889 Reader.PendingBodies[MD] = GetCurrentCursorOffset();
890 HasPendingBody = true;
891 MD->setSelfDecl(ReadDeclAs<ImplicitParamDecl>());
892 MD->setCmdDecl(ReadDeclAs<ImplicitParamDecl>());
894 MD->setInstanceMethod(Record.readInt());
895 MD->setVariadic(Record.readInt());
896 MD->setPropertyAccessor(Record.readInt());
897 MD->setDefined(Record.readInt());
898 MD->IsOverriding = Record.readInt();
899 MD->HasSkippedBody = Record.readInt();
901 MD->IsRedeclaration = Record.readInt();
902 MD->HasRedeclaration = Record.readInt();
903 if (MD->HasRedeclaration)
904 Reader.getContext().setObjCMethodRedeclaration(MD,
905 ReadDeclAs<ObjCMethodDecl>());
907 MD->setDeclImplementation((ObjCMethodDecl::ImplementationControl)Record.readInt());
908 MD->setObjCDeclQualifier((Decl::ObjCDeclQualifier)Record.readInt());
909 MD->SetRelatedResultType(Record.readInt());
910 MD->setReturnType(Record.readType());
911 MD->setReturnTypeSourceInfo(GetTypeSourceInfo());
912 MD->DeclEndLoc = ReadSourceLocation();
913 unsigned NumParams = Record.readInt();
914 SmallVector<ParmVarDecl *, 16> Params;
915 Params.reserve(NumParams);
916 for (unsigned I = 0; I != NumParams; ++I)
917 Params.push_back(ReadDeclAs<ParmVarDecl>());
919 MD->SelLocsKind = Record.readInt();
920 unsigned NumStoredSelLocs = Record.readInt();
921 SmallVector<SourceLocation, 16> SelLocs;
922 SelLocs.reserve(NumStoredSelLocs);
923 for (unsigned i = 0; i != NumStoredSelLocs; ++i)
924 SelLocs.push_back(ReadSourceLocation());
926 MD->setParamsAndSelLocs(Reader.getContext(), Params, SelLocs);
929 void ASTDeclReader::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
930 VisitTypedefNameDecl(D);
932 D->Variance = Record.readInt();
933 D->Index = Record.readInt();
934 D->VarianceLoc = ReadSourceLocation();
935 D->ColonLoc = ReadSourceLocation();
938 void ASTDeclReader::VisitObjCContainerDecl(ObjCContainerDecl *CD) {
940 CD->setAtStartLoc(ReadSourceLocation());
941 CD->setAtEndRange(ReadSourceRange());
944 ObjCTypeParamList *ASTDeclReader::ReadObjCTypeParamList() {
945 unsigned numParams = Record.readInt();
949 SmallVector<ObjCTypeParamDecl *, 4> typeParams;
950 typeParams.reserve(numParams);
951 for (unsigned i = 0; i != numParams; ++i) {
952 auto typeParam = ReadDeclAs<ObjCTypeParamDecl>();
956 typeParams.push_back(typeParam);
959 SourceLocation lAngleLoc = ReadSourceLocation();
960 SourceLocation rAngleLoc = ReadSourceLocation();
962 return ObjCTypeParamList::create(Reader.getContext(), lAngleLoc,
963 typeParams, rAngleLoc);
966 void ASTDeclReader::ReadObjCDefinitionData(
967 struct ObjCInterfaceDecl::DefinitionData &Data) {
968 // Read the superclass.
969 Data.SuperClassTInfo = GetTypeSourceInfo();
971 Data.EndLoc = ReadSourceLocation();
972 Data.HasDesignatedInitializers = Record.readInt();
974 // Read the directly referenced protocols and their SourceLocations.
975 unsigned NumProtocols = Record.readInt();
976 SmallVector<ObjCProtocolDecl *, 16> Protocols;
977 Protocols.reserve(NumProtocols);
978 for (unsigned I = 0; I != NumProtocols; ++I)
979 Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>());
980 SmallVector<SourceLocation, 16> ProtoLocs;
981 ProtoLocs.reserve(NumProtocols);
982 for (unsigned I = 0; I != NumProtocols; ++I)
983 ProtoLocs.push_back(ReadSourceLocation());
984 Data.ReferencedProtocols.set(Protocols.data(), NumProtocols, ProtoLocs.data(),
985 Reader.getContext());
987 // Read the transitive closure of protocols referenced by this class.
988 NumProtocols = Record.readInt();
990 Protocols.reserve(NumProtocols);
991 for (unsigned I = 0; I != NumProtocols; ++I)
992 Protocols.push_back(ReadDeclAs<ObjCProtocolDecl>());
993 Data.AllReferencedProtocols.set(Protocols.data(), NumProtocols,
994 Reader.getContext());
997 void ASTDeclReader::MergeDefinitionData(ObjCInterfaceDecl *D,
998 struct ObjCInterfaceDecl::DefinitionData &&NewDD) {
999 // FIXME: odr checking?
1002 void ASTDeclReader::VisitObjCInterfaceDecl(ObjCInterfaceDecl *ID) {
1003 RedeclarableResult Redecl = VisitRedeclarable(ID);
1004 VisitObjCContainerDecl(ID);
1005 TypeIDForTypeDecl = Record.getGlobalTypeID(Record.readInt());
1006 mergeRedeclarable(ID, Redecl);
1008 ID->TypeParamList = ReadObjCTypeParamList();
1009 if (Record.readInt()) {
1010 // Read the definition.
1011 ID->allocateDefinitionData();
1013 ReadObjCDefinitionData(ID->data());
1014 ObjCInterfaceDecl *Canon = ID->getCanonicalDecl();
1015 if (Canon->Data.getPointer()) {
1016 // If we already have a definition, keep the definition invariant and
1018 MergeDefinitionData(Canon, std::move(ID->data()));
1019 ID->Data = Canon->Data;
1021 // Set the definition data of the canonical declaration, so other
1022 // redeclarations will see it.
1023 ID->getCanonicalDecl()->Data = ID->Data;
1025 // We will rebuild this list lazily.
1026 ID->setIvarList(nullptr);
1029 // Note that we have deserialized a definition.
1030 Reader.PendingDefinitions.insert(ID);
1032 // Note that we've loaded this Objective-C class.
1033 Reader.ObjCClassesLoaded.push_back(ID);
1035 ID->Data = ID->getCanonicalDecl()->Data;
1039 void ASTDeclReader::VisitObjCIvarDecl(ObjCIvarDecl *IVD) {
1040 VisitFieldDecl(IVD);
1041 IVD->setAccessControl((ObjCIvarDecl::AccessControl)Record.readInt());
1042 // This field will be built lazily.
1043 IVD->setNextIvar(nullptr);
1044 bool synth = Record.readInt();
1045 IVD->setSynthesize(synth);
1048 void ASTDeclReader::VisitObjCProtocolDecl(ObjCProtocolDecl *PD) {
1049 RedeclarableResult Redecl = VisitRedeclarable(PD);
1050 VisitObjCContainerDecl(PD);
1051 mergeRedeclarable(PD, Redecl);
1053 if (Record.readInt()) {
1054 // Read the definition.
1055 PD->allocateDefinitionData();
1057 // Set the definition data of the canonical declaration, so other
1058 // redeclarations will see it.
1059 PD->getCanonicalDecl()->Data = PD->Data;
1061 unsigned NumProtoRefs = Record.readInt();
1062 SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
1063 ProtoRefs.reserve(NumProtoRefs);
1064 for (unsigned I = 0; I != NumProtoRefs; ++I)
1065 ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>());
1066 SmallVector<SourceLocation, 16> ProtoLocs;
1067 ProtoLocs.reserve(NumProtoRefs);
1068 for (unsigned I = 0; I != NumProtoRefs; ++I)
1069 ProtoLocs.push_back(ReadSourceLocation());
1070 PD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
1071 Reader.getContext());
1073 // Note that we have deserialized a definition.
1074 Reader.PendingDefinitions.insert(PD);
1076 PD->Data = PD->getCanonicalDecl()->Data;
1080 void ASTDeclReader::VisitObjCAtDefsFieldDecl(ObjCAtDefsFieldDecl *FD) {
1084 void ASTDeclReader::VisitObjCCategoryDecl(ObjCCategoryDecl *CD) {
1085 VisitObjCContainerDecl(CD);
1086 CD->setCategoryNameLoc(ReadSourceLocation());
1087 CD->setIvarLBraceLoc(ReadSourceLocation());
1088 CD->setIvarRBraceLoc(ReadSourceLocation());
1090 // Note that this category has been deserialized. We do this before
1091 // deserializing the interface declaration, so that it will consider this
1093 Reader.CategoriesDeserialized.insert(CD);
1095 CD->ClassInterface = ReadDeclAs<ObjCInterfaceDecl>();
1096 CD->TypeParamList = ReadObjCTypeParamList();
1097 unsigned NumProtoRefs = Record.readInt();
1098 SmallVector<ObjCProtocolDecl *, 16> ProtoRefs;
1099 ProtoRefs.reserve(NumProtoRefs);
1100 for (unsigned I = 0; I != NumProtoRefs; ++I)
1101 ProtoRefs.push_back(ReadDeclAs<ObjCProtocolDecl>());
1102 SmallVector<SourceLocation, 16> ProtoLocs;
1103 ProtoLocs.reserve(NumProtoRefs);
1104 for (unsigned I = 0; I != NumProtoRefs; ++I)
1105 ProtoLocs.push_back(ReadSourceLocation());
1106 CD->setProtocolList(ProtoRefs.data(), NumProtoRefs, ProtoLocs.data(),
1107 Reader.getContext());
1110 void ASTDeclReader::VisitObjCCompatibleAliasDecl(ObjCCompatibleAliasDecl *CAD) {
1111 VisitNamedDecl(CAD);
1112 CAD->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>());
1115 void ASTDeclReader::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
1117 D->setAtLoc(ReadSourceLocation());
1118 D->setLParenLoc(ReadSourceLocation());
1119 QualType T = Record.readType();
1120 TypeSourceInfo *TSI = GetTypeSourceInfo();
1122 D->setPropertyAttributes(
1123 (ObjCPropertyDecl::PropertyAttributeKind)Record.readInt());
1124 D->setPropertyAttributesAsWritten(
1125 (ObjCPropertyDecl::PropertyAttributeKind)Record.readInt());
1126 D->setPropertyImplementation(
1127 (ObjCPropertyDecl::PropertyControl)Record.readInt());
1128 DeclarationName GetterName = Record.readDeclarationName();
1129 SourceLocation GetterLoc = ReadSourceLocation();
1130 D->setGetterName(GetterName.getObjCSelector(), GetterLoc);
1131 DeclarationName SetterName = Record.readDeclarationName();
1132 SourceLocation SetterLoc = ReadSourceLocation();
1133 D->setSetterName(SetterName.getObjCSelector(), SetterLoc);
1134 D->setGetterMethodDecl(ReadDeclAs<ObjCMethodDecl>());
1135 D->setSetterMethodDecl(ReadDeclAs<ObjCMethodDecl>());
1136 D->setPropertyIvarDecl(ReadDeclAs<ObjCIvarDecl>());
1139 void ASTDeclReader::VisitObjCImplDecl(ObjCImplDecl *D) {
1140 VisitObjCContainerDecl(D);
1141 D->setClassInterface(ReadDeclAs<ObjCInterfaceDecl>());
1144 void ASTDeclReader::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
1145 VisitObjCImplDecl(D);
1146 D->CategoryNameLoc = ReadSourceLocation();
1149 void ASTDeclReader::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
1150 VisitObjCImplDecl(D);
1151 D->setSuperClass(ReadDeclAs<ObjCInterfaceDecl>());
1152 D->SuperLoc = ReadSourceLocation();
1153 D->setIvarLBraceLoc(ReadSourceLocation());
1154 D->setIvarRBraceLoc(ReadSourceLocation());
1155 D->setHasNonZeroConstructors(Record.readInt());
1156 D->setHasDestructors(Record.readInt());
1157 D->NumIvarInitializers = Record.readInt();
1158 if (D->NumIvarInitializers)
1159 D->IvarInitializers = ReadGlobalOffset();
1162 void ASTDeclReader::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
1164 D->setAtLoc(ReadSourceLocation());
1165 D->setPropertyDecl(ReadDeclAs<ObjCPropertyDecl>());
1166 D->PropertyIvarDecl = ReadDeclAs<ObjCIvarDecl>();
1167 D->IvarLoc = ReadSourceLocation();
1168 D->setGetterCXXConstructor(Record.readExpr());
1169 D->setSetterCXXAssignment(Record.readExpr());
1172 void ASTDeclReader::VisitFieldDecl(FieldDecl *FD) {
1173 VisitDeclaratorDecl(FD);
1174 FD->Mutable = Record.readInt();
1175 if (int BitWidthOrInitializer = Record.readInt()) {
1176 FD->InitStorage.setInt(
1177 static_cast<FieldDecl::InitStorageKind>(BitWidthOrInitializer - 1));
1178 if (FD->InitStorage.getInt() == FieldDecl::ISK_CapturedVLAType) {
1179 // Read captured variable length array.
1180 FD->InitStorage.setPointer(Record.readType().getAsOpaquePtr());
1182 FD->InitStorage.setPointer(Record.readExpr());
1185 if (!FD->getDeclName()) {
1186 if (FieldDecl *Tmpl = ReadDeclAs<FieldDecl>())
1187 Reader.getContext().setInstantiatedFromUnnamedFieldDecl(FD, Tmpl);
1192 void ASTDeclReader::VisitMSPropertyDecl(MSPropertyDecl *PD) {
1193 VisitDeclaratorDecl(PD);
1194 PD->GetterId = Record.getIdentifierInfo();
1195 PD->SetterId = Record.getIdentifierInfo();
1198 void ASTDeclReader::VisitIndirectFieldDecl(IndirectFieldDecl *FD) {
1201 FD->ChainingSize = Record.readInt();
1202 assert(FD->ChainingSize >= 2 && "Anonymous chaining must be >= 2");
1203 FD->Chaining = new (Reader.getContext())NamedDecl*[FD->ChainingSize];
1205 for (unsigned I = 0; I != FD->ChainingSize; ++I)
1206 FD->Chaining[I] = ReadDeclAs<NamedDecl>();
1211 ASTDeclReader::RedeclarableResult ASTDeclReader::VisitVarDeclImpl(VarDecl *VD) {
1212 RedeclarableResult Redecl = VisitRedeclarable(VD);
1213 VisitDeclaratorDecl(VD);
1215 VD->VarDeclBits.SClass = (StorageClass)Record.readInt();
1216 VD->VarDeclBits.TSCSpec = Record.readInt();
1217 VD->VarDeclBits.InitStyle = Record.readInt();
1218 if (!isa<ParmVarDecl>(VD)) {
1219 VD->NonParmVarDeclBits.IsThisDeclarationADemotedDefinition =
1221 VD->NonParmVarDeclBits.ExceptionVar = Record.readInt();
1222 VD->NonParmVarDeclBits.NRVOVariable = Record.readInt();
1223 VD->NonParmVarDeclBits.CXXForRangeDecl = Record.readInt();
1224 VD->NonParmVarDeclBits.ARCPseudoStrong = Record.readInt();
1225 VD->NonParmVarDeclBits.IsInline = Record.readInt();
1226 VD->NonParmVarDeclBits.IsInlineSpecified = Record.readInt();
1227 VD->NonParmVarDeclBits.IsConstexpr = Record.readInt();
1228 VD->NonParmVarDeclBits.IsInitCapture = Record.readInt();
1229 VD->NonParmVarDeclBits.PreviousDeclInSameBlockScope = Record.readInt();
1230 VD->NonParmVarDeclBits.ImplicitParamKind = Record.readInt();
1232 Linkage VarLinkage = Linkage(Record.readInt());
1233 VD->setCachedLinkage(VarLinkage);
1235 // Reconstruct the one piece of the IdentifierNamespace that we need.
1236 if (VD->getStorageClass() == SC_Extern && VarLinkage != NoLinkage &&
1237 VD->getLexicalDeclContext()->isFunctionOrMethod())
1238 VD->setLocalExternDecl();
1240 if (uint64_t Val = Record.readInt()) {
1241 VD->setInit(Record.readExpr());
1242 if (Val > 1) { // IsInitKnownICE = 1, IsInitNotICE = 2, IsInitICE = 3
1243 EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
1244 Eval->CheckedICE = true;
1245 Eval->IsICE = Val == 3;
1250 VarNotTemplate = 0, VarTemplate, StaticDataMemberSpecialization
1252 switch ((VarKind)Record.readInt()) {
1253 case VarNotTemplate:
1254 // Only true variables (not parameters or implicit parameters) can be
1255 // merged; the other kinds are not really redeclarable at all.
1256 if (!isa<ParmVarDecl>(VD) && !isa<ImplicitParamDecl>(VD) &&
1257 !isa<VarTemplateSpecializationDecl>(VD))
1258 mergeRedeclarable(VD, Redecl);
1261 // Merged when we merge the template.
1262 VD->setDescribedVarTemplate(ReadDeclAs<VarTemplateDecl>());
1264 case StaticDataMemberSpecialization: { // HasMemberSpecializationInfo.
1265 VarDecl *Tmpl = ReadDeclAs<VarDecl>();
1266 TemplateSpecializationKind TSK =
1267 (TemplateSpecializationKind)Record.readInt();
1268 SourceLocation POI = ReadSourceLocation();
1269 Reader.getContext().setInstantiatedFromStaticDataMember(VD, Tmpl, TSK,POI);
1270 mergeRedeclarable(VD, Redecl);
1278 void ASTDeclReader::VisitImplicitParamDecl(ImplicitParamDecl *PD) {
1282 void ASTDeclReader::VisitParmVarDecl(ParmVarDecl *PD) {
1284 unsigned isObjCMethodParam = Record.readInt();
1285 unsigned scopeDepth = Record.readInt();
1286 unsigned scopeIndex = Record.readInt();
1287 unsigned declQualifier = Record.readInt();
1288 if (isObjCMethodParam) {
1289 assert(scopeDepth == 0);
1290 PD->setObjCMethodScopeInfo(scopeIndex);
1291 PD->ParmVarDeclBits.ScopeDepthOrObjCQuals = declQualifier;
1293 PD->setScopeInfo(scopeDepth, scopeIndex);
1295 PD->ParmVarDeclBits.IsKNRPromoted = Record.readInt();
1296 PD->ParmVarDeclBits.HasInheritedDefaultArg = Record.readInt();
1297 if (Record.readInt()) // hasUninstantiatedDefaultArg.
1298 PD->setUninstantiatedDefaultArg(Record.readExpr());
1300 // FIXME: If this is a redeclaration of a function from another module, handle
1301 // inheritance of default arguments.
1304 void ASTDeclReader::VisitDecompositionDecl(DecompositionDecl *DD) {
1306 BindingDecl **BDs = DD->getTrailingObjects<BindingDecl*>();
1307 for (unsigned I = 0; I != DD->NumBindings; ++I)
1308 BDs[I] = ReadDeclAs<BindingDecl>();
1311 void ASTDeclReader::VisitBindingDecl(BindingDecl *BD) {
1313 BD->Binding = Record.readExpr();
1316 void ASTDeclReader::VisitFileScopeAsmDecl(FileScopeAsmDecl *AD) {
1318 AD->setAsmString(cast<StringLiteral>(Record.readExpr()));
1319 AD->setRParenLoc(ReadSourceLocation());
1322 void ASTDeclReader::VisitBlockDecl(BlockDecl *BD) {
1324 BD->setBody(cast_or_null<CompoundStmt>(Record.readStmt()));
1325 BD->setSignatureAsWritten(GetTypeSourceInfo());
1326 unsigned NumParams = Record.readInt();
1327 SmallVector<ParmVarDecl *, 16> Params;
1328 Params.reserve(NumParams);
1329 for (unsigned I = 0; I != NumParams; ++I)
1330 Params.push_back(ReadDeclAs<ParmVarDecl>());
1331 BD->setParams(Params);
1333 BD->setIsVariadic(Record.readInt());
1334 BD->setBlockMissingReturnType(Record.readInt());
1335 BD->setIsConversionFromLambda(Record.readInt());
1337 bool capturesCXXThis = Record.readInt();
1338 unsigned numCaptures = Record.readInt();
1339 SmallVector<BlockDecl::Capture, 16> captures;
1340 captures.reserve(numCaptures);
1341 for (unsigned i = 0; i != numCaptures; ++i) {
1342 VarDecl *decl = ReadDeclAs<VarDecl>();
1343 unsigned flags = Record.readInt();
1344 bool byRef = (flags & 1);
1345 bool nested = (flags & 2);
1346 Expr *copyExpr = ((flags & 4) ? Record.readExpr() : nullptr);
1348 captures.push_back(BlockDecl::Capture(decl, byRef, nested, copyExpr));
1350 BD->setCaptures(Reader.getContext(), captures, capturesCXXThis);
1353 void ASTDeclReader::VisitCapturedDecl(CapturedDecl *CD) {
1355 unsigned ContextParamPos = Record.readInt();
1356 CD->setNothrow(Record.readInt() != 0);
1357 // Body is set by VisitCapturedStmt.
1358 for (unsigned I = 0; I < CD->NumParams; ++I) {
1359 if (I != ContextParamPos)
1360 CD->setParam(I, ReadDeclAs<ImplicitParamDecl>());
1362 CD->setContextParam(I, ReadDeclAs<ImplicitParamDecl>());
1366 void ASTDeclReader::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
1368 D->setLanguage((LinkageSpecDecl::LanguageIDs)Record.readInt());
1369 D->setExternLoc(ReadSourceLocation());
1370 D->setRBraceLoc(ReadSourceLocation());
1373 void ASTDeclReader::VisitExportDecl(ExportDecl *D) {
1375 D->RBraceLoc = ReadSourceLocation();
1378 void ASTDeclReader::VisitLabelDecl(LabelDecl *D) {
1380 D->setLocStart(ReadSourceLocation());
1383 void ASTDeclReader::VisitNamespaceDecl(NamespaceDecl *D) {
1384 RedeclarableResult Redecl = VisitRedeclarable(D);
1386 D->setInline(Record.readInt());
1387 D->LocStart = ReadSourceLocation();
1388 D->RBraceLoc = ReadSourceLocation();
1390 // Defer loading the anonymous namespace until we've finished merging
1391 // this namespace; loading it might load a later declaration of the
1392 // same namespace, and we have an invariant that older declarations
1393 // get merged before newer ones try to merge.
1394 GlobalDeclID AnonNamespace = 0;
1395 if (Redecl.getFirstID() == ThisDeclID) {
1396 AnonNamespace = ReadDeclID();
1398 // Link this namespace back to the first declaration, which has already
1399 // been deserialized.
1400 D->AnonOrFirstNamespaceAndInline.setPointer(D->getFirstDecl());
1403 mergeRedeclarable(D, Redecl);
1405 if (AnonNamespace) {
1406 // Each module has its own anonymous namespace, which is disjoint from
1407 // any other module's anonymous namespaces, so don't attach the anonymous
1408 // namespace at all.
1409 NamespaceDecl *Anon = cast<NamespaceDecl>(Reader.GetDecl(AnonNamespace));
1410 if (!Record.isModule())
1411 D->setAnonymousNamespace(Anon);
1415 void ASTDeclReader::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
1416 RedeclarableResult Redecl = VisitRedeclarable(D);
1418 D->NamespaceLoc = ReadSourceLocation();
1419 D->IdentLoc = ReadSourceLocation();
1420 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1421 D->Namespace = ReadDeclAs<NamedDecl>();
1422 mergeRedeclarable(D, Redecl);
1425 void ASTDeclReader::VisitUsingDecl(UsingDecl *D) {
1427 D->setUsingLoc(ReadSourceLocation());
1428 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1429 ReadDeclarationNameLoc(D->DNLoc, D->getDeclName());
1430 D->FirstUsingShadow.setPointer(ReadDeclAs<UsingShadowDecl>());
1431 D->setTypename(Record.readInt());
1432 if (NamedDecl *Pattern = ReadDeclAs<NamedDecl>())
1433 Reader.getContext().setInstantiatedFromUsingDecl(D, Pattern);
1437 void ASTDeclReader::VisitUsingPackDecl(UsingPackDecl *D) {
1439 D->InstantiatedFrom = ReadDeclAs<NamedDecl>();
1440 NamedDecl **Expansions = D->getTrailingObjects<NamedDecl*>();
1441 for (unsigned I = 0; I != D->NumExpansions; ++I)
1442 Expansions[I] = ReadDeclAs<NamedDecl>();
1446 void ASTDeclReader::VisitUsingShadowDecl(UsingShadowDecl *D) {
1447 RedeclarableResult Redecl = VisitRedeclarable(D);
1449 D->setTargetDecl(ReadDeclAs<NamedDecl>());
1450 D->UsingOrNextShadow = ReadDeclAs<NamedDecl>();
1451 UsingShadowDecl *Pattern = ReadDeclAs<UsingShadowDecl>();
1453 Reader.getContext().setInstantiatedFromUsingShadowDecl(D, Pattern);
1454 mergeRedeclarable(D, Redecl);
1457 void ASTDeclReader::VisitConstructorUsingShadowDecl(
1458 ConstructorUsingShadowDecl *D) {
1459 VisitUsingShadowDecl(D);
1460 D->NominatedBaseClassShadowDecl = ReadDeclAs<ConstructorUsingShadowDecl>();
1461 D->ConstructedBaseClassShadowDecl = ReadDeclAs<ConstructorUsingShadowDecl>();
1462 D->IsVirtual = Record.readInt();
1465 void ASTDeclReader::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
1467 D->UsingLoc = ReadSourceLocation();
1468 D->NamespaceLoc = ReadSourceLocation();
1469 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1470 D->NominatedNamespace = ReadDeclAs<NamedDecl>();
1471 D->CommonAncestor = ReadDeclAs<DeclContext>();
1474 void ASTDeclReader::VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D) {
1476 D->setUsingLoc(ReadSourceLocation());
1477 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1478 ReadDeclarationNameLoc(D->DNLoc, D->getDeclName());
1479 D->EllipsisLoc = ReadSourceLocation();
1483 void ASTDeclReader::VisitUnresolvedUsingTypenameDecl(
1484 UnresolvedUsingTypenameDecl *D) {
1486 D->TypenameLocation = ReadSourceLocation();
1487 D->QualifierLoc = Record.readNestedNameSpecifierLoc();
1488 D->EllipsisLoc = ReadSourceLocation();
1492 void ASTDeclReader::ReadCXXDefinitionData(
1493 struct CXXRecordDecl::DefinitionData &Data, const CXXRecordDecl *D) {
1494 // Note: the caller has deserialized the IsLambda bit already.
1495 Data.UserDeclaredConstructor = Record.readInt();
1496 Data.UserDeclaredSpecialMembers = Record.readInt();
1497 Data.Aggregate = Record.readInt();
1498 Data.PlainOldData = Record.readInt();
1499 Data.Empty = Record.readInt();
1500 Data.Polymorphic = Record.readInt();
1501 Data.Abstract = Record.readInt();
1502 Data.IsStandardLayout = Record.readInt();
1503 Data.HasNoNonEmptyBases = Record.readInt();
1504 Data.HasPrivateFields = Record.readInt();
1505 Data.HasProtectedFields = Record.readInt();
1506 Data.HasPublicFields = Record.readInt();
1507 Data.HasMutableFields = Record.readInt();
1508 Data.HasVariantMembers = Record.readInt();
1509 Data.HasOnlyCMembers = Record.readInt();
1510 Data.HasInClassInitializer = Record.readInt();
1511 Data.HasUninitializedReferenceMember = Record.readInt();
1512 Data.HasUninitializedFields = Record.readInt();
1513 Data.HasInheritedConstructor = Record.readInt();
1514 Data.HasInheritedAssignment = Record.readInt();
1515 Data.NeedOverloadResolutionForMoveConstructor = Record.readInt();
1516 Data.NeedOverloadResolutionForMoveAssignment = Record.readInt();
1517 Data.NeedOverloadResolutionForDestructor = Record.readInt();
1518 Data.DefaultedMoveConstructorIsDeleted = Record.readInt();
1519 Data.DefaultedMoveAssignmentIsDeleted = Record.readInt();
1520 Data.DefaultedDestructorIsDeleted = Record.readInt();
1521 Data.HasTrivialSpecialMembers = Record.readInt();
1522 Data.DeclaredNonTrivialSpecialMembers = Record.readInt();
1523 Data.HasIrrelevantDestructor = Record.readInt();
1524 Data.HasConstexprNonCopyMoveConstructor = Record.readInt();
1525 Data.HasDefaultedDefaultConstructor = Record.readInt();
1526 Data.DefaultedDefaultConstructorIsConstexpr = Record.readInt();
1527 Data.HasConstexprDefaultConstructor = Record.readInt();
1528 Data.HasNonLiteralTypeFieldsOrBases = Record.readInt();
1529 Data.ComputedVisibleConversions = Record.readInt();
1530 Data.UserProvidedDefaultConstructor = Record.readInt();
1531 Data.DeclaredSpecialMembers = Record.readInt();
1532 Data.ImplicitCopyConstructorCanHaveConstParamForVBase = Record.readInt();
1533 Data.ImplicitCopyConstructorCanHaveConstParamForNonVBase = Record.readInt();
1534 Data.ImplicitCopyAssignmentHasConstParam = Record.readInt();
1535 Data.HasDeclaredCopyConstructorWithConstParam = Record.readInt();
1536 Data.HasDeclaredCopyAssignmentWithConstParam = Record.readInt();
1537 Data.ODRHash = Record.readInt();
1538 Data.HasODRHash = true;
1540 if (Record.readInt()) {
1541 Reader.BodySource[D] = Loc.F->Kind == ModuleKind::MK_MainFile
1542 ? ExternalASTSource::EK_Never
1543 : ExternalASTSource::EK_Always;
1546 Data.NumBases = Record.readInt();
1548 Data.Bases = ReadGlobalOffset();
1549 Data.NumVBases = Record.readInt();
1551 Data.VBases = ReadGlobalOffset();
1553 Record.readUnresolvedSet(Data.Conversions);
1554 Record.readUnresolvedSet(Data.VisibleConversions);
1555 assert(Data.Definition && "Data.Definition should be already set!");
1556 Data.FirstFriend = ReadDeclID();
1558 if (Data.IsLambda) {
1559 typedef LambdaCapture Capture;
1560 CXXRecordDecl::LambdaDefinitionData &Lambda
1561 = static_cast<CXXRecordDecl::LambdaDefinitionData &>(Data);
1562 Lambda.Dependent = Record.readInt();
1563 Lambda.IsGenericLambda = Record.readInt();
1564 Lambda.CaptureDefault = Record.readInt();
1565 Lambda.NumCaptures = Record.readInt();
1566 Lambda.NumExplicitCaptures = Record.readInt();
1567 Lambda.ManglingNumber = Record.readInt();
1568 Lambda.ContextDecl = ReadDeclID();
1570 = (Capture*)Reader.Context.Allocate(sizeof(Capture)*Lambda.NumCaptures);
1571 Capture *ToCapture = Lambda.Captures;
1572 Lambda.MethodTyInfo = GetTypeSourceInfo();
1573 for (unsigned I = 0, N = Lambda.NumCaptures; I != N; ++I) {
1574 SourceLocation Loc = ReadSourceLocation();
1575 bool IsImplicit = Record.readInt();
1576 LambdaCaptureKind Kind = static_cast<LambdaCaptureKind>(Record.readInt());
1581 *ToCapture++ = Capture(Loc, IsImplicit, Kind, nullptr,SourceLocation());
1585 VarDecl *Var = ReadDeclAs<VarDecl>();
1586 SourceLocation EllipsisLoc = ReadSourceLocation();
1587 *ToCapture++ = Capture(Loc, IsImplicit, Kind, Var, EllipsisLoc);
1594 void ASTDeclReader::MergeDefinitionData(
1595 CXXRecordDecl *D, struct CXXRecordDecl::DefinitionData &&MergeDD) {
1596 assert(D->DefinitionData &&
1597 "merging class definition into non-definition");
1598 auto &DD = *D->DefinitionData;
1600 if (DD.Definition != MergeDD.Definition) {
1601 // Track that we merged the definitions.
1602 Reader.MergedDeclContexts.insert(std::make_pair(MergeDD.Definition,
1604 Reader.PendingDefinitions.erase(MergeDD.Definition);
1605 MergeDD.Definition->IsCompleteDefinition = false;
1606 Reader.mergeDefinitionVisibility(DD.Definition, MergeDD.Definition);
1607 assert(Reader.Lookups.find(MergeDD.Definition) == Reader.Lookups.end() &&
1608 "already loaded pending lookups for merged definition");
1611 auto PFDI = Reader.PendingFakeDefinitionData.find(&DD);
1612 if (PFDI != Reader.PendingFakeDefinitionData.end() &&
1613 PFDI->second == ASTReader::PendingFakeDefinitionKind::Fake) {
1614 // We faked up this definition data because we found a class for which we'd
1615 // not yet loaded the definition. Replace it with the real thing now.
1616 assert(!DD.IsLambda && !MergeDD.IsLambda && "faked up lambda definition?");
1617 PFDI->second = ASTReader::PendingFakeDefinitionKind::FakeLoaded;
1619 // Don't change which declaration is the definition; that is required
1620 // to be invariant once we select it.
1621 auto *Def = DD.Definition;
1622 DD = std::move(MergeDD);
1623 DD.Definition = Def;
1627 // FIXME: Move this out into a .def file?
1628 bool DetectedOdrViolation = false;
1629 #define OR_FIELD(Field) DD.Field |= MergeDD.Field;
1630 #define MATCH_FIELD(Field) \
1631 DetectedOdrViolation |= DD.Field != MergeDD.Field; \
1633 MATCH_FIELD(UserDeclaredConstructor)
1634 MATCH_FIELD(UserDeclaredSpecialMembers)
1635 MATCH_FIELD(Aggregate)
1636 MATCH_FIELD(PlainOldData)
1638 MATCH_FIELD(Polymorphic)
1639 MATCH_FIELD(Abstract)
1640 MATCH_FIELD(IsStandardLayout)
1641 MATCH_FIELD(HasNoNonEmptyBases)
1642 MATCH_FIELD(HasPrivateFields)
1643 MATCH_FIELD(HasProtectedFields)
1644 MATCH_FIELD(HasPublicFields)
1645 MATCH_FIELD(HasMutableFields)
1646 MATCH_FIELD(HasVariantMembers)
1647 MATCH_FIELD(HasOnlyCMembers)
1648 MATCH_FIELD(HasInClassInitializer)
1649 MATCH_FIELD(HasUninitializedReferenceMember)
1650 MATCH_FIELD(HasUninitializedFields)
1651 MATCH_FIELD(HasInheritedConstructor)
1652 MATCH_FIELD(HasInheritedAssignment)
1653 MATCH_FIELD(NeedOverloadResolutionForMoveConstructor)
1654 MATCH_FIELD(NeedOverloadResolutionForMoveAssignment)
1655 MATCH_FIELD(NeedOverloadResolutionForDestructor)
1656 MATCH_FIELD(DefaultedMoveConstructorIsDeleted)
1657 MATCH_FIELD(DefaultedMoveAssignmentIsDeleted)
1658 MATCH_FIELD(DefaultedDestructorIsDeleted)
1659 OR_FIELD(HasTrivialSpecialMembers)
1660 OR_FIELD(DeclaredNonTrivialSpecialMembers)
1661 MATCH_FIELD(HasIrrelevantDestructor)
1662 OR_FIELD(HasConstexprNonCopyMoveConstructor)
1663 OR_FIELD(HasDefaultedDefaultConstructor)
1664 MATCH_FIELD(DefaultedDefaultConstructorIsConstexpr)
1665 OR_FIELD(HasConstexprDefaultConstructor)
1666 MATCH_FIELD(HasNonLiteralTypeFieldsOrBases)
1667 // ComputedVisibleConversions is handled below.
1668 MATCH_FIELD(UserProvidedDefaultConstructor)
1669 OR_FIELD(DeclaredSpecialMembers)
1670 MATCH_FIELD(ImplicitCopyConstructorCanHaveConstParamForVBase)
1671 MATCH_FIELD(ImplicitCopyConstructorCanHaveConstParamForNonVBase)
1672 MATCH_FIELD(ImplicitCopyAssignmentHasConstParam)
1673 OR_FIELD(HasDeclaredCopyConstructorWithConstParam)
1674 OR_FIELD(HasDeclaredCopyAssignmentWithConstParam)
1675 MATCH_FIELD(IsLambda)
1679 if (DD.NumBases != MergeDD.NumBases || DD.NumVBases != MergeDD.NumVBases)
1680 DetectedOdrViolation = true;
1681 // FIXME: Issue a diagnostic if the base classes don't match when we come
1682 // to lazily load them.
1684 // FIXME: Issue a diagnostic if the list of conversion functions doesn't
1685 // match when we come to lazily load them.
1686 if (MergeDD.ComputedVisibleConversions && !DD.ComputedVisibleConversions) {
1687 DD.VisibleConversions = std::move(MergeDD.VisibleConversions);
1688 DD.ComputedVisibleConversions = true;
1691 // FIXME: Issue a diagnostic if FirstFriend doesn't match when we come to
1695 // FIXME: ODR-checking for merging lambdas (this happens, for instance,
1696 // when they occur within the body of a function template specialization).
1699 if (D->getODRHash() != MergeDD.ODRHash) {
1700 DetectedOdrViolation = true;
1703 if (DetectedOdrViolation)
1704 Reader.PendingOdrMergeFailures[DD.Definition].push_back(MergeDD.Definition);
1707 void ASTDeclReader::ReadCXXRecordDefinition(CXXRecordDecl *D, bool Update) {
1708 struct CXXRecordDecl::DefinitionData *DD;
1709 ASTContext &C = Reader.getContext();
1711 // Determine whether this is a lambda closure type, so that we can
1712 // allocate the appropriate DefinitionData structure.
1713 bool IsLambda = Record.readInt();
1715 DD = new (C) CXXRecordDecl::LambdaDefinitionData(D, nullptr, false, false,
1718 DD = new (C) struct CXXRecordDecl::DefinitionData(D);
1720 ReadCXXDefinitionData(*DD, D);
1722 // We might already have a definition for this record. This can happen either
1723 // because we're reading an update record, or because we've already done some
1724 // merging. Either way, just merge into it.
1725 CXXRecordDecl *Canon = D->getCanonicalDecl();
1726 if (Canon->DefinitionData) {
1727 MergeDefinitionData(Canon, std::move(*DD));
1728 D->DefinitionData = Canon->DefinitionData;
1732 // Mark this declaration as being a definition.
1733 D->IsCompleteDefinition = true;
1734 D->DefinitionData = DD;
1736 // If this is not the first declaration or is an update record, we can have
1737 // other redeclarations already. Make a note that we need to propagate the
1738 // DefinitionData pointer onto them.
1739 if (Update || Canon != D) {
1740 Canon->DefinitionData = D->DefinitionData;
1741 Reader.PendingDefinitions.insert(D);
1745 ASTDeclReader::RedeclarableResult
1746 ASTDeclReader::VisitCXXRecordDeclImpl(CXXRecordDecl *D) {
1747 RedeclarableResult Redecl = VisitRecordDeclImpl(D);
1749 ASTContext &C = Reader.getContext();
1752 CXXRecNotTemplate = 0, CXXRecTemplate, CXXRecMemberSpecialization
1754 switch ((CXXRecKind)Record.readInt()) {
1755 case CXXRecNotTemplate:
1756 // Merged when we merge the folding set entry in the primary template.
1757 if (!isa<ClassTemplateSpecializationDecl>(D))
1758 mergeRedeclarable(D, Redecl);
1760 case CXXRecTemplate: {
1761 // Merged when we merge the template.
1762 ClassTemplateDecl *Template = ReadDeclAs<ClassTemplateDecl>();
1763 D->TemplateOrInstantiation = Template;
1764 if (!Template->getTemplatedDecl()) {
1765 // We've not actually loaded the ClassTemplateDecl yet, because we're
1766 // currently being loaded as its pattern. Rely on it to set up our
1767 // TypeForDecl (see VisitClassTemplateDecl).
1769 // Beware: we do not yet know our canonical declaration, and may still
1770 // get merged once the surrounding class template has got off the ground.
1771 TypeIDForTypeDecl = 0;
1775 case CXXRecMemberSpecialization: {
1776 CXXRecordDecl *RD = ReadDeclAs<CXXRecordDecl>();
1777 TemplateSpecializationKind TSK =
1778 (TemplateSpecializationKind)Record.readInt();
1779 SourceLocation POI = ReadSourceLocation();
1780 MemberSpecializationInfo *MSI = new (C) MemberSpecializationInfo(RD, TSK);
1781 MSI->setPointOfInstantiation(POI);
1782 D->TemplateOrInstantiation = MSI;
1783 mergeRedeclarable(D, Redecl);
1788 bool WasDefinition = Record.readInt();
1790 ReadCXXRecordDefinition(D, /*Update*/false);
1792 // Propagate DefinitionData pointer from the canonical declaration.
1793 D->DefinitionData = D->getCanonicalDecl()->DefinitionData;
1795 // Lazily load the key function to avoid deserializing every method so we can
1797 if (WasDefinition) {
1798 DeclID KeyFn = ReadDeclID();
1799 if (KeyFn && D->IsCompleteDefinition)
1800 // FIXME: This is wrong for the ARM ABI, where some other module may have
1801 // made this function no longer be a key function. We need an update
1802 // record or similar for that case.
1803 C.KeyFunctions[D] = KeyFn;
1809 void ASTDeclReader::VisitCXXDeductionGuideDecl(CXXDeductionGuideDecl *D) {
1810 VisitFunctionDecl(D);
1813 void ASTDeclReader::VisitCXXMethodDecl(CXXMethodDecl *D) {
1814 VisitFunctionDecl(D);
1816 unsigned NumOverridenMethods = Record.readInt();
1817 if (D->isCanonicalDecl()) {
1818 while (NumOverridenMethods--) {
1819 // Avoid invariant checking of CXXMethodDecl::addOverriddenMethod,
1820 // MD may be initializing.
1821 if (CXXMethodDecl *MD = ReadDeclAs<CXXMethodDecl>())
1822 Reader.getContext().addOverriddenMethod(D, MD->getCanonicalDecl());
1825 // We don't care about which declarations this used to override; we get
1826 // the relevant information from the canonical declaration.
1827 Record.skipInts(NumOverridenMethods);
1831 void ASTDeclReader::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
1832 // We need the inherited constructor information to merge the declaration,
1833 // so we have to read it before we call VisitCXXMethodDecl.
1834 if (D->isInheritingConstructor()) {
1835 auto *Shadow = ReadDeclAs<ConstructorUsingShadowDecl>();
1836 auto *Ctor = ReadDeclAs<CXXConstructorDecl>();
1837 *D->getTrailingObjects<InheritedConstructor>() =
1838 InheritedConstructor(Shadow, Ctor);
1841 VisitCXXMethodDecl(D);
1844 void ASTDeclReader::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
1845 VisitCXXMethodDecl(D);
1847 if (auto *OperatorDelete = ReadDeclAs<FunctionDecl>()) {
1848 auto *Canon = cast<CXXDestructorDecl>(D->getCanonicalDecl());
1849 // FIXME: Check consistency if we have an old and new operator delete.
1850 if (!Canon->OperatorDelete)
1851 Canon->OperatorDelete = OperatorDelete;
1855 void ASTDeclReader::VisitCXXConversionDecl(CXXConversionDecl *D) {
1856 VisitCXXMethodDecl(D);
1859 void ASTDeclReader::VisitImportDecl(ImportDecl *D) {
1861 D->ImportedAndComplete.setPointer(readModule());
1862 D->ImportedAndComplete.setInt(Record.readInt());
1863 SourceLocation *StoredLocs = D->getTrailingObjects<SourceLocation>();
1864 for (unsigned I = 0, N = Record.back(); I != N; ++I)
1865 StoredLocs[I] = ReadSourceLocation();
1866 Record.skipInts(1); // The number of stored source locations.
1869 void ASTDeclReader::VisitAccessSpecDecl(AccessSpecDecl *D) {
1871 D->setColonLoc(ReadSourceLocation());
1874 void ASTDeclReader::VisitFriendDecl(FriendDecl *D) {
1876 if (Record.readInt()) // hasFriendDecl
1877 D->Friend = ReadDeclAs<NamedDecl>();
1879 D->Friend = GetTypeSourceInfo();
1880 for (unsigned i = 0; i != D->NumTPLists; ++i)
1881 D->getTrailingObjects<TemplateParameterList *>()[i] =
1882 Record.readTemplateParameterList();
1883 D->NextFriend = ReadDeclID();
1884 D->UnsupportedFriend = (Record.readInt() != 0);
1885 D->FriendLoc = ReadSourceLocation();
1888 void ASTDeclReader::VisitFriendTemplateDecl(FriendTemplateDecl *D) {
1890 unsigned NumParams = Record.readInt();
1891 D->NumParams = NumParams;
1892 D->Params = new TemplateParameterList*[NumParams];
1893 for (unsigned i = 0; i != NumParams; ++i)
1894 D->Params[i] = Record.readTemplateParameterList();
1895 if (Record.readInt()) // HasFriendDecl
1896 D->Friend = ReadDeclAs<NamedDecl>();
1898 D->Friend = GetTypeSourceInfo();
1899 D->FriendLoc = ReadSourceLocation();
1902 DeclID ASTDeclReader::VisitTemplateDecl(TemplateDecl *D) {
1905 DeclID PatternID = ReadDeclID();
1906 NamedDecl *TemplatedDecl = cast_or_null<NamedDecl>(Reader.GetDecl(PatternID));
1907 TemplateParameterList *TemplateParams = Record.readTemplateParameterList();
1908 // FIXME handle associated constraints
1909 D->init(TemplatedDecl, TemplateParams);
1914 ASTDeclReader::RedeclarableResult
1915 ASTDeclReader::VisitRedeclarableTemplateDecl(RedeclarableTemplateDecl *D) {
1916 RedeclarableResult Redecl = VisitRedeclarable(D);
1918 // Make sure we've allocated the Common pointer first. We do this before
1919 // VisitTemplateDecl so that getCommonPtr() can be used during initialization.
1920 RedeclarableTemplateDecl *CanonD = D->getCanonicalDecl();
1921 if (!CanonD->Common) {
1922 CanonD->Common = CanonD->newCommon(Reader.getContext());
1923 Reader.PendingDefinitions.insert(CanonD);
1925 D->Common = CanonD->Common;
1927 // If this is the first declaration of the template, fill in the information
1928 // for the 'common' pointer.
1929 if (ThisDeclID == Redecl.getFirstID()) {
1930 if (RedeclarableTemplateDecl *RTD
1931 = ReadDeclAs<RedeclarableTemplateDecl>()) {
1932 assert(RTD->getKind() == D->getKind() &&
1933 "InstantiatedFromMemberTemplate kind mismatch");
1934 D->setInstantiatedFromMemberTemplate(RTD);
1935 if (Record.readInt())
1936 D->setMemberSpecialization();
1940 DeclID PatternID = VisitTemplateDecl(D);
1941 D->IdentifierNamespace = Record.readInt();
1943 mergeRedeclarable(D, Redecl, PatternID);
1945 // If we merged the template with a prior declaration chain, merge the common
1947 // FIXME: Actually merge here, don't just overwrite.
1948 D->Common = D->getCanonicalDecl()->Common;
1953 static DeclID *newDeclIDList(ASTContext &Context, DeclID *Old,
1954 SmallVectorImpl<DeclID> &IDs) {
1955 assert(!IDs.empty() && "no IDs to add to list");
1957 IDs.insert(IDs.end(), Old + 1, Old + 1 + Old[0]);
1958 std::sort(IDs.begin(), IDs.end());
1959 IDs.erase(std::unique(IDs.begin(), IDs.end()), IDs.end());
1962 auto *Result = new (Context) DeclID[1 + IDs.size()];
1963 *Result = IDs.size();
1964 std::copy(IDs.begin(), IDs.end(), Result + 1);
1968 void ASTDeclReader::VisitClassTemplateDecl(ClassTemplateDecl *D) {
1969 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
1971 if (ThisDeclID == Redecl.getFirstID()) {
1972 // This ClassTemplateDecl owns a CommonPtr; read it to keep track of all of
1973 // the specializations.
1974 SmallVector<serialization::DeclID, 32> SpecIDs;
1975 ReadDeclIDList(SpecIDs);
1977 if (!SpecIDs.empty()) {
1978 auto *CommonPtr = D->getCommonPtr();
1979 CommonPtr->LazySpecializations = newDeclIDList(
1980 Reader.getContext(), CommonPtr->LazySpecializations, SpecIDs);
1984 if (D->getTemplatedDecl()->TemplateOrInstantiation) {
1985 // We were loaded before our templated declaration was. We've not set up
1986 // its corresponding type yet (see VisitCXXRecordDeclImpl), so reconstruct
1988 Reader.Context.getInjectedClassNameType(
1989 D->getTemplatedDecl(), D->getInjectedClassNameSpecialization());
1993 void ASTDeclReader::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) {
1994 llvm_unreachable("BuiltinTemplates are not serialized");
1997 /// TODO: Unify with ClassTemplateDecl version?
1998 /// May require unifying ClassTemplateDecl and
1999 /// VarTemplateDecl beyond TemplateDecl...
2000 void ASTDeclReader::VisitVarTemplateDecl(VarTemplateDecl *D) {
2001 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2003 if (ThisDeclID == Redecl.getFirstID()) {
2004 // This VarTemplateDecl owns a CommonPtr; read it to keep track of all of
2005 // the specializations.
2006 SmallVector<serialization::DeclID, 32> SpecIDs;
2007 ReadDeclIDList(SpecIDs);
2009 if (!SpecIDs.empty()) {
2010 auto *CommonPtr = D->getCommonPtr();
2011 CommonPtr->LazySpecializations = newDeclIDList(
2012 Reader.getContext(), CommonPtr->LazySpecializations, SpecIDs);
2017 ASTDeclReader::RedeclarableResult
2018 ASTDeclReader::VisitClassTemplateSpecializationDeclImpl(
2019 ClassTemplateSpecializationDecl *D) {
2020 RedeclarableResult Redecl = VisitCXXRecordDeclImpl(D);
2022 ASTContext &C = Reader.getContext();
2023 if (Decl *InstD = ReadDecl()) {
2024 if (ClassTemplateDecl *CTD = dyn_cast<ClassTemplateDecl>(InstD)) {
2025 D->SpecializedTemplate = CTD;
2027 SmallVector<TemplateArgument, 8> TemplArgs;
2028 Record.readTemplateArgumentList(TemplArgs);
2029 TemplateArgumentList *ArgList
2030 = TemplateArgumentList::CreateCopy(C, TemplArgs);
2031 ClassTemplateSpecializationDecl::SpecializedPartialSpecialization *PS
2032 = new (C) ClassTemplateSpecializationDecl::
2033 SpecializedPartialSpecialization();
2034 PS->PartialSpecialization
2035 = cast<ClassTemplatePartialSpecializationDecl>(InstD);
2036 PS->TemplateArgs = ArgList;
2037 D->SpecializedTemplate = PS;
2041 SmallVector<TemplateArgument, 8> TemplArgs;
2042 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
2043 D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs);
2044 D->PointOfInstantiation = ReadSourceLocation();
2045 D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
2047 bool writtenAsCanonicalDecl = Record.readInt();
2048 if (writtenAsCanonicalDecl) {
2049 ClassTemplateDecl *CanonPattern = ReadDeclAs<ClassTemplateDecl>();
2050 if (D->isCanonicalDecl()) { // It's kept in the folding set.
2051 // Set this as, or find, the canonical declaration for this specialization
2052 ClassTemplateSpecializationDecl *CanonSpec;
2053 if (ClassTemplatePartialSpecializationDecl *Partial =
2054 dyn_cast<ClassTemplatePartialSpecializationDecl>(D)) {
2055 CanonSpec = CanonPattern->getCommonPtr()->PartialSpecializations
2056 .GetOrInsertNode(Partial);
2059 CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
2061 // If there was already a canonical specialization, merge into it.
2062 if (CanonSpec != D) {
2063 mergeRedeclarable<TagDecl>(D, CanonSpec, Redecl);
2065 // This declaration might be a definition. Merge with any existing
2067 if (auto *DDD = D->DefinitionData) {
2068 if (CanonSpec->DefinitionData)
2069 MergeDefinitionData(CanonSpec, std::move(*DDD));
2071 CanonSpec->DefinitionData = D->DefinitionData;
2073 D->DefinitionData = CanonSpec->DefinitionData;
2079 if (TypeSourceInfo *TyInfo = GetTypeSourceInfo()) {
2080 ClassTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo
2081 = new (C) ClassTemplateSpecializationDecl::ExplicitSpecializationInfo;
2082 ExplicitInfo->TypeAsWritten = TyInfo;
2083 ExplicitInfo->ExternLoc = ReadSourceLocation();
2084 ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation();
2085 D->ExplicitInfo = ExplicitInfo;
2091 void ASTDeclReader::VisitClassTemplatePartialSpecializationDecl(
2092 ClassTemplatePartialSpecializationDecl *D) {
2093 RedeclarableResult Redecl = VisitClassTemplateSpecializationDeclImpl(D);
2095 D->TemplateParams = Record.readTemplateParameterList();
2096 D->ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2098 // These are read/set from/to the first declaration.
2099 if (ThisDeclID == Redecl.getFirstID()) {
2100 D->InstantiatedFromMember.setPointer(
2101 ReadDeclAs<ClassTemplatePartialSpecializationDecl>());
2102 D->InstantiatedFromMember.setInt(Record.readInt());
2106 void ASTDeclReader::VisitClassScopeFunctionSpecializationDecl(
2107 ClassScopeFunctionSpecializationDecl *D) {
2109 D->Specialization = ReadDeclAs<CXXMethodDecl>();
2112 void ASTDeclReader::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
2113 RedeclarableResult Redecl = VisitRedeclarableTemplateDecl(D);
2115 if (ThisDeclID == Redecl.getFirstID()) {
2116 // This FunctionTemplateDecl owns a CommonPtr; read it.
2117 SmallVector<serialization::DeclID, 32> SpecIDs;
2118 ReadDeclIDList(SpecIDs);
2120 if (!SpecIDs.empty()) {
2121 auto *CommonPtr = D->getCommonPtr();
2122 CommonPtr->LazySpecializations = newDeclIDList(
2123 Reader.getContext(), CommonPtr->LazySpecializations, SpecIDs);
2128 /// TODO: Unify with ClassTemplateSpecializationDecl version?
2129 /// May require unifying ClassTemplate(Partial)SpecializationDecl and
2130 /// VarTemplate(Partial)SpecializationDecl with a new data
2131 /// structure Template(Partial)SpecializationDecl, and
2132 /// using Template(Partial)SpecializationDecl as input type.
2133 ASTDeclReader::RedeclarableResult
2134 ASTDeclReader::VisitVarTemplateSpecializationDeclImpl(
2135 VarTemplateSpecializationDecl *D) {
2136 RedeclarableResult Redecl = VisitVarDeclImpl(D);
2138 ASTContext &C = Reader.getContext();
2139 if (Decl *InstD = ReadDecl()) {
2140 if (VarTemplateDecl *VTD = dyn_cast<VarTemplateDecl>(InstD)) {
2141 D->SpecializedTemplate = VTD;
2143 SmallVector<TemplateArgument, 8> TemplArgs;
2144 Record.readTemplateArgumentList(TemplArgs);
2145 TemplateArgumentList *ArgList = TemplateArgumentList::CreateCopy(
2147 VarTemplateSpecializationDecl::SpecializedPartialSpecialization *PS =
2149 VarTemplateSpecializationDecl::SpecializedPartialSpecialization();
2150 PS->PartialSpecialization =
2151 cast<VarTemplatePartialSpecializationDecl>(InstD);
2152 PS->TemplateArgs = ArgList;
2153 D->SpecializedTemplate = PS;
2158 if (TypeSourceInfo *TyInfo = GetTypeSourceInfo()) {
2159 VarTemplateSpecializationDecl::ExplicitSpecializationInfo *ExplicitInfo =
2160 new (C) VarTemplateSpecializationDecl::ExplicitSpecializationInfo;
2161 ExplicitInfo->TypeAsWritten = TyInfo;
2162 ExplicitInfo->ExternLoc = ReadSourceLocation();
2163 ExplicitInfo->TemplateKeywordLoc = ReadSourceLocation();
2164 D->ExplicitInfo = ExplicitInfo;
2167 SmallVector<TemplateArgument, 8> TemplArgs;
2168 Record.readTemplateArgumentList(TemplArgs, /*Canonicalize*/ true);
2169 D->TemplateArgs = TemplateArgumentList::CreateCopy(C, TemplArgs);
2170 D->PointOfInstantiation = ReadSourceLocation();
2171 D->SpecializationKind = (TemplateSpecializationKind)Record.readInt();
2173 bool writtenAsCanonicalDecl = Record.readInt();
2174 if (writtenAsCanonicalDecl) {
2175 VarTemplateDecl *CanonPattern = ReadDeclAs<VarTemplateDecl>();
2176 if (D->isCanonicalDecl()) { // It's kept in the folding set.
2177 // FIXME: If it's already present, merge it.
2178 if (VarTemplatePartialSpecializationDecl *Partial =
2179 dyn_cast<VarTemplatePartialSpecializationDecl>(D)) {
2180 CanonPattern->getCommonPtr()->PartialSpecializations
2181 .GetOrInsertNode(Partial);
2183 CanonPattern->getCommonPtr()->Specializations.GetOrInsertNode(D);
2191 /// TODO: Unify with ClassTemplatePartialSpecializationDecl version?
2192 /// May require unifying ClassTemplate(Partial)SpecializationDecl and
2193 /// VarTemplate(Partial)SpecializationDecl with a new data
2194 /// structure Template(Partial)SpecializationDecl, and
2195 /// using Template(Partial)SpecializationDecl as input type.
2196 void ASTDeclReader::VisitVarTemplatePartialSpecializationDecl(
2197 VarTemplatePartialSpecializationDecl *D) {
2198 RedeclarableResult Redecl = VisitVarTemplateSpecializationDeclImpl(D);
2200 D->TemplateParams = Record.readTemplateParameterList();
2201 D->ArgsAsWritten = Record.readASTTemplateArgumentListInfo();
2203 // These are read/set from/to the first declaration.
2204 if (ThisDeclID == Redecl.getFirstID()) {
2205 D->InstantiatedFromMember.setPointer(
2206 ReadDeclAs<VarTemplatePartialSpecializationDecl>());
2207 D->InstantiatedFromMember.setInt(Record.readInt());
2211 void ASTDeclReader::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
2214 D->setDeclaredWithTypename(Record.readInt());
2216 if (Record.readInt())
2217 D->setDefaultArgument(GetTypeSourceInfo());
2220 void ASTDeclReader::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
2221 VisitDeclaratorDecl(D);
2222 // TemplateParmPosition.
2223 D->setDepth(Record.readInt());
2224 D->setPosition(Record.readInt());
2225 if (D->isExpandedParameterPack()) {
2226 auto TypesAndInfos =
2227 D->getTrailingObjects<std::pair<QualType, TypeSourceInfo *>>();
2228 for (unsigned I = 0, N = D->getNumExpansionTypes(); I != N; ++I) {
2229 new (&TypesAndInfos[I].first) QualType(Record.readType());
2230 TypesAndInfos[I].second = GetTypeSourceInfo();
2233 // Rest of NonTypeTemplateParmDecl.
2234 D->ParameterPack = Record.readInt();
2235 if (Record.readInt())
2236 D->setDefaultArgument(Record.readExpr());
2240 void ASTDeclReader::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
2241 VisitTemplateDecl(D);
2242 // TemplateParmPosition.
2243 D->setDepth(Record.readInt());
2244 D->setPosition(Record.readInt());
2245 if (D->isExpandedParameterPack()) {
2246 TemplateParameterList **Data =
2247 D->getTrailingObjects<TemplateParameterList *>();
2248 for (unsigned I = 0, N = D->getNumExpansionTemplateParameters();
2250 Data[I] = Record.readTemplateParameterList();
2252 // Rest of TemplateTemplateParmDecl.
2253 D->ParameterPack = Record.readInt();
2254 if (Record.readInt())
2255 D->setDefaultArgument(Reader.getContext(),
2256 Record.readTemplateArgumentLoc());
2260 void ASTDeclReader::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
2261 VisitRedeclarableTemplateDecl(D);
2264 void ASTDeclReader::VisitStaticAssertDecl(StaticAssertDecl *D) {
2266 D->AssertExprAndFailed.setPointer(Record.readExpr());
2267 D->AssertExprAndFailed.setInt(Record.readInt());
2268 D->Message = cast_or_null<StringLiteral>(Record.readExpr());
2269 D->RParenLoc = ReadSourceLocation();
2272 void ASTDeclReader::VisitEmptyDecl(EmptyDecl *D) {
2276 std::pair<uint64_t, uint64_t>
2277 ASTDeclReader::VisitDeclContext(DeclContext *DC) {
2278 uint64_t LexicalOffset = ReadLocalOffset();
2279 uint64_t VisibleOffset = ReadLocalOffset();
2280 return std::make_pair(LexicalOffset, VisibleOffset);
2283 template <typename T>
2284 ASTDeclReader::RedeclarableResult
2285 ASTDeclReader::VisitRedeclarable(Redeclarable<T> *D) {
2286 DeclID FirstDeclID = ReadDeclID();
2287 Decl *MergeWith = nullptr;
2289 bool IsKeyDecl = ThisDeclID == FirstDeclID;
2290 bool IsFirstLocalDecl = false;
2292 uint64_t RedeclOffset = 0;
2294 // 0 indicates that this declaration was the only declaration of its entity,
2295 // and is used for space optimization.
2296 if (FirstDeclID == 0) {
2297 FirstDeclID = ThisDeclID;
2299 IsFirstLocalDecl = true;
2300 } else if (unsigned N = Record.readInt()) {
2301 // This declaration was the first local declaration, but may have imported
2302 // other declarations.
2304 IsFirstLocalDecl = true;
2306 // We have some declarations that must be before us in our redeclaration
2307 // chain. Read them now, and remember that we ought to merge with one of
2309 // FIXME: Provide a known merge target to the second and subsequent such
2311 for (unsigned I = 0; I != N - 1; ++I)
2312 MergeWith = ReadDecl();
2314 RedeclOffset = ReadLocalOffset();
2316 // This declaration was not the first local declaration. Read the first
2317 // local declaration now, to trigger the import of other redeclarations.
2321 T *FirstDecl = cast_or_null<T>(Reader.GetDecl(FirstDeclID));
2322 if (FirstDecl != D) {
2323 // We delay loading of the redeclaration chain to avoid deeply nested calls.
2324 // We temporarily set the first (canonical) declaration as the previous one
2325 // which is the one that matters and mark the real previous DeclID to be
2326 // loaded & attached later on.
2327 D->RedeclLink = Redeclarable<T>::PreviousDeclLink(FirstDecl);
2328 D->First = FirstDecl->getCanonicalDecl();
2331 T *DAsT = static_cast<T*>(D);
2333 // Note that we need to load local redeclarations of this decl and build a
2334 // decl chain for them. This must happen *after* we perform the preloading
2335 // above; this ensures that the redeclaration chain is built in the correct
2337 if (IsFirstLocalDecl)
2338 Reader.PendingDeclChains.push_back(std::make_pair(DAsT, RedeclOffset));
2340 return RedeclarableResult(MergeWith, FirstDeclID, IsKeyDecl);
2343 /// \brief Attempts to merge the given declaration (D) with another declaration
2344 /// of the same entity.
2345 template<typename T>
2346 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase,
2347 RedeclarableResult &Redecl,
2348 DeclID TemplatePatternID) {
2349 // If modules are not available, there is no reason to perform this merge.
2350 if (!Reader.getContext().getLangOpts().Modules)
2353 // If we're not the canonical declaration, we don't need to merge.
2354 if (!DBase->isFirstDecl())
2357 T *D = static_cast<T*>(DBase);
2359 if (auto *Existing = Redecl.getKnownMergeTarget())
2360 // We already know of an existing declaration we should merge with.
2361 mergeRedeclarable(D, cast<T>(Existing), Redecl, TemplatePatternID);
2362 else if (FindExistingResult ExistingRes = findExisting(D))
2363 if (T *Existing = ExistingRes)
2364 mergeRedeclarable(D, Existing, Redecl, TemplatePatternID);
2367 /// \brief "Cast" to type T, asserting if we don't have an implicit conversion.
2368 /// We use this to put code in a template that will only be valid for certain
2370 template<typename T> static T assert_cast(T t) { return t; }
2371 template<typename T> static T assert_cast(...) {
2372 llvm_unreachable("bad assert_cast");
2375 /// \brief Merge together the pattern declarations from two template
2377 void ASTDeclReader::mergeTemplatePattern(RedeclarableTemplateDecl *D,
2378 RedeclarableTemplateDecl *Existing,
2379 DeclID DsID, bool IsKeyDecl) {
2380 auto *DPattern = D->getTemplatedDecl();
2381 auto *ExistingPattern = Existing->getTemplatedDecl();
2382 RedeclarableResult Result(/*MergeWith*/ ExistingPattern,
2383 DPattern->getCanonicalDecl()->getGlobalID(),
2386 if (auto *DClass = dyn_cast<CXXRecordDecl>(DPattern)) {
2387 // Merge with any existing definition.
2388 // FIXME: This is duplicated in several places. Refactor.
2389 auto *ExistingClass =
2390 cast<CXXRecordDecl>(ExistingPattern)->getCanonicalDecl();
2391 if (auto *DDD = DClass->DefinitionData) {
2392 if (ExistingClass->DefinitionData) {
2393 MergeDefinitionData(ExistingClass, std::move(*DDD));
2395 ExistingClass->DefinitionData = DClass->DefinitionData;
2396 // We may have skipped this before because we thought that DClass
2397 // was the canonical declaration.
2398 Reader.PendingDefinitions.insert(DClass);
2401 DClass->DefinitionData = ExistingClass->DefinitionData;
2403 return mergeRedeclarable(DClass, cast<TagDecl>(ExistingPattern),
2406 if (auto *DFunction = dyn_cast<FunctionDecl>(DPattern))
2407 return mergeRedeclarable(DFunction, cast<FunctionDecl>(ExistingPattern),
2409 if (auto *DVar = dyn_cast<VarDecl>(DPattern))
2410 return mergeRedeclarable(DVar, cast<VarDecl>(ExistingPattern), Result);
2411 if (auto *DAlias = dyn_cast<TypeAliasDecl>(DPattern))
2412 return mergeRedeclarable(DAlias, cast<TypedefNameDecl>(ExistingPattern),
2414 llvm_unreachable("merged an unknown kind of redeclarable template");
2417 /// \brief Attempts to merge the given declaration (D) with another declaration
2418 /// of the same entity.
2419 template<typename T>
2420 void ASTDeclReader::mergeRedeclarable(Redeclarable<T> *DBase, T *Existing,
2421 RedeclarableResult &Redecl,
2422 DeclID TemplatePatternID) {
2423 T *D = static_cast<T*>(DBase);
2424 T *ExistingCanon = Existing->getCanonicalDecl();
2425 T *DCanon = D->getCanonicalDecl();
2426 if (ExistingCanon != DCanon) {
2427 assert(DCanon->getGlobalID() == Redecl.getFirstID() &&
2428 "already merged this declaration");
2430 // Have our redeclaration link point back at the canonical declaration
2431 // of the existing declaration, so that this declaration has the
2432 // appropriate canonical declaration.
2433 D->RedeclLink = Redeclarable<T>::PreviousDeclLink(ExistingCanon);
2434 D->First = ExistingCanon;
2435 ExistingCanon->Used |= D->Used;
2438 // When we merge a namespace, update its pointer to the first namespace.
2439 // We cannot have loaded any redeclarations of this declaration yet, so
2440 // there's nothing else that needs to be updated.
2441 if (auto *Namespace = dyn_cast<NamespaceDecl>(D))
2442 Namespace->AnonOrFirstNamespaceAndInline.setPointer(
2443 assert_cast<NamespaceDecl*>(ExistingCanon));
2445 // When we merge a template, merge its pattern.
2446 if (auto *DTemplate = dyn_cast<RedeclarableTemplateDecl>(D))
2447 mergeTemplatePattern(
2448 DTemplate, assert_cast<RedeclarableTemplateDecl*>(ExistingCanon),
2449 TemplatePatternID, Redecl.isKeyDecl());
2451 // If this declaration is a key declaration, make a note of that.
2452 if (Redecl.isKeyDecl())
2453 Reader.KeyDecls[ExistingCanon].push_back(Redecl.getFirstID());
2457 /// \brief Attempts to merge the given declaration (D) with another declaration
2458 /// of the same entity, for the case where the entity is not actually
2459 /// redeclarable. This happens, for instance, when merging the fields of
2460 /// identical class definitions from two different modules.
2461 template<typename T>
2462 void ASTDeclReader::mergeMergeable(Mergeable<T> *D) {
2463 // If modules are not available, there is no reason to perform this merge.
2464 if (!Reader.getContext().getLangOpts().Modules)
2467 // ODR-based merging is only performed in C++. In C, identically-named things
2468 // in different translation units are not redeclarations (but may still have
2469 // compatible types).
2470 if (!Reader.getContext().getLangOpts().CPlusPlus)
2473 if (FindExistingResult ExistingRes = findExisting(static_cast<T*>(D)))
2474 if (T *Existing = ExistingRes)
2475 Reader.Context.setPrimaryMergedDecl(static_cast<T*>(D),
2476 Existing->getCanonicalDecl());
2479 void ASTDeclReader::VisitOMPThreadPrivateDecl(OMPThreadPrivateDecl *D) {
2481 unsigned NumVars = D->varlist_size();
2482 SmallVector<Expr *, 16> Vars;
2483 Vars.reserve(NumVars);
2484 for (unsigned i = 0; i != NumVars; ++i) {
2485 Vars.push_back(Record.readExpr());
2490 void ASTDeclReader::VisitOMPDeclareReductionDecl(OMPDeclareReductionDecl *D) {
2492 D->setLocation(ReadSourceLocation());
2493 D->setCombiner(Record.readExpr());
2494 D->setInitializer(Record.readExpr());
2495 D->PrevDeclInScope = ReadDeclID();
2498 void ASTDeclReader::VisitOMPCapturedExprDecl(OMPCapturedExprDecl *D) {
2502 //===----------------------------------------------------------------------===//
2503 // Attribute Reading
2504 //===----------------------------------------------------------------------===//
2506 /// \brief Reads attributes from the current stream position.
2507 void ASTReader::ReadAttributes(ASTRecordReader &Record, AttrVec &Attrs) {
2508 for (unsigned i = 0, e = Record.readInt(); i != e; ++i) {
2509 Attr *New = nullptr;
2510 attr::Kind Kind = (attr::Kind)Record.readInt();
2511 SourceRange Range = Record.readSourceRange();
2513 #include "clang/Serialization/AttrPCHRead.inc"
2515 assert(New && "Unable to decode attribute?");
2516 Attrs.push_back(New);
2520 //===----------------------------------------------------------------------===//
2521 // ASTReader Implementation
2522 //===----------------------------------------------------------------------===//
2524 /// \brief Note that we have loaded the declaration with the given
2527 /// This routine notes that this declaration has already been loaded,
2528 /// so that future GetDecl calls will return this declaration rather
2529 /// than trying to load a new declaration.
2530 inline void ASTReader::LoadedDecl(unsigned Index, Decl *D) {
2531 assert(!DeclsLoaded[Index] && "Decl loaded twice?");
2532 DeclsLoaded[Index] = D;
2536 /// \brief Determine whether the consumer will be interested in seeing
2537 /// this declaration (via HandleTopLevelDecl).
2539 /// This routine should return true for anything that might affect
2540 /// code generation, e.g., inline function definitions, Objective-C
2541 /// declarations with metadata, etc.
2542 static bool isConsumerInterestedIn(ASTContext &Ctx, Decl *D, bool HasBody) {
2543 // An ObjCMethodDecl is never considered as "interesting" because its
2544 // implementation container always is.
2546 // An ImportDecl or VarDecl imported from a module will get emitted when
2547 // we import the relevant module.
2548 if ((isa<ImportDecl>(D) || isa<VarDecl>(D)) && D->getImportedOwningModule() &&
2549 Ctx.DeclMustBeEmitted(D))
2552 if (isa<FileScopeAsmDecl>(D) ||
2553 isa<ObjCProtocolDecl>(D) ||
2554 isa<ObjCImplDecl>(D) ||
2555 isa<ImportDecl>(D) ||
2556 isa<PragmaCommentDecl>(D) ||
2557 isa<PragmaDetectMismatchDecl>(D))
2559 if (isa<OMPThreadPrivateDecl>(D) || isa<OMPDeclareReductionDecl>(D))
2560 return !D->getDeclContext()->isFunctionOrMethod();
2561 if (VarDecl *Var = dyn_cast<VarDecl>(D))
2562 return Var->isFileVarDecl() &&
2563 Var->isThisDeclarationADefinition() == VarDecl::Definition;
2564 if (FunctionDecl *Func = dyn_cast<FunctionDecl>(D))
2565 return Func->doesThisDeclarationHaveABody() || HasBody;
2567 if (auto *ES = D->getASTContext().getExternalSource())
2568 if (ES->hasExternalDefinitions(D) == ExternalASTSource::EK_Never)
2574 /// \brief Get the correct cursor and offset for loading a declaration.
2575 ASTReader::RecordLocation
2576 ASTReader::DeclCursorForID(DeclID ID, SourceLocation &Loc) {
2577 GlobalDeclMapType::iterator I = GlobalDeclMap.find(ID);
2578 assert(I != GlobalDeclMap.end() && "Corrupted global declaration map");
2579 ModuleFile *M = I->second;
2580 const DeclOffset &DOffs =
2581 M->DeclOffsets[ID - M->BaseDeclID - NUM_PREDEF_DECL_IDS];
2582 Loc = TranslateSourceLocation(*M, DOffs.getLocation());
2583 return RecordLocation(M, DOffs.BitOffset);
2586 ASTReader::RecordLocation ASTReader::getLocalBitOffset(uint64_t GlobalOffset) {
2587 ContinuousRangeMap<uint64_t, ModuleFile*, 4>::iterator I
2588 = GlobalBitOffsetsMap.find(GlobalOffset);
2590 assert(I != GlobalBitOffsetsMap.end() && "Corrupted global bit offsets map");
2591 return RecordLocation(I->second, GlobalOffset - I->second->GlobalBitOffset);
2594 uint64_t ASTReader::getGlobalBitOffset(ModuleFile &M, uint32_t LocalOffset) {
2595 return LocalOffset + M.GlobalBitOffset;
2598 static bool isSameTemplateParameterList(const TemplateParameterList *X,
2599 const TemplateParameterList *Y);
2601 /// \brief Determine whether two template parameters are similar enough
2602 /// that they may be used in declarations of the same template.
2603 static bool isSameTemplateParameter(const NamedDecl *X,
2604 const NamedDecl *Y) {
2605 if (X->getKind() != Y->getKind())
2608 if (const TemplateTypeParmDecl *TX = dyn_cast<TemplateTypeParmDecl>(X)) {
2609 const TemplateTypeParmDecl *TY = cast<TemplateTypeParmDecl>(Y);
2610 return TX->isParameterPack() == TY->isParameterPack();
2613 if (const NonTypeTemplateParmDecl *TX = dyn_cast<NonTypeTemplateParmDecl>(X)) {
2614 const NonTypeTemplateParmDecl *TY = cast<NonTypeTemplateParmDecl>(Y);
2615 return TX->isParameterPack() == TY->isParameterPack() &&
2616 TX->getASTContext().hasSameType(TX->getType(), TY->getType());
2619 const TemplateTemplateParmDecl *TX = cast<TemplateTemplateParmDecl>(X);
2620 const TemplateTemplateParmDecl *TY = cast<TemplateTemplateParmDecl>(Y);
2621 return TX->isParameterPack() == TY->isParameterPack() &&
2622 isSameTemplateParameterList(TX->getTemplateParameters(),
2623 TY->getTemplateParameters());
2626 static NamespaceDecl *getNamespace(const NestedNameSpecifier *X) {
2627 if (auto *NS = X->getAsNamespace())
2629 if (auto *NAS = X->getAsNamespaceAlias())
2630 return NAS->getNamespace();
2634 static bool isSameQualifier(const NestedNameSpecifier *X,
2635 const NestedNameSpecifier *Y) {
2636 if (auto *NSX = getNamespace(X)) {
2637 auto *NSY = getNamespace(Y);
2638 if (!NSY || NSX->getCanonicalDecl() != NSY->getCanonicalDecl())
2640 } else if (X->getKind() != Y->getKind())
2643 // FIXME: For namespaces and types, we're permitted to check that the entity
2644 // is named via the same tokens. We should probably do so.
2645 switch (X->getKind()) {
2646 case NestedNameSpecifier::Identifier:
2647 if (X->getAsIdentifier() != Y->getAsIdentifier())
2650 case NestedNameSpecifier::Namespace:
2651 case NestedNameSpecifier::NamespaceAlias:
2652 // We've already checked that we named the same namespace.
2654 case NestedNameSpecifier::TypeSpec:
2655 case NestedNameSpecifier::TypeSpecWithTemplate:
2656 if (X->getAsType()->getCanonicalTypeInternal() !=
2657 Y->getAsType()->getCanonicalTypeInternal())
2660 case NestedNameSpecifier::Global:
2661 case NestedNameSpecifier::Super:
2665 // Recurse into earlier portion of NNS, if any.
2666 auto *PX = X->getPrefix();
2667 auto *PY = Y->getPrefix();
2669 return isSameQualifier(PX, PY);
2673 /// \brief Determine whether two template parameter lists are similar enough
2674 /// that they may be used in declarations of the same template.
2675 static bool isSameTemplateParameterList(const TemplateParameterList *X,
2676 const TemplateParameterList *Y) {
2677 if (X->size() != Y->size())
2680 for (unsigned I = 0, N = X->size(); I != N; ++I)
2681 if (!isSameTemplateParameter(X->getParam(I), Y->getParam(I)))
2687 /// Determine whether the attributes we can overload on are identical for A and
2688 /// B. Will ignore any overloadable attrs represented in the type of A and B.
2689 static bool hasSameOverloadableAttrs(const FunctionDecl *A,
2690 const FunctionDecl *B) {
2691 // Note that pass_object_size attributes are represented in the function's
2692 // ExtParameterInfo, so we don't need to check them here.
2694 SmallVector<const EnableIfAttr *, 4> AEnableIfs;
2695 // Since this is an equality check, we can ignore that enable_if attrs show up
2696 // in reverse order.
2697 for (const auto *EIA : A->specific_attrs<EnableIfAttr>())
2698 AEnableIfs.push_back(EIA);
2700 SmallVector<const EnableIfAttr *, 4> BEnableIfs;
2701 for (const auto *EIA : B->specific_attrs<EnableIfAttr>())
2702 BEnableIfs.push_back(EIA);
2704 // Two very common cases: either we have 0 enable_if attrs, or we have an
2705 // unequal number of enable_if attrs.
2706 if (AEnableIfs.empty() && BEnableIfs.empty())
2709 if (AEnableIfs.size() != BEnableIfs.size())
2712 llvm::FoldingSetNodeID Cand1ID, Cand2ID;
2713 for (unsigned I = 0, E = AEnableIfs.size(); I != E; ++I) {
2717 AEnableIfs[I]->getCond()->Profile(Cand1ID, A->getASTContext(), true);
2718 BEnableIfs[I]->getCond()->Profile(Cand2ID, B->getASTContext(), true);
2719 if (Cand1ID != Cand2ID)
2726 /// \brief Determine whether the two declarations refer to the same entity.
2727 static bool isSameEntity(NamedDecl *X, NamedDecl *Y) {
2728 assert(X->getDeclName() == Y->getDeclName() && "Declaration name mismatch!");
2733 // Must be in the same context.
2734 if (!X->getDeclContext()->getRedeclContext()->Equals(
2735 Y->getDeclContext()->getRedeclContext()))
2738 // Two typedefs refer to the same entity if they have the same underlying
2740 if (TypedefNameDecl *TypedefX = dyn_cast<TypedefNameDecl>(X))
2741 if (TypedefNameDecl *TypedefY = dyn_cast<TypedefNameDecl>(Y))
2742 return X->getASTContext().hasSameType(TypedefX->getUnderlyingType(),
2743 TypedefY->getUnderlyingType());
2745 // Must have the same kind.
2746 if (X->getKind() != Y->getKind())
2749 // Objective-C classes and protocols with the same name always match.
2750 if (isa<ObjCInterfaceDecl>(X) || isa<ObjCProtocolDecl>(X))
2753 if (isa<ClassTemplateSpecializationDecl>(X)) {
2754 // No need to handle these here: we merge them when adding them to the
2759 // Compatible tags match.
2760 if (TagDecl *TagX = dyn_cast<TagDecl>(X)) {
2761 TagDecl *TagY = cast<TagDecl>(Y);
2762 return (TagX->getTagKind() == TagY->getTagKind()) ||
2763 ((TagX->getTagKind() == TTK_Struct || TagX->getTagKind() == TTK_Class ||
2764 TagX->getTagKind() == TTK_Interface) &&
2765 (TagY->getTagKind() == TTK_Struct || TagY->getTagKind() == TTK_Class ||
2766 TagY->getTagKind() == TTK_Interface));
2769 // Functions with the same type and linkage match.
2770 // FIXME: This needs to cope with merging of prototyped/non-prototyped
2772 if (FunctionDecl *FuncX = dyn_cast<FunctionDecl>(X)) {
2773 FunctionDecl *FuncY = cast<FunctionDecl>(Y);
2774 if (CXXConstructorDecl *CtorX = dyn_cast<CXXConstructorDecl>(X)) {
2775 CXXConstructorDecl *CtorY = cast<CXXConstructorDecl>(Y);
2776 if (CtorX->getInheritedConstructor() &&
2777 !isSameEntity(CtorX->getInheritedConstructor().getConstructor(),
2778 CtorY->getInheritedConstructor().getConstructor()))
2781 ASTContext &C = FuncX->getASTContext();
2782 if (!C.hasSameType(FuncX->getType(), FuncY->getType())) {
2783 // We can get functions with different types on the redecl chain in C++17
2784 // if they have differing exception specifications and at least one of
2785 // the excpetion specs is unresolved.
2786 // FIXME: Do we need to check for C++14 deduced return types here too?
2787 auto *XFPT = FuncX->getType()->getAs<FunctionProtoType>();
2788 auto *YFPT = FuncY->getType()->getAs<FunctionProtoType>();
2789 if (C.getLangOpts().CPlusPlus1z && XFPT && YFPT &&
2790 (isUnresolvedExceptionSpec(XFPT->getExceptionSpecType()) ||
2791 isUnresolvedExceptionSpec(YFPT->getExceptionSpecType())) &&
2792 C.hasSameFunctionTypeIgnoringExceptionSpec(FuncX->getType(),
2797 return FuncX->getLinkageInternal() == FuncY->getLinkageInternal() &&
2798 hasSameOverloadableAttrs(FuncX, FuncY);
2801 // Variables with the same type and linkage match.
2802 if (VarDecl *VarX = dyn_cast<VarDecl>(X)) {
2803 VarDecl *VarY = cast<VarDecl>(Y);
2804 if (VarX->getLinkageInternal() == VarY->getLinkageInternal()) {
2805 ASTContext &C = VarX->getASTContext();
2806 if (C.hasSameType(VarX->getType(), VarY->getType()))
2809 // We can get decls with different types on the redecl chain. Eg.
2810 // template <typename T> struct S { static T Var[]; }; // #1
2811 // template <typename T> T S<T>::Var[sizeof(T)]; // #2
2812 // Only? happens when completing an incomplete array type. In this case
2813 // when comparing #1 and #2 we should go through their element type.
2814 const ArrayType *VarXTy = C.getAsArrayType(VarX->getType());
2815 const ArrayType *VarYTy = C.getAsArrayType(VarY->getType());
2816 if (!VarXTy || !VarYTy)
2818 if (VarXTy->isIncompleteArrayType() || VarYTy->isIncompleteArrayType())
2819 return C.hasSameType(VarXTy->getElementType(), VarYTy->getElementType());
2824 // Namespaces with the same name and inlinedness match.
2825 if (NamespaceDecl *NamespaceX = dyn_cast<NamespaceDecl>(X)) {
2826 NamespaceDecl *NamespaceY = cast<NamespaceDecl>(Y);
2827 return NamespaceX->isInline() == NamespaceY->isInline();
2830 // Identical template names and kinds match if their template parameter lists
2831 // and patterns match.
2832 if (TemplateDecl *TemplateX = dyn_cast<TemplateDecl>(X)) {
2833 TemplateDecl *TemplateY = cast<TemplateDecl>(Y);
2834 return isSameEntity(TemplateX->getTemplatedDecl(),
2835 TemplateY->getTemplatedDecl()) &&
2836 isSameTemplateParameterList(TemplateX->getTemplateParameters(),
2837 TemplateY->getTemplateParameters());
2840 // Fields with the same name and the same type match.
2841 if (FieldDecl *FDX = dyn_cast<FieldDecl>(X)) {
2842 FieldDecl *FDY = cast<FieldDecl>(Y);
2843 // FIXME: Also check the bitwidth is odr-equivalent, if any.
2844 return X->getASTContext().hasSameType(FDX->getType(), FDY->getType());
2847 // Indirect fields with the same target field match.
2848 if (auto *IFDX = dyn_cast<IndirectFieldDecl>(X)) {
2849 auto *IFDY = cast<IndirectFieldDecl>(Y);
2850 return IFDX->getAnonField()->getCanonicalDecl() ==
2851 IFDY->getAnonField()->getCanonicalDecl();
2854 // Enumerators with the same name match.
2855 if (isa<EnumConstantDecl>(X))
2856 // FIXME: Also check the value is odr-equivalent.
2859 // Using shadow declarations with the same target match.
2860 if (UsingShadowDecl *USX = dyn_cast<UsingShadowDecl>(X)) {
2861 UsingShadowDecl *USY = cast<UsingShadowDecl>(Y);
2862 return USX->getTargetDecl() == USY->getTargetDecl();
2865 // Using declarations with the same qualifier match. (We already know that
2866 // the name matches.)
2867 if (auto *UX = dyn_cast<UsingDecl>(X)) {
2868 auto *UY = cast<UsingDecl>(Y);
2869 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
2870 UX->hasTypename() == UY->hasTypename() &&
2871 UX->isAccessDeclaration() == UY->isAccessDeclaration();
2873 if (auto *UX = dyn_cast<UnresolvedUsingValueDecl>(X)) {
2874 auto *UY = cast<UnresolvedUsingValueDecl>(Y);
2875 return isSameQualifier(UX->getQualifier(), UY->getQualifier()) &&
2876 UX->isAccessDeclaration() == UY->isAccessDeclaration();
2878 if (auto *UX = dyn_cast<UnresolvedUsingTypenameDecl>(X))
2879 return isSameQualifier(
2881 cast<UnresolvedUsingTypenameDecl>(Y)->getQualifier());
2883 // Namespace alias definitions with the same target match.
2884 if (auto *NAX = dyn_cast<NamespaceAliasDecl>(X)) {
2885 auto *NAY = cast<NamespaceAliasDecl>(Y);
2886 return NAX->getNamespace()->Equals(NAY->getNamespace());
2892 /// Find the context in which we should search for previous declarations when
2893 /// looking for declarations to merge.
2894 DeclContext *ASTDeclReader::getPrimaryContextForMerging(ASTReader &Reader,
2896 if (NamespaceDecl *ND = dyn_cast<NamespaceDecl>(DC))
2897 return ND->getOriginalNamespace();
2899 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(DC)) {
2900 // Try to dig out the definition.
2901 auto *DD = RD->DefinitionData;
2903 DD = RD->getCanonicalDecl()->DefinitionData;
2905 // If there's no definition yet, then DC's definition is added by an update
2906 // record, but we've not yet loaded that update record. In this case, we
2907 // commit to DC being the canonical definition now, and will fix this when
2908 // we load the update record.
2910 DD = new (Reader.Context) struct CXXRecordDecl::DefinitionData(RD);
2911 RD->IsCompleteDefinition = true;
2912 RD->DefinitionData = DD;
2913 RD->getCanonicalDecl()->DefinitionData = DD;
2915 // Track that we did this horrible thing so that we can fix it later.
2916 Reader.PendingFakeDefinitionData.insert(
2917 std::make_pair(DD, ASTReader::PendingFakeDefinitionKind::Fake));
2920 return DD->Definition;
2923 if (EnumDecl *ED = dyn_cast<EnumDecl>(DC))
2924 return ED->getASTContext().getLangOpts().CPlusPlus? ED->getDefinition()
2927 // We can see the TU here only if we have no Sema object. In that case,
2928 // there's no TU scope to look in, so using the DC alone is sufficient.
2929 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
2935 ASTDeclReader::FindExistingResult::~FindExistingResult() {
2936 // Record that we had a typedef name for linkage whether or not we merge
2937 // with that declaration.
2938 if (TypedefNameForLinkage) {
2939 DeclContext *DC = New->getDeclContext()->getRedeclContext();
2940 Reader.ImportedTypedefNamesForLinkage.insert(
2941 std::make_pair(std::make_pair(DC, TypedefNameForLinkage), New));
2945 if (!AddResult || Existing)
2948 DeclarationName Name = New->getDeclName();
2949 DeclContext *DC = New->getDeclContext()->getRedeclContext();
2950 if (needsAnonymousDeclarationNumber(New)) {
2951 setAnonymousDeclForMerging(Reader, New->getLexicalDeclContext(),
2952 AnonymousDeclNumber, New);
2953 } else if (DC->isTranslationUnit() &&
2954 !Reader.getContext().getLangOpts().CPlusPlus) {
2955 if (Reader.getIdResolver().tryAddTopLevelDecl(New, Name))
2956 Reader.PendingFakeLookupResults[Name.getAsIdentifierInfo()]
2958 } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
2959 // Add the declaration to its redeclaration context so later merging
2960 // lookups will find it.
2961 MergeDC->makeDeclVisibleInContextImpl(New, /*Internal*/true);
2965 /// Find the declaration that should be merged into, given the declaration found
2966 /// by name lookup. If we're merging an anonymous declaration within a typedef,
2967 /// we need a matching typedef, and we merge with the type inside it.
2968 static NamedDecl *getDeclForMerging(NamedDecl *Found,
2969 bool IsTypedefNameForLinkage) {
2970 if (!IsTypedefNameForLinkage)
2973 // If we found a typedef declaration that gives a name to some other
2974 // declaration, then we want that inner declaration. Declarations from
2975 // AST files are handled via ImportedTypedefNamesForLinkage.
2976 if (Found->isFromASTFile())
2979 if (auto *TND = dyn_cast<TypedefNameDecl>(Found))
2980 return TND->getAnonDeclWithTypedefName(/*AnyRedecl*/true);
2985 NamedDecl *ASTDeclReader::getAnonymousDeclForMerging(ASTReader &Reader,
2988 // If the lexical context has been merged, look into the now-canonical
2990 if (auto *Merged = Reader.MergedDeclContexts.lookup(DC))
2993 // If we've seen this before, return the canonical declaration.
2994 auto &Previous = Reader.AnonymousDeclarationsForMerging[DC];
2995 if (Index < Previous.size() && Previous[Index])
2996 return Previous[Index];
2998 // If this is the first time, but we have parsed a declaration of the context,
2999 // build the anonymous declaration list from the parsed declaration.
3000 if (!cast<Decl>(DC)->isFromASTFile()) {
3001 numberAnonymousDeclsWithin(DC, [&](NamedDecl *ND, unsigned Number) {
3002 if (Previous.size() == Number)
3003 Previous.push_back(cast<NamedDecl>(ND->getCanonicalDecl()));
3005 Previous[Number] = cast<NamedDecl>(ND->getCanonicalDecl());
3009 return Index < Previous.size() ? Previous[Index] : nullptr;
3012 void ASTDeclReader::setAnonymousDeclForMerging(ASTReader &Reader,
3013 DeclContext *DC, unsigned Index,
3015 if (auto *Merged = Reader.MergedDeclContexts.lookup(DC))
3018 auto &Previous = Reader.AnonymousDeclarationsForMerging[DC];
3019 if (Index >= Previous.size())
3020 Previous.resize(Index + 1);
3021 if (!Previous[Index])
3022 Previous[Index] = D;
3025 ASTDeclReader::FindExistingResult ASTDeclReader::findExisting(NamedDecl *D) {
3026 DeclarationName Name = TypedefNameForLinkage ? TypedefNameForLinkage
3029 if (!Name && !needsAnonymousDeclarationNumber(D)) {
3030 // Don't bother trying to find unnamed declarations that are in
3031 // unmergeable contexts.
3032 FindExistingResult Result(Reader, D, /*Existing=*/nullptr,
3033 AnonymousDeclNumber, TypedefNameForLinkage);
3038 DeclContext *DC = D->getDeclContext()->getRedeclContext();
3039 if (TypedefNameForLinkage) {
3040 auto It = Reader.ImportedTypedefNamesForLinkage.find(
3041 std::make_pair(DC, TypedefNameForLinkage));
3042 if (It != Reader.ImportedTypedefNamesForLinkage.end())
3043 if (isSameEntity(It->second, D))
3044 return FindExistingResult(Reader, D, It->second, AnonymousDeclNumber,
3045 TypedefNameForLinkage);
3046 // Go on to check in other places in case an existing typedef name
3047 // was not imported.
3050 if (needsAnonymousDeclarationNumber(D)) {
3051 // This is an anonymous declaration that we may need to merge. Look it up
3052 // in its context by number.
3053 if (auto *Existing = getAnonymousDeclForMerging(
3054 Reader, D->getLexicalDeclContext(), AnonymousDeclNumber))
3055 if (isSameEntity(Existing, D))
3056 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3057 TypedefNameForLinkage);
3058 } else if (DC->isTranslationUnit() &&
3059 !Reader.getContext().getLangOpts().CPlusPlus) {
3060 IdentifierResolver &IdResolver = Reader.getIdResolver();
3062 // Temporarily consider the identifier to be up-to-date. We don't want to
3063 // cause additional lookups here.
3064 class UpToDateIdentifierRAII {
3069 explicit UpToDateIdentifierRAII(IdentifierInfo *II)
3070 : II(II), WasOutToDate(false)
3073 WasOutToDate = II->isOutOfDate();
3075 II->setOutOfDate(false);
3079 ~UpToDateIdentifierRAII() {
3081 II->setOutOfDate(true);
3083 } UpToDate(Name.getAsIdentifierInfo());
3085 for (IdentifierResolver::iterator I = IdResolver.begin(Name),
3086 IEnd = IdResolver.end();
3088 if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
3089 if (isSameEntity(Existing, D))
3090 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3091 TypedefNameForLinkage);
3093 } else if (DeclContext *MergeDC = getPrimaryContextForMerging(Reader, DC)) {
3094 DeclContext::lookup_result R = MergeDC->noload_lookup(Name);
3095 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
3096 if (NamedDecl *Existing = getDeclForMerging(*I, TypedefNameForLinkage))
3097 if (isSameEntity(Existing, D))
3098 return FindExistingResult(Reader, D, Existing, AnonymousDeclNumber,
3099 TypedefNameForLinkage);
3102 // Not in a mergeable context.
3103 return FindExistingResult(Reader);
3106 // If this declaration is from a merged context, make a note that we need to
3107 // check that the canonical definition of that context contains the decl.
3109 // FIXME: We should do something similar if we merge two definitions of the
3110 // same template specialization into the same CXXRecordDecl.
3111 auto MergedDCIt = Reader.MergedDeclContexts.find(D->getLexicalDeclContext());
3112 if (MergedDCIt != Reader.MergedDeclContexts.end() &&
3113 MergedDCIt->second == D->getDeclContext())
3114 Reader.PendingOdrMergeChecks.push_back(D);
3116 return FindExistingResult(Reader, D, /*Existing=*/nullptr,
3117 AnonymousDeclNumber, TypedefNameForLinkage);
3120 template<typename DeclT>
3121 Decl *ASTDeclReader::getMostRecentDeclImpl(Redeclarable<DeclT> *D) {
3122 return D->RedeclLink.getLatestNotUpdated();
3124 Decl *ASTDeclReader::getMostRecentDeclImpl(...) {
3125 llvm_unreachable("getMostRecentDecl on non-redeclarable declaration");
3128 Decl *ASTDeclReader::getMostRecentDecl(Decl *D) {
3131 switch (D->getKind()) {
3132 #define ABSTRACT_DECL(TYPE)
3133 #define DECL(TYPE, BASE) \
3135 return getMostRecentDeclImpl(cast<TYPE##Decl>(D));
3136 #include "clang/AST/DeclNodes.inc"
3138 llvm_unreachable("unknown decl kind");
3141 Decl *ASTReader::getMostRecentExistingDecl(Decl *D) {
3142 return ASTDeclReader::getMostRecentDecl(D->getCanonicalDecl());
3145 template<typename DeclT>
3146 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3147 Redeclarable<DeclT> *D,
3148 Decl *Previous, Decl *Canon) {
3149 D->RedeclLink.setPrevious(cast<DeclT>(Previous));
3150 D->First = cast<DeclT>(Previous)->First;
3155 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3156 Redeclarable<VarDecl> *D,
3157 Decl *Previous, Decl *Canon) {
3158 VarDecl *VD = static_cast<VarDecl*>(D);
3159 VarDecl *PrevVD = cast<VarDecl>(Previous);
3160 D->RedeclLink.setPrevious(PrevVD);
3161 D->First = PrevVD->First;
3163 // We should keep at most one definition on the chain.
3164 // FIXME: Cache the definition once we've found it. Building a chain with
3165 // N definitions currently takes O(N^2) time here.
3166 if (VD->isThisDeclarationADefinition() == VarDecl::Definition) {
3167 for (VarDecl *CurD = PrevVD; CurD; CurD = CurD->getPreviousDecl()) {
3168 if (CurD->isThisDeclarationADefinition() == VarDecl::Definition) {
3169 Reader.mergeDefinitionVisibility(CurD, VD);
3170 VD->demoteThisDefinitionToDeclaration();
3178 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader,
3179 Redeclarable<FunctionDecl> *D,
3180 Decl *Previous, Decl *Canon) {
3181 FunctionDecl *FD = static_cast<FunctionDecl*>(D);
3182 FunctionDecl *PrevFD = cast<FunctionDecl>(Previous);
3184 FD->RedeclLink.setPrevious(PrevFD);
3185 FD->First = PrevFD->First;
3187 // If the previous declaration is an inline function declaration, then this
3188 // declaration is too.
3189 if (PrevFD->IsInline != FD->IsInline) {
3190 // FIXME: [dcl.fct.spec]p4:
3191 // If a function with external linkage is declared inline in one
3192 // translation unit, it shall be declared inline in all translation
3193 // units in which it appears.
3195 // Be careful of this case:
3198 // template<typename T> struct X { void f(); };
3199 // template<typename T> inline void X<T>::f() {}
3201 // module B instantiates the declaration of X<int>::f
3202 // module C instantiates the definition of X<int>::f
3204 // If module B and C are merged, we do not have a violation of this rule.
3205 FD->IsInline = true;
3208 // If we need to propagate an exception specification along the redecl
3209 // chain, make a note of that so that we can do so later.
3210 auto *FPT = FD->getType()->getAs<FunctionProtoType>();
3211 auto *PrevFPT = PrevFD->getType()->getAs<FunctionProtoType>();
3212 if (FPT && PrevFPT) {
3213 bool IsUnresolved = isUnresolvedExceptionSpec(FPT->getExceptionSpecType());
3214 bool WasUnresolved =
3215 isUnresolvedExceptionSpec(PrevFPT->getExceptionSpecType());
3216 if (IsUnresolved != WasUnresolved)
3217 Reader.PendingExceptionSpecUpdates.insert(
3218 std::make_pair(Canon, IsUnresolved ? PrevFD : FD));
3221 } // end namespace clang
3223 void ASTDeclReader::attachPreviousDeclImpl(ASTReader &Reader, ...) {
3224 llvm_unreachable("attachPreviousDecl on non-redeclarable declaration");
3227 /// Inherit the default template argument from \p From to \p To. Returns
3228 /// \c false if there is no default template for \p From.
3229 template <typename ParmDecl>
3230 static bool inheritDefaultTemplateArgument(ASTContext &Context, ParmDecl *From,
3232 auto *To = cast<ParmDecl>(ToD);
3233 if (!From->hasDefaultArgument())
3235 To->setInheritedDefaultArgument(Context, From);
3239 static void inheritDefaultTemplateArguments(ASTContext &Context,
3242 auto *FromTP = From->getTemplateParameters();
3243 auto *ToTP = To->getTemplateParameters();
3244 assert(FromTP->size() == ToTP->size() && "merged mismatched templates?");
3246 for (unsigned I = 0, N = FromTP->size(); I != N; ++I) {
3247 NamedDecl *FromParam = FromTP->getParam(N - I - 1);
3248 if (FromParam->isParameterPack())
3250 NamedDecl *ToParam = ToTP->getParam(N - I - 1);
3252 if (auto *FTTP = dyn_cast<TemplateTypeParmDecl>(FromParam)) {
3253 if (!inheritDefaultTemplateArgument(Context, FTTP, ToParam))
3255 } else if (auto *FNTTP = dyn_cast<NonTypeTemplateParmDecl>(FromParam)) {
3256 if (!inheritDefaultTemplateArgument(Context, FNTTP, ToParam))
3259 if (!inheritDefaultTemplateArgument(
3260 Context, cast<TemplateTemplateParmDecl>(FromParam), ToParam))
3266 void ASTDeclReader::attachPreviousDecl(ASTReader &Reader, Decl *D,
3267 Decl *Previous, Decl *Canon) {
3268 assert(D && Previous);
3270 switch (D->getKind()) {
3271 #define ABSTRACT_DECL(TYPE)
3272 #define DECL(TYPE, BASE) \
3274 attachPreviousDeclImpl(Reader, cast<TYPE##Decl>(D), Previous, Canon); \
3276 #include "clang/AST/DeclNodes.inc"
3279 // If the declaration was visible in one module, a redeclaration of it in
3280 // another module remains visible even if it wouldn't be visible by itself.
3282 // FIXME: In this case, the declaration should only be visible if a module
3283 // that makes it visible has been imported.
3284 D->IdentifierNamespace |=
3285 Previous->IdentifierNamespace &
3286 (Decl::IDNS_Ordinary | Decl::IDNS_Tag | Decl::IDNS_Type);
3288 // If the declaration declares a template, it may inherit default arguments
3289 // from the previous declaration.
3290 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
3291 inheritDefaultTemplateArguments(Reader.getContext(),
3292 cast<TemplateDecl>(Previous), TD);
3295 template<typename DeclT>
3296 void ASTDeclReader::attachLatestDeclImpl(Redeclarable<DeclT> *D, Decl *Latest) {
3297 D->RedeclLink.setLatest(cast<DeclT>(Latest));
3299 void ASTDeclReader::attachLatestDeclImpl(...) {
3300 llvm_unreachable("attachLatestDecl on non-redeclarable declaration");
3303 void ASTDeclReader::attachLatestDecl(Decl *D, Decl *Latest) {
3304 assert(D && Latest);
3306 switch (D->getKind()) {
3307 #define ABSTRACT_DECL(TYPE)
3308 #define DECL(TYPE, BASE) \
3310 attachLatestDeclImpl(cast<TYPE##Decl>(D), Latest); \
3312 #include "clang/AST/DeclNodes.inc"
3316 template<typename DeclT>
3317 void ASTDeclReader::markIncompleteDeclChainImpl(Redeclarable<DeclT> *D) {
3318 D->RedeclLink.markIncomplete();
3320 void ASTDeclReader::markIncompleteDeclChainImpl(...) {
3321 llvm_unreachable("markIncompleteDeclChain on non-redeclarable declaration");
3324 void ASTReader::markIncompleteDeclChain(Decl *D) {
3325 switch (D->getKind()) {
3326 #define ABSTRACT_DECL(TYPE)
3327 #define DECL(TYPE, BASE) \
3329 ASTDeclReader::markIncompleteDeclChainImpl(cast<TYPE##Decl>(D)); \
3331 #include "clang/AST/DeclNodes.inc"
3335 /// \brief Read the declaration at the given offset from the AST file.
3336 Decl *ASTReader::ReadDeclRecord(DeclID ID) {
3337 unsigned Index = ID - NUM_PREDEF_DECL_IDS;
3338 SourceLocation DeclLoc;
3339 RecordLocation Loc = DeclCursorForID(ID, DeclLoc);
3340 llvm::BitstreamCursor &DeclsCursor = Loc.F->DeclsCursor;
3341 // Keep track of where we are in the stream, then jump back there
3342 // after reading this declaration.
3343 SavedStreamPosition SavedPosition(DeclsCursor);
3345 ReadingKindTracker ReadingKind(Read_Decl, *this);
3347 // Note that we are loading a declaration record.
3348 Deserializing ADecl(this);
3350 DeclsCursor.JumpToBit(Loc.Offset);
3351 ASTRecordReader Record(*this, *Loc.F);
3352 ASTDeclReader Reader(*this, Record, Loc, ID, DeclLoc);
3353 unsigned Code = DeclsCursor.ReadCode();
3356 switch ((DeclCode)Record.readRecord(DeclsCursor, Code)) {
3357 case DECL_CONTEXT_LEXICAL:
3358 case DECL_CONTEXT_VISIBLE:
3359 llvm_unreachable("Record cannot be de-serialized with ReadDeclRecord");
3361 D = TypedefDecl::CreateDeserialized(Context, ID);
3363 case DECL_TYPEALIAS:
3364 D = TypeAliasDecl::CreateDeserialized(Context, ID);
3367 D = EnumDecl::CreateDeserialized(Context, ID);
3370 D = RecordDecl::CreateDeserialized(Context, ID);
3372 case DECL_ENUM_CONSTANT:
3373 D = EnumConstantDecl::CreateDeserialized(Context, ID);
3376 D = FunctionDecl::CreateDeserialized(Context, ID);
3378 case DECL_LINKAGE_SPEC:
3379 D = LinkageSpecDecl::CreateDeserialized(Context, ID);
3382 D = ExportDecl::CreateDeserialized(Context, ID);
3385 D = LabelDecl::CreateDeserialized(Context, ID);
3387 case DECL_NAMESPACE:
3388 D = NamespaceDecl::CreateDeserialized(Context, ID);
3390 case DECL_NAMESPACE_ALIAS:
3391 D = NamespaceAliasDecl::CreateDeserialized(Context, ID);
3394 D = UsingDecl::CreateDeserialized(Context, ID);
3396 case DECL_USING_PACK:
3397 D = UsingPackDecl::CreateDeserialized(Context, ID, Record.readInt());
3399 case DECL_USING_SHADOW:
3400 D = UsingShadowDecl::CreateDeserialized(Context, ID);
3402 case DECL_CONSTRUCTOR_USING_SHADOW:
3403 D = ConstructorUsingShadowDecl::CreateDeserialized(Context, ID);
3405 case DECL_USING_DIRECTIVE:
3406 D = UsingDirectiveDecl::CreateDeserialized(Context, ID);
3408 case DECL_UNRESOLVED_USING_VALUE:
3409 D = UnresolvedUsingValueDecl::CreateDeserialized(Context, ID);
3411 case DECL_UNRESOLVED_USING_TYPENAME:
3412 D = UnresolvedUsingTypenameDecl::CreateDeserialized(Context, ID);
3414 case DECL_CXX_RECORD:
3415 D = CXXRecordDecl::CreateDeserialized(Context, ID);
3417 case DECL_CXX_DEDUCTION_GUIDE:
3418 D = CXXDeductionGuideDecl::CreateDeserialized(Context, ID);
3420 case DECL_CXX_METHOD:
3421 D = CXXMethodDecl::CreateDeserialized(Context, ID);
3423 case DECL_CXX_CONSTRUCTOR:
3424 D = CXXConstructorDecl::CreateDeserialized(Context, ID, false);
3426 case DECL_CXX_INHERITED_CONSTRUCTOR:
3427 D = CXXConstructorDecl::CreateDeserialized(Context, ID, true);
3429 case DECL_CXX_DESTRUCTOR:
3430 D = CXXDestructorDecl::CreateDeserialized(Context, ID);
3432 case DECL_CXX_CONVERSION:
3433 D = CXXConversionDecl::CreateDeserialized(Context, ID);
3435 case DECL_ACCESS_SPEC:
3436 D = AccessSpecDecl::CreateDeserialized(Context, ID);
3439 D = FriendDecl::CreateDeserialized(Context, ID, Record.readInt());
3441 case DECL_FRIEND_TEMPLATE:
3442 D = FriendTemplateDecl::CreateDeserialized(Context, ID);
3444 case DECL_CLASS_TEMPLATE:
3445 D = ClassTemplateDecl::CreateDeserialized(Context, ID);
3447 case DECL_CLASS_TEMPLATE_SPECIALIZATION:
3448 D = ClassTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3450 case DECL_CLASS_TEMPLATE_PARTIAL_SPECIALIZATION:
3451 D = ClassTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3453 case DECL_VAR_TEMPLATE:
3454 D = VarTemplateDecl::CreateDeserialized(Context, ID);
3456 case DECL_VAR_TEMPLATE_SPECIALIZATION:
3457 D = VarTemplateSpecializationDecl::CreateDeserialized(Context, ID);
3459 case DECL_VAR_TEMPLATE_PARTIAL_SPECIALIZATION:
3460 D = VarTemplatePartialSpecializationDecl::CreateDeserialized(Context, ID);
3462 case DECL_CLASS_SCOPE_FUNCTION_SPECIALIZATION:
3463 D = ClassScopeFunctionSpecializationDecl::CreateDeserialized(Context, ID);
3465 case DECL_FUNCTION_TEMPLATE:
3466 D = FunctionTemplateDecl::CreateDeserialized(Context, ID);
3468 case DECL_TEMPLATE_TYPE_PARM:
3469 D = TemplateTypeParmDecl::CreateDeserialized(Context, ID);
3471 case DECL_NON_TYPE_TEMPLATE_PARM:
3472 D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID);
3474 case DECL_EXPANDED_NON_TYPE_TEMPLATE_PARM_PACK:
3475 D = NonTypeTemplateParmDecl::CreateDeserialized(Context, ID,
3478 case DECL_TEMPLATE_TEMPLATE_PARM:
3479 D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID);
3481 case DECL_EXPANDED_TEMPLATE_TEMPLATE_PARM_PACK:
3482 D = TemplateTemplateParmDecl::CreateDeserialized(Context, ID,
3485 case DECL_TYPE_ALIAS_TEMPLATE:
3486 D = TypeAliasTemplateDecl::CreateDeserialized(Context, ID);
3488 case DECL_STATIC_ASSERT:
3489 D = StaticAssertDecl::CreateDeserialized(Context, ID);
3491 case DECL_OBJC_METHOD:
3492 D = ObjCMethodDecl::CreateDeserialized(Context, ID);
3494 case DECL_OBJC_INTERFACE:
3495 D = ObjCInterfaceDecl::CreateDeserialized(Context, ID);
3497 case DECL_OBJC_IVAR:
3498 D = ObjCIvarDecl::CreateDeserialized(Context, ID);
3500 case DECL_OBJC_PROTOCOL:
3501 D = ObjCProtocolDecl::CreateDeserialized(Context, ID);
3503 case DECL_OBJC_AT_DEFS_FIELD:
3504 D = ObjCAtDefsFieldDecl::CreateDeserialized(Context, ID);
3506 case DECL_OBJC_CATEGORY:
3507 D = ObjCCategoryDecl::CreateDeserialized(Context, ID);
3509 case DECL_OBJC_CATEGORY_IMPL:
3510 D = ObjCCategoryImplDecl::CreateDeserialized(Context, ID);
3512 case DECL_OBJC_IMPLEMENTATION:
3513 D = ObjCImplementationDecl::CreateDeserialized(Context, ID);
3515 case DECL_OBJC_COMPATIBLE_ALIAS:
3516 D = ObjCCompatibleAliasDecl::CreateDeserialized(Context, ID);
3518 case DECL_OBJC_PROPERTY:
3519 D = ObjCPropertyDecl::CreateDeserialized(Context, ID);
3521 case DECL_OBJC_PROPERTY_IMPL:
3522 D = ObjCPropertyImplDecl::CreateDeserialized(Context, ID);
3525 D = FieldDecl::CreateDeserialized(Context, ID);
3527 case DECL_INDIRECTFIELD:
3528 D = IndirectFieldDecl::CreateDeserialized(Context, ID);
3531 D = VarDecl::CreateDeserialized(Context, ID);
3533 case DECL_IMPLICIT_PARAM:
3534 D = ImplicitParamDecl::CreateDeserialized(Context, ID);
3537 D = ParmVarDecl::CreateDeserialized(Context, ID);
3539 case DECL_DECOMPOSITION:
3540 D = DecompositionDecl::CreateDeserialized(Context, ID, Record.readInt());
3543 D = BindingDecl::CreateDeserialized(Context, ID);
3545 case DECL_FILE_SCOPE_ASM:
3546 D = FileScopeAsmDecl::CreateDeserialized(Context, ID);
3549 D = BlockDecl::CreateDeserialized(Context, ID);
3551 case DECL_MS_PROPERTY:
3552 D = MSPropertyDecl::CreateDeserialized(Context, ID);
3555 D = CapturedDecl::CreateDeserialized(Context, ID, Record.readInt());
3557 case DECL_CXX_BASE_SPECIFIERS:
3558 Error("attempt to read a C++ base-specifier record as a declaration");
3560 case DECL_CXX_CTOR_INITIALIZERS:
3561 Error("attempt to read a C++ ctor initializer record as a declaration");
3564 // Note: last entry of the ImportDecl record is the number of stored source
3566 D = ImportDecl::CreateDeserialized(Context, ID, Record.back());
3568 case DECL_OMP_THREADPRIVATE:
3569 D = OMPThreadPrivateDecl::CreateDeserialized(Context, ID, Record.readInt());
3571 case DECL_OMP_DECLARE_REDUCTION:
3572 D = OMPDeclareReductionDecl::CreateDeserialized(Context, ID);
3574 case DECL_OMP_CAPTUREDEXPR:
3575 D = OMPCapturedExprDecl::CreateDeserialized(Context, ID);
3577 case DECL_PRAGMA_COMMENT:
3578 D = PragmaCommentDecl::CreateDeserialized(Context, ID, Record.readInt());
3580 case DECL_PRAGMA_DETECT_MISMATCH:
3581 D = PragmaDetectMismatchDecl::CreateDeserialized(Context, ID,
3585 D = EmptyDecl::CreateDeserialized(Context, ID);
3587 case DECL_OBJC_TYPE_PARAM:
3588 D = ObjCTypeParamDecl::CreateDeserialized(Context, ID);
3592 assert(D && "Unknown declaration reading AST file");
3593 LoadedDecl(Index, D);
3594 // Set the DeclContext before doing any deserialization, to make sure internal
3595 // calls to Decl::getASTContext() by Decl's methods will find the
3596 // TranslationUnitDecl without crashing.
3597 D->setDeclContext(Context.getTranslationUnitDecl());
3600 // If this declaration is also a declaration context, get the
3601 // offsets for its tables of lexical and visible declarations.
3602 if (DeclContext *DC = dyn_cast<DeclContext>(D)) {
3603 std::pair<uint64_t, uint64_t> Offsets = Reader.VisitDeclContext(DC);
3604 if (Offsets.first &&
3605 ReadLexicalDeclContextStorage(*Loc.F, DeclsCursor, Offsets.first, DC))
3607 if (Offsets.second &&
3608 ReadVisibleDeclContextStorage(*Loc.F, DeclsCursor, Offsets.second, ID))
3611 assert(Record.getIdx() == Record.size());
3613 // Load any relevant update records.
3614 PendingUpdateRecords.push_back(
3615 PendingUpdateRecord(ID, D, /*JustLoaded=*/true));
3617 // Load the categories after recursive loading is finished.
3618 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(D))
3619 // If we already have a definition when deserializing the ObjCInterfaceDecl,
3620 // we put the Decl in PendingDefinitions so we can pull the categories here.
3621 if (Class->isThisDeclarationADefinition() ||
3622 PendingDefinitions.count(Class))
3623 loadObjCCategories(ID, Class);
3625 // If we have deserialized a declaration that has a definition the
3626 // AST consumer might need to know about, queue it.
3627 // We don't pass it to the consumer immediately because we may be in recursive
3628 // loading, and some declarations may still be initializing.
3629 PotentiallyInterestingDecls.push_back(
3630 InterestingDecl(D, Reader.hasPendingBody()));
3635 void ASTReader::PassInterestingDeclsToConsumer() {
3638 if (PassingDeclsToConsumer)
3641 // Guard variable to avoid recursively redoing the process of passing
3642 // decls to consumer.
3643 SaveAndRestore<bool> GuardPassingDeclsToConsumer(PassingDeclsToConsumer,
3646 // Ensure that we've loaded all potentially-interesting declarations
3647 // that need to be eagerly loaded.
3648 for (auto ID : EagerlyDeserializedDecls)
3650 EagerlyDeserializedDecls.clear();
3652 while (!PotentiallyInterestingDecls.empty()) {
3653 InterestingDecl D = PotentiallyInterestingDecls.front();
3654 PotentiallyInterestingDecls.pop_front();
3655 if (isConsumerInterestedIn(Context, D.getDecl(), D.hasPendingBody()))
3656 PassInterestingDeclToConsumer(D.getDecl());
3660 void ASTReader::loadDeclUpdateRecords(PendingUpdateRecord &Record) {
3661 // The declaration may have been modified by files later in the chain.
3662 // If this is the case, read the record containing the updates from each file
3663 // and pass it to ASTDeclReader to make the modifications.
3664 serialization::GlobalDeclID ID = Record.ID;
3666 ProcessingUpdatesRAIIObj ProcessingUpdates(*this);
3667 DeclUpdateOffsetsMap::iterator UpdI = DeclUpdateOffsets.find(ID);
3668 if (UpdI != DeclUpdateOffsets.end()) {
3669 auto UpdateOffsets = std::move(UpdI->second);
3670 DeclUpdateOffsets.erase(UpdI);
3672 // Check if this decl was interesting to the consumer. If we just loaded
3673 // the declaration, then we know it was interesting and we skip the call
3674 // to isConsumerInterestedIn because it is unsafe to call in the
3675 // current ASTReader state.
3676 bool WasInteresting =
3677 Record.JustLoaded || isConsumerInterestedIn(Context, D, false);
3678 for (auto &FileAndOffset : UpdateOffsets) {
3679 ModuleFile *F = FileAndOffset.first;
3680 uint64_t Offset = FileAndOffset.second;
3681 llvm::BitstreamCursor &Cursor = F->DeclsCursor;
3682 SavedStreamPosition SavedPosition(Cursor);
3683 Cursor.JumpToBit(Offset);
3684 unsigned Code = Cursor.ReadCode();
3685 ASTRecordReader Record(*this, *F);
3686 unsigned RecCode = Record.readRecord(Cursor, Code);
3688 assert(RecCode == DECL_UPDATES && "Expected DECL_UPDATES record!");
3690 ASTDeclReader Reader(*this, Record, RecordLocation(F, Offset), ID,
3692 Reader.UpdateDecl(D);
3694 // We might have made this declaration interesting. If so, remember that
3695 // we need to hand it off to the consumer.
3696 if (!WasInteresting &&
3697 isConsumerInterestedIn(Context, D, Reader.hasPendingBody())) {
3698 PotentiallyInterestingDecls.push_back(
3699 InterestingDecl(D, Reader.hasPendingBody()));
3700 WasInteresting = true;
3705 // Load the pending visible updates for this decl context, if it has any.
3706 auto I = PendingVisibleUpdates.find(ID);
3707 if (I != PendingVisibleUpdates.end()) {
3708 auto VisibleUpdates = std::move(I->second);
3709 PendingVisibleUpdates.erase(I);
3711 auto *DC = cast<DeclContext>(D)->getPrimaryContext();
3712 for (const PendingVisibleUpdate &Update : VisibleUpdates)
3713 Lookups[DC].Table.add(
3714 Update.Mod, Update.Data,
3715 reader::ASTDeclContextNameLookupTrait(*this, *Update.Mod));
3716 DC->setHasExternalVisibleStorage(true);
3720 void ASTReader::loadPendingDeclChain(Decl *FirstLocal, uint64_t LocalOffset) {
3721 // Attach FirstLocal to the end of the decl chain.
3722 Decl *CanonDecl = FirstLocal->getCanonicalDecl();
3723 if (FirstLocal != CanonDecl) {
3724 Decl *PrevMostRecent = ASTDeclReader::getMostRecentDecl(CanonDecl);
3725 ASTDeclReader::attachPreviousDecl(
3726 *this, FirstLocal, PrevMostRecent ? PrevMostRecent : CanonDecl,
3731 ASTDeclReader::attachLatestDecl(CanonDecl, FirstLocal);
3735 // Load the list of other redeclarations from this module file.
3736 ModuleFile *M = getOwningModuleFile(FirstLocal);
3737 assert(M && "imported decl from no module file");
3739 llvm::BitstreamCursor &Cursor = M->DeclsCursor;
3740 SavedStreamPosition SavedPosition(Cursor);
3741 Cursor.JumpToBit(LocalOffset);
3744 unsigned Code = Cursor.ReadCode();
3745 unsigned RecCode = Cursor.readRecord(Code, Record);
3747 assert(RecCode == LOCAL_REDECLARATIONS && "expected LOCAL_REDECLARATIONS record!");
3749 // FIXME: We have several different dispatches on decl kind here; maybe
3750 // we should instead generate one loop per kind and dispatch up-front?
3751 Decl *MostRecent = FirstLocal;
3752 for (unsigned I = 0, N = Record.size(); I != N; ++I) {
3753 auto *D = GetLocalDecl(*M, Record[N - I - 1]);
3754 ASTDeclReader::attachPreviousDecl(*this, D, MostRecent, CanonDecl);
3757 ASTDeclReader::attachLatestDecl(CanonDecl, MostRecent);
3761 /// \brief Given an ObjC interface, goes through the modules and links to the
3762 /// interface all the categories for it.
3763 class ObjCCategoriesVisitor {
3765 ObjCInterfaceDecl *Interface;
3766 llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized;
3767 ObjCCategoryDecl *Tail;
3768 llvm::DenseMap<DeclarationName, ObjCCategoryDecl *> NameCategoryMap;
3769 serialization::GlobalDeclID InterfaceID;
3770 unsigned PreviousGeneration;
3772 void add(ObjCCategoryDecl *Cat) {
3773 // Only process each category once.
3774 if (!Deserialized.erase(Cat))
3777 // Check for duplicate categories.
3778 if (Cat->getDeclName()) {
3779 ObjCCategoryDecl *&Existing = NameCategoryMap[Cat->getDeclName()];
3781 Reader.getOwningModuleFile(Existing)
3782 != Reader.getOwningModuleFile(Cat)) {
3783 // FIXME: We should not warn for duplicates in diamond:
3791 // If there are duplicates in ML/MR, there will be warning when
3792 // creating MB *and* when importing MB. We should not warn when
3794 Reader.Diag(Cat->getLocation(), diag::warn_dup_category_def)
3795 << Interface->getDeclName() << Cat->getDeclName();
3796 Reader.Diag(Existing->getLocation(), diag::note_previous_definition);
3797 } else if (!Existing) {
3798 // Record this category.
3803 // Add this category to the end of the chain.
3805 ASTDeclReader::setNextObjCCategory(Tail, Cat);
3807 Interface->setCategoryListRaw(Cat);
3812 ObjCCategoriesVisitor(ASTReader &Reader,
3813 ObjCInterfaceDecl *Interface,
3814 llvm::SmallPtrSetImpl<ObjCCategoryDecl *> &Deserialized,
3815 serialization::GlobalDeclID InterfaceID,
3816 unsigned PreviousGeneration)
3817 : Reader(Reader), Interface(Interface), Deserialized(Deserialized),
3818 Tail(nullptr), InterfaceID(InterfaceID),
3819 PreviousGeneration(PreviousGeneration)
3821 // Populate the name -> category map with the set of known categories.
3822 for (auto *Cat : Interface->known_categories()) {
3823 if (Cat->getDeclName())
3824 NameCategoryMap[Cat->getDeclName()] = Cat;
3826 // Keep track of the tail of the category list.
3831 bool operator()(ModuleFile &M) {
3832 // If we've loaded all of the category information we care about from
3833 // this module file, we're done.
3834 if (M.Generation <= PreviousGeneration)
3837 // Map global ID of the definition down to the local ID used in this
3838 // module file. If there is no such mapping, we'll find nothing here
3839 // (or in any module it imports).
3840 DeclID LocalID = Reader.mapGlobalIDToModuleFileGlobalID(M, InterfaceID);
3844 // Perform a binary search to find the local redeclarations for this
3845 // declaration (if any).
3846 const ObjCCategoriesInfo Compare = { LocalID, 0 };
3847 const ObjCCategoriesInfo *Result
3848 = std::lower_bound(M.ObjCCategoriesMap,
3849 M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap,
3851 if (Result == M.ObjCCategoriesMap + M.LocalNumObjCCategoriesInMap ||
3852 Result->DefinitionID != LocalID) {
3853 // We didn't find anything. If the class definition is in this module
3854 // file, then the module files it depends on cannot have any categories,
3855 // so suppress further lookup.
3856 return Reader.isDeclIDFromModule(InterfaceID, M);
3859 // We found something. Dig out all of the categories.
3860 unsigned Offset = Result->Offset;
3861 unsigned N = M.ObjCCategories[Offset];
3862 M.ObjCCategories[Offset++] = 0; // Don't try to deserialize again
3863 for (unsigned I = 0; I != N; ++I)
3864 add(cast_or_null<ObjCCategoryDecl>(
3865 Reader.GetLocalDecl(M, M.ObjCCategories[Offset++])));
3869 } // end anonymous namespace
3871 void ASTReader::loadObjCCategories(serialization::GlobalDeclID ID,
3872 ObjCInterfaceDecl *D,
3873 unsigned PreviousGeneration) {
3874 ObjCCategoriesVisitor Visitor(*this, D, CategoriesDeserialized, ID,
3875 PreviousGeneration);
3876 ModuleMgr.visit(Visitor);
3879 template<typename DeclT, typename Fn>
3880 static void forAllLaterRedecls(DeclT *D, Fn F) {
3883 // Check whether we've already merged D into its redeclaration chain.
3884 // MostRecent may or may not be nullptr if D has not been merged. If
3885 // not, walk the merged redecl chain and see if it's there.
3886 auto *MostRecent = D->getMostRecentDecl();
3888 for (auto *Redecl = MostRecent; Redecl && !Found;
3889 Redecl = Redecl->getPreviousDecl())
3890 Found = (Redecl == D);
3892 // If this declaration is merged, apply the functor to all later decls.
3894 for (auto *Redecl = MostRecent; Redecl != D;
3895 Redecl = Redecl->getPreviousDecl())
3900 void ASTDeclReader::UpdateDecl(Decl *D) {
3901 while (Record.getIdx() < Record.size()) {
3902 switch ((DeclUpdateKind)Record.readInt()) {
3903 case UPD_CXX_ADDED_IMPLICIT_MEMBER: {
3904 auto *RD = cast<CXXRecordDecl>(D);
3905 // FIXME: If we also have an update record for instantiating the
3906 // definition of D, we need that to happen before we get here.
3907 Decl *MD = Record.readDecl();
3908 assert(MD && "couldn't read decl from update record");
3909 // FIXME: We should call addHiddenDecl instead, to add the member
3910 // to its DeclContext.
3911 RD->addedMember(MD);
3915 case UPD_CXX_ADDED_TEMPLATE_SPECIALIZATION:
3916 // It will be added to the template's specializations set when loaded.
3917 (void)Record.readDecl();
3920 case UPD_CXX_ADDED_ANONYMOUS_NAMESPACE: {
3921 NamespaceDecl *Anon = ReadDeclAs<NamespaceDecl>();
3923 // Each module has its own anonymous namespace, which is disjoint from
3924 // any other module's anonymous namespaces, so don't attach the anonymous
3925 // namespace at all.
3926 if (!Record.isModule()) {
3927 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(D))
3928 TU->setAnonymousNamespace(Anon);
3930 cast<NamespaceDecl>(D)->setAnonymousNamespace(Anon);
3935 case UPD_CXX_INSTANTIATED_STATIC_DATA_MEMBER: {
3936 VarDecl *VD = cast<VarDecl>(D);
3937 VD->getMemberSpecializationInfo()->setPointOfInstantiation(
3938 ReadSourceLocation());
3939 uint64_t Val = Record.readInt();
3940 if (Val && !VD->getInit()) {
3941 VD->setInit(Record.readExpr());
3942 if (Val > 1) { // IsInitKnownICE = 1, IsInitNotICE = 2, IsInitICE = 3
3943 EvaluatedStmt *Eval = VD->ensureEvaluatedStmt();
3944 Eval->CheckedICE = true;
3945 Eval->IsICE = Val == 3;
3951 case UPD_CXX_INSTANTIATED_DEFAULT_ARGUMENT: {
3952 auto Param = cast<ParmVarDecl>(D);
3954 // We have to read the default argument regardless of whether we use it
3955 // so that hypothetical further update records aren't messed up.
3956 // TODO: Add a function to skip over the next expr record.
3957 auto DefaultArg = Record.readExpr();
3959 // Only apply the update if the parameter still has an uninstantiated
3960 // default argument.
3961 if (Param->hasUninstantiatedDefaultArg())
3962 Param->setDefaultArg(DefaultArg);
3966 case UPD_CXX_INSTANTIATED_DEFAULT_MEMBER_INITIALIZER: {
3967 auto FD = cast<FieldDecl>(D);
3968 auto DefaultInit = Record.readExpr();
3970 // Only apply the update if the field still has an uninstantiated
3971 // default member initializer.
3972 if (FD->hasInClassInitializer() && !FD->getInClassInitializer()) {
3974 FD->setInClassInitializer(DefaultInit);
3976 // Instantiation failed. We can get here if we serialized an AST for
3977 // an invalid program.
3978 FD->removeInClassInitializer();
3983 case UPD_CXX_ADDED_FUNCTION_DEFINITION: {
3984 FunctionDecl *FD = cast<FunctionDecl>(D);
3985 if (Reader.PendingBodies[FD]) {
3986 // FIXME: Maybe check for ODR violations.
3987 // It's safe to stop now because this update record is always last.
3991 if (Record.readInt()) {
3992 // Maintain AST consistency: any later redeclarations of this function
3993 // are inline if this one is. (We might have merged another declaration
3995 forAllLaterRedecls(FD, [](FunctionDecl *FD) {
3996 FD->setImplicitlyInline();
3999 FD->setInnerLocStart(ReadSourceLocation());
4000 ReadFunctionDefinition(FD);
4001 assert(Record.getIdx() == Record.size() && "lazy body must be last");
4005 case UPD_CXX_INSTANTIATED_CLASS_DEFINITION: {
4006 auto *RD = cast<CXXRecordDecl>(D);
4007 auto *OldDD = RD->getCanonicalDecl()->DefinitionData;
4008 bool HadRealDefinition =
4009 OldDD && (OldDD->Definition != RD ||
4010 !Reader.PendingFakeDefinitionData.count(OldDD));
4011 ReadCXXRecordDefinition(RD, /*Update*/true);
4013 // Visible update is handled separately.
4014 uint64_t LexicalOffset = ReadLocalOffset();
4015 if (!HadRealDefinition && LexicalOffset) {
4016 Record.readLexicalDeclContextStorage(LexicalOffset, RD);
4017 Reader.PendingFakeDefinitionData.erase(OldDD);
4020 auto TSK = (TemplateSpecializationKind)Record.readInt();
4021 SourceLocation POI = ReadSourceLocation();
4022 if (MemberSpecializationInfo *MSInfo =
4023 RD->getMemberSpecializationInfo()) {
4024 MSInfo->setTemplateSpecializationKind(TSK);
4025 MSInfo->setPointOfInstantiation(POI);
4027 ClassTemplateSpecializationDecl *Spec =
4028 cast<ClassTemplateSpecializationDecl>(RD);
4029 Spec->setTemplateSpecializationKind(TSK);
4030 Spec->setPointOfInstantiation(POI);
4032 if (Record.readInt()) {
4034 ReadDeclAs<ClassTemplatePartialSpecializationDecl>();
4035 SmallVector<TemplateArgument, 8> TemplArgs;
4036 Record.readTemplateArgumentList(TemplArgs);
4037 auto *TemplArgList = TemplateArgumentList::CreateCopy(
4038 Reader.getContext(), TemplArgs);
4040 // FIXME: If we already have a partial specialization set,
4041 // check that it matches.
4042 if (!Spec->getSpecializedTemplateOrPartial()
4043 .is<ClassTemplatePartialSpecializationDecl *>())
4044 Spec->setInstantiationOf(PartialSpec, TemplArgList);
4048 RD->setTagKind((TagTypeKind)Record.readInt());
4049 RD->setLocation(ReadSourceLocation());
4050 RD->setLocStart(ReadSourceLocation());
4051 RD->setBraceRange(ReadSourceRange());
4053 if (Record.readInt()) {
4055 Record.readAttributes(Attrs);
4056 // If the declaration already has attributes, we assume that some other
4057 // AST file already loaded them.
4059 D->setAttrsImpl(Attrs, Reader.getContext());
4064 case UPD_CXX_RESOLVED_DTOR_DELETE: {
4065 // Set the 'operator delete' directly to avoid emitting another update
4067 auto *Del = ReadDeclAs<FunctionDecl>();
4068 auto *First = cast<CXXDestructorDecl>(D->getCanonicalDecl());
4069 // FIXME: Check consistency if we have an old and new operator delete.
4070 if (!First->OperatorDelete)
4071 First->OperatorDelete = Del;
4075 case UPD_CXX_RESOLVED_EXCEPTION_SPEC: {
4076 FunctionProtoType::ExceptionSpecInfo ESI;
4077 SmallVector<QualType, 8> ExceptionStorage;
4078 Record.readExceptionSpec(ExceptionStorage, ESI);
4080 // Update this declaration's exception specification, if needed.
4081 auto *FD = cast<FunctionDecl>(D);
4082 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
4083 // FIXME: If the exception specification is already present, check that it
4085 if (isUnresolvedExceptionSpec(FPT->getExceptionSpecType())) {
4086 FD->setType(Reader.Context.getFunctionType(
4087 FPT->getReturnType(), FPT->getParamTypes(),
4088 FPT->getExtProtoInfo().withExceptionSpec(ESI)));
4090 // When we get to the end of deserializing, see if there are other decls
4091 // that we need to propagate this exception specification onto.
4092 Reader.PendingExceptionSpecUpdates.insert(
4093 std::make_pair(FD->getCanonicalDecl(), FD));
4098 case UPD_CXX_DEDUCED_RETURN_TYPE: {
4099 // FIXME: Also do this when merging redecls.
4100 QualType DeducedResultType = Record.readType();
4101 for (auto *Redecl : merged_redecls(D)) {
4102 // FIXME: If the return type is already deduced, check that it matches.
4103 FunctionDecl *FD = cast<FunctionDecl>(Redecl);
4104 Reader.Context.adjustDeducedFunctionResultType(FD, DeducedResultType);
4109 case UPD_DECL_MARKED_USED: {
4110 // Maintain AST consistency: any later redeclarations are used too.
4111 D->markUsed(Reader.Context);
4115 case UPD_MANGLING_NUMBER:
4116 Reader.Context.setManglingNumber(cast<NamedDecl>(D), Record.readInt());
4119 case UPD_STATIC_LOCAL_NUMBER:
4120 Reader.Context.setStaticLocalNumber(cast<VarDecl>(D), Record.readInt());
4123 case UPD_DECL_MARKED_OPENMP_THREADPRIVATE:
4124 D->addAttr(OMPThreadPrivateDeclAttr::CreateImplicit(
4125 Reader.Context, ReadSourceRange()));
4128 case UPD_DECL_EXPORTED: {
4129 unsigned SubmoduleID = readSubmoduleID();
4130 auto *Exported = cast<NamedDecl>(D);
4131 if (auto *TD = dyn_cast<TagDecl>(Exported))
4132 Exported = TD->getDefinition();
4133 Module *Owner = SubmoduleID ? Reader.getSubmodule(SubmoduleID) : nullptr;
4134 if (Reader.getContext().getLangOpts().ModulesLocalVisibility) {
4135 Reader.getContext().mergeDefinitionIntoModule(cast<NamedDecl>(Exported),
4137 Reader.PendingMergedDefinitionsToDeduplicate.insert(
4138 cast<NamedDecl>(Exported));
4139 } else if (Owner && Owner->NameVisibility != Module::AllVisible) {
4140 // If Owner is made visible at some later point, make this declaration
4142 Reader.HiddenNamesMap[Owner].push_back(Exported);
4144 // The declaration is now visible.
4145 Exported->setVisibleDespiteOwningModule();
4150 case UPD_DECL_MARKED_OPENMP_DECLARETARGET:
4151 case UPD_ADDED_ATTR_TO_RECORD:
4153 Record.readAttributes(Attrs);
4154 assert(Attrs.size() == 1);
4155 D->addAttr(Attrs[0]);